很多时候,数组被挤压np.squeeze().它说,在文档中
从a的形状中删除一维条目.
但是我一直在想:为什么是在一个形状为零,无量纲项?或者换种方式:为什么都a.shape = (2,1) 和 (2,)存在?
重要的一个例子是乘法数组.两个二维数组将一次乘以每个值
例如
>>> x = np.ones((2, 1))*2
>>> y = np.ones((2, 1))*3
>>> x.shape
(2,1)
>>> x*y
array([[ 6.],
[ 6.]])
Run Code Online (Sandbox Code Playgroud)
如果将1d数组乘以2d数组,则行为会有所不同
>>> z = np.ones((2,))*3
>>> x*z
array([[ 6., 6.],
[ 6., 6.]])
Run Code Online (Sandbox Code Playgroud)
其次,您也可能想要将早期维度egashape =(1,2,2)压缩为a.shape =(2,2)
小智 5
压缩(2,1)数组时,得到(2,)既可以用作(2,1)也可以用作(1,2):
>>> a = np.ones(2)
>>> a.shape
(2,)
>>> a.T.shape
(2,)
>>> X = np.ones((2,2))*2
>>> np.dot(a,X)
[4. 4.]
>>> np.dot(X,a)
[4. 4.]
Run Code Online (Sandbox Code Playgroud)
(2,1)数组不会发生这种情况:
>>> b = np.ones((2,1))
>>> np.dot(b,X)
Traceback (most recent call last):
ValueError: shapes (2,1) and (2,2) not aligned: 1 (dim 1) != 2 (dim 0)
Run Code Online (Sandbox Code Playgroud)