numpy的squeeze函数和expand_dims函数 小鱼儿 2024-04-19 11:25 10阅读 0赞 # 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. '''
还没有评论,来说两句吧...