关于squeeze函数

reshape函数:改变数组的维数(注意不是shape大小)

>>> e= np.arange(10)
>>> e
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> e.reshape(1,1,10)
array([[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]])
>>> e.reshape(1,1,10)
array([[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]])
>>> e.reshape(1,10,1)
array([[[0],
        [1],
        [2],
        [3],
        [4],
        [5],
        [6],
        [7],
        [8],
        [9]]])

squeeze 函数:从数组的形状中删除单维度条目,即把shape中为1的维度去掉

没必要的维度去掉,类似[[[1,2]]]只需要保留一个维度

用法:numpy.squeeze(a,axis = None)

 1)a表示输入的数组;
 2)axis用于指定需要删除的维度,但是指定的维度必须为单维度,否则将会报错;
 3)axis的取值可为None 或 int 或 tuple of ints, 可选。若axis为空,则删除所有单维度的条目;
 4)返回值:数组
 5) 不会修改原数组;
>>> a = e.reshape(1,1,10)
>>> a
array([[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]])
>>> np.squeeze(a)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

体现在画图时

>>> plt.plot(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 3240, in plot
    ret = ax.plot(*args, **kwargs)
  File "C:\Python27\lib\site-packages\matplotlib\__init__.py", line 1710, in inner
    return func(ax, *args, **kwargs)
  File "C:\Python27\lib\site-packages\matplotlib\axes\_axes.py", line 1437, in plot
    for line in self._get_lines(*args, **kwargs):
  File "C:\Python27\lib\site-packages\matplotlib\axes\_base.py", line 404, in _grab_next_args
    for seg in self._plot_args(this, kwargs):
  File "C:\Python27\lib\site-packages\matplotlib\axes\_base.py", line 384, in _plot_args
    x, y = self._xy_from_xy(x, y)
  File "C:\Python27\lib\site-packages\matplotlib\axes\_base.py", line 246, in _xy_from_xy
    "shapes {} and {}".format(x.shape, y.shape))
ValueError: x and y can be no greater than 2-D, but have shapes (1L,) and (1L, 1L, 10L)
>>> plt.plot(np.squeeze(a))
[<matplotlib.lines.Line2D object at 0x00000000146CD940>]
>>> plt.show()

通过np.squeeze()函数转换后,要显示的数组变成了秩为1的数组,即(10,)

a = e.reshape(1,2,5)
a
array([[[0, 1, 2, 3, 4],
        [5, 6, 7, 8, 9]]])
np.squeeze(a)
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
a.shape
(1, 2, 5)
np.squeeze(a).shape
(2, 5)

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值