1 | import numpy as np |
1 | a = np.arange(10).reshape(1,10) |
1 | a |
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
1 | a.shape |
(1, 10)
1 | b = np.squeeze(a) |
1 | b |
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
1 | b.shape |
(10,)
例2
1 | c = np.arange(10).reshape(2, 5) |
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
1 | np.squeeze(c) |
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
例3
1 | d = np.arange(10).reshape(1,2,5) |
1 | d |
array([[[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]]])
1 | d.shape |
(1, 2, 5)
1 | np.squeeze(d) |
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
1 | np.squeeze(d).shape |
(2, 5)
结论: 根据上述例1-3可知,np.squeeze() 函数的作用就是删除数形状中的单维度条目,即把shape中为1的维度去掉,但是对没有单维度的数组不起作用,如例2中没有单维度。
例4
1 | e = np.arange(10).reshape(1,10,1) |
1 | e |
array([[[0],
[1],
[2],
[3],
[4],
[5],
[6],
[7],
[8],
[9]]])
1 | np.squeeze(e) |
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
1 | np.squeeze(e).shape |
(10,)
1 | np.squeeze(e, axis=0) |
array([[0],
[1],
[2],
[3],
[4],
[5],
[6],
[7],
[8],
[9]])
1 | np.squeeze(e, axis=0).shape |
(10, 1)
1 | np.squeeze(e,axis=2) |
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
1 | np.squeeze(e, axis=2).shape |
(1, 10)
例7 指定的维度不是单维,因此会报错
1 | np.squeeze(e, axis = 1) |
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-13-bf6f4f40a24d> in <module>()
----> 1 np.squeeze(e, axis = 1)
~/anaconda3/lib/python3.6/site-packages/numpy/core/fromnumeric.py in squeeze(a, axis)
1196 try:
1197 # First try to use the new axis= parameter
-> 1198 return squeeze(axis=axis)
1199 except TypeError:
1200 # For backwards compatibility
ValueError: cannot select an axis to squeeze out which has size not equal to one
例8 matplotlib 画图示例
1 | import matplotlib.pyplot as plt |
1 | # 无法正常显示图示案例 |
(1, 5)
1 | plt.plot(squares) |
1 | #正常显示图示案例 |
1 | np.squeeze(squares).shape |
(5,)
例9
1 | import numpy as np |
(1, 1)
1 | B = np.squeeze(A) #将数组A中维度为1 的条目删除,从而变成了0维的数组 |
array(0.6)
1 | isinstance(B, float) #由于B是0维数组,因此返回false |
False
1 | B.item() #可以通过item() 方法,将0维数组转化为float |
0.6
1 | isinstance(B.item(),float) |
True