Numpy库学习—squeeze()函数

版权声明:流浪者 https://blog.csdn.net/gz153016/article/details/86553019
"""
Numpy库学习—squeeze()函数
numpy.squeeze()函数
语法:numpy.squeeze(a,axis = None)
 1)a表示输入的数组;
 2)axis用于指定需要删除的维度,但是指定的维度必须为单维度,否则将会报错;
 3)axis的取值可为None 或 int 或 tuple of ints, 可选。若axis为空,则删除所有单维度的条目;
 4)返回值:数组
 5) 不会修改原数组;
 场景:在机器学习和深度学习中,通常算法的结果是可以表示向量的数组(即包含两对或以上的方括号形式[[]]),
 如果直接利用这个数组进行画图可能显示界面为空(见后面的示例)。
 我们可以利用squeeze()函数将表示向量的数组转换为秩为1的数组,
 这样利用matplotlib库函数画图时,就可以正常的显示结果了

"""
import numpy as np
#例1
# a=np.arange(10).reshape(1,10)
# print(a)# [[0 1 2 3 4 5 6 7 8 9]]
# print(a.shape)# (1, 10)
# b=np.squeeze(a)# [0 1 2 3 4 5 6 7 8 9]
# print(b)
# print(b.shape)# (10,)

# #例二
# c=np.arange(10).reshape(2,5)
# print(c)
# b=np.squeeze(c)
# print(b)

# #例三
# d=np.arange(10).reshape(1,2,5)
# print(d)
# print(d.shape)#(1, 2, 5)
# b=np.squeeze(d)
# print(b)
# print(np.squeeze(b).shape)
"""
结论:根据上述例1~3可知,np.squeeze()函数可以删除数组形状中的单维度条目,
即把shape中为1的维度去掉,
但是对非单维的维度不起作用
"""
# 例四
e=np.arange(10).reshape(1,10,1)
# print(e)
# print(np.squeeze(e))
# print(np.squeeze(e).shape)
# print(np.squeeze(e).ndim)

# #例五
# print(np.squeeze(e,axis=0))
# print(np.squeeze(e,axis=0).shape)

#例六
# print(np.squeeze(e,axis=2))
# print(np.squeeze(e,axis=2).shape)

#例七
# print(np.squeeze(e,axis=1))
#ValueError: cannot select an axis to squeeze out which has size not equal to one

#例八
import matplotlib.pyplot as plt
import numpy as np
#无法正常显示图示案例
squares =np.array([[1,4,9,16,25]])
print(squares)
print(squares.shape)      #要显示的数组为可表示1行5列的向量的数组
plt.plot(squares)
plt.show()
#正常显示图示案例
#通过np.squeeze()函数转换后,要显示的数组变成了秩为1的数组,即(5,)
plt.plot(np.squeeze(squares))
plt.show()




















猜你喜欢

转载自blog.csdn.net/gz153016/article/details/86553019