以下两种情况有什么不同(为什么第一种情况中缺少尺寸):
zeros((3,)).shape
Out[67]: (3,)
zeros((3,1)).shape
Out[68]: (3, 1)
shape
是数组的维度元组。一个一维数组的形状为(n,)。一个二维数组的形状为(n,m),一个三维数组的形状为(n,m,k),以此类推。
当您从(3,)
变为(3,1)
时,您正在从一维变为二维。
您可以通过这种方式持续添加维度(您可以使用.ndim
检查数组的维数):
一维:
>>> a = np.zeros((2))
array([ 0., 0.])
>>> a.shape
(2,)
>>> a.ndim
1
两个维度:
>>> b = np.zeros((2,2))
array([[ 0., 0.],
[ 0., 0.]])
>>> b.shape
(2,2)
>>> b.ndim
2
三个维度:
>>> c = np.zeros((2,2,2))
array([[[ 0., 0.],
[ 0., 0.]],
[[ 0., 0.],
[ 0., 0.]]])
>>> c.shape
(2,2,2)
>>> c.ndim
3
四个维度:
>>> d = np.zeros((2,2,2,2))
array([[[[ 0., 0.],
[ 0., 0.]],
[[ 0., 0.],
[ 0., 0.]]],
[[[ 0., 0.],
[ 0., 0.]],
[[ 0., 0.],
[ 0., 0.]]]])
>>> d.shape
(2,2,2,2)
>>> d.ndim
4