numpy.squeeze()函数
语法:numpy.squeeze(a,axis = None)
1)a表示输入的数组;
2)axis用于指定需要删除的维度,但是指定的维度必须为单维度,否则将会报错;
3)axis的取值可为None 或 int 或 tuple of ints, 可选。若axis为空,则删除所有单维度的条目;
4)返回值:数组
5) 不会修改原数组;
引用:https://blog.csdn.net/zenghaitao0128/article/details/78512715
引用:https://docs.scipy.org/doc/numpy/reference/generated/numpy.squeeze.html
场景:在机器学习和深度学习中,通常算法的结果是可以表示向量的数组(即包含两对或以上的方括号形式[[]]),如果直接利用这个数组进行画图可能显示界面为空(见后面的示例)。我们可以利用squeeze()函数将表示向量的数组转换为秩为1的数组,这样利用matplotlib库函数画图时,就可以正常的显示结果了。
例子:
import numpy as np
a = np.arange(10)
print("a = np.arange(10):"+str(a))
a = a.reshape(1,10)
print("a = a.reshape(1,10):"+str(a))
a = a.reshape(1,1,10)
print("a = a.reshape(1,1,10):"+str(a))
a = np.squeeze(a)
print("a = np.squeeze(a):"+str(a))
运行结果为:
a = np.arange(10):[0 1 2 3 4 5 6 7 8 9]
a = a.reshape(1,10):[[0 1 2 3 4 5 6 7 8 9]]
a = a.reshape(1,1,10):[[[0 1 2 3 4 5 6 7 8 9]]]
a = np.squeeze(a):[0 1 2 3 4 5 6 7 8 9]
结论:根据上述例子可知,np.squeeze()函数可以删除数组形状中的单维度条目,即把shape中为1的维度去掉,但是对非单维的维度不起作用。
例子:matplotlib画图示例
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
#无法正常显示图示案例
squares =np.array([[1,4,9,16,25]])
squares.shape #要显示的数组为可表示1行5列的向量的数组
(1, 5)
plt.plot(squares)
plt.show()
#正常显示图示案例
#通过np.squeeze()函数转换后,要显示的数组变成了秩为1的数组,即(5,)
plt.plot(np.squeeze(squares))
plt.show()
np.squeeze(squares).shape
(5,)