np.squeeze函数和np.newaxis的区别和联系

np.squeeze()函数
语法:numpy.squeeze(a,axis = None)

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

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

np.newaxis函数
作用:在这一位置增加一个一维,这一位置指的是np.newaxis所在的位置

例子一:

x1 = np.array([1, 2, 3, 4, 5]) # the shape of x1 is (5,) x1_new = x1[:, np.newaxis] # now, the shape of x1_new is (5, 1) # array([[1], # [2], # [3], # [4], # [5]]) x1_new = x1[np.newaxis,:] # now, the shape of x1_new is (1, 5) # array([[1, 2, 3, 4, 5]])
例子二:
In [124]: arr = np.arange(5*5).reshape(5,5)

In [125]: arr.shape
Out[125]: (5, 5)

# promoting 2D array to a 5D array
In [126]: arr_5D = arr[np.newaxis, ..., np.newaxis, np.newaxis]

In [127]: arr_5D.shape
Out[127]: (1, 5, 5, 1, 1)
 

猜你喜欢

转载自www.cnblogs.com/dtpromise/p/11788986.html
今日推荐