import numpy as np
a = np.array([[1,2,3],
[4,5,6],
[7,8,9]])
print('a.shape = ',a.shape)
b = a[:,0]
print('b.shape = ',b.shape)
c = np.array([[1],[4],[7]])
print('c.shape = ',c.shape)
print('np.squeeze(c).shape = ',np.squeeze(c).shape)
# output:
# a.shape = (3, 3)
# b.shape = (3,)
# c.shape = (3, 1)
# np.squeeze(c).shape = (3,)
显然输出a的维度是(3, 3)。
如果想取出矩阵a的第一列,期望输出的b.shape应该是(3, 1),这样的维度在以后矩阵的乘法运算中会减少出bug的几率,但实际上输出的维度是(3, ),可见维度大小为1的直接被抛弃。类似执行了np.squeeze(),参见上面代码。这种维度丢失的情况好像只在矩阵的切片有一个维度是1的情况下出现。下面介绍几个解决的方法,参考https://stackoverflow.com/questions/3551242/numpy-index-slice-without-losing-dimension-information
用法:
import numpy as np
a = np.array([[1,2,3],
[4,5,6],
[7,8,9]])
# 取a的第一列
b1 = a[:,0][:,np.newaxis]
print('b1.shape = ',b1.shape)
# 取a的第一行
b2 = a[0,:][np.newaxis,:]
print('b2.shape = ',b2.shape)
# output:
# b1.shape = (3, 1)
# b2.shape = (1, 3)
用法:
import numpy as np
a = np.array([[1,2,3],
[4,5,6],
[7,8,9]])
# 取a的第一列
b1 = a[:,0 ,np.newaxis]
print('b1.shape = ',b1.shape)
# 取a的第一行
b2 = a[np.newaxis,0,:]
print('b2.shape = ',b2.shape)
# output:
# b1.shape = (3, 1)
# b2.shape = (1, 3)
用法:
import numpy as np
a = np.array([[1,2,3],
[4,5,6],
[7,8,9]])
# 取a的第一列
b1 = a[:,[0]]
print('b1.shape = ',b1.shape)
# 取a的第一行
b2 = a[[0],:]
print('b2.shape = ',b2.shape)
# output:
# b1.shape = (3, 1)
# b2.shape = (1, 3)
这个方法很方便,但是据说在高维度的情况下会出问题,参考文章开头链接中的相关内容
其实一开始我就用的这个方法,因为它直观…而且吴恩达老师在编程课上用的也是这个方法,就是会让代码变得很长。
用法:
import numpy as np
a = np.array([[1,2,3],
[4,5,6],
[7,8,9]])
# 取a的第一列
b1 = a[:,0].reshape(a.shape[0], 1)
print('b1.shape = ',b1.shape)
# 取a的第一行
b2 = a[0,:].reshape(1,a.shape[1])
print('b2.shape = ',b2.shape)
# output:
# b1.shape = (3, 1)
# b2.shape = (1, 3)
有些程序运行的结果也会丢失维度是1的情况,但程序一般会有个参数叫keepdim=,如果是keepdim=True,那么结果维度是1时就会保留该维度。