python squeeze()

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
2
c = np.arange(10).reshape(2, 5)
c
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
2
3
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
1
2
3
# 无法正常显示图示案例
squares = np.array([[1,4,9,16,25]])
squares.shape #要显示的数组维可表示为1行5列的向量的数组
(1, 5)
1
2
plt.plot(squares)
plt.show()

png

1
2
3
4
#正常显示图示案例
#通过np.squeeze()函数转换后,要显示的数组变为了秩为1的数组,既(5,)
plt.plot(np.squeeze(squares))
plt.show()

png

1
np.squeeze(squares).shape
(5,)

例9

1
2
3
4
import numpy as np

A = np.array([[0.6]]) #定义一个一行一列的数组
A.shape
(1, 1)
1
2
B = np.squeeze(A)  #将数组A中维度为1 的条目删除,从而变成了0维的数组
B #B虽然是0维,但是仍然是数组,而不是单纯的浮点数(float)
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
Pu liu wechat
subscribe to my blog by scanning my public wechat account
Thanks Support