numpy的squeeze函数和expand_dims函数

np.squeeze()

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

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


 - a表示输入的数组; 
 - axis用于指定需要删除的维度,但是指定的维度必须为单维度,否则将会报错; 
 - axis的取值可为None 或 int 或tuple of ints, 可选。若axis为空,则删除所有单维度的条目; 
 - 返回值:数组 不会修改原数组;

>>import numpy as np
>>e = np.arange(10)
>>e
>>Out[28]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

>>a = e.reshape(10, 1, 1)
>>a.shape
>>Out[35]: (10, 1, 1)

>>b = np.squeeze(a)
>>b.shape
>>Out[36]: (10,)

np.expand_dims()

np.expand_dims:用于扩展数组的形状

>>import numpy as np
>>a = np.arange(24).reshape(2,3,4)
>>a.shape
>>Out[41]: (2, 3, 4)

np.expand_dims(a, axis=0)表示在0位置添加数据,转换结果如下:

>>b = np.expand_dims(a, axis=0)
>>b.shape
>>Out[43]: (1, 2, 3, 4)

np.expand_dims(a, axis=1)表示在1位置添加数据,转换结果如下:

>>c = np.expand_dims(a, axis=1)
>>c.shape
>>Out[45]: (2, 1, 3, 4)

np.expand_dims(a, axis=2)表示在2位置添加数据,转换结果如下:

>>d = np.expand_dims(a, axis=2)
>>d.shape
>>Out[47]: (2, 3, 1, 4)

np.expand_dims(a, axis=3)表示在3位置添加数据,转换结果如下:

>>e = np.expand_dims(a, axis=3)
>>e.shape
>>Out[49]: (2, 3, 4, 1)

能在(1,2,3)中插入的位置总共为4个,再添加就会出现以下的警告,要不然也会在后面某一处提示AxisError:

>>f = np.expand_dims(a, axis=4)
>>D:\pycharm\PyCharm 2018.2\helpers\pydev\pydevconsole.py:1: DeprecationWarning: Both axis > a.ndim and axis < -a.ndim - 1 are deprecated and will raise an AxisError in the future.
  '''
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值