np.expand_dims

np.expend_dims扩展数组形状

通过在指定位置插入新的轴来扩展数组形状。


np.expand_dims(arr, axis)

参数:

  • arr:输入数组
  • axis:新轴插入的位置

实例:

import numpy as np

x = np.array(([1, 2], [3, 4]))
print(x)

y = np.expand_dims(x, axis=0)
print(y)

print(x.shape, y.shape)

输出结果:

[[1 2]
 [3 4]]


[[[1 2]
  [3 4]]]


(2, 2) (1, 2, 2)

对于数组x, 在位置 1 插入轴

y = np.expand_dims(x, axis=1)
print(y)
print('**********************')
print(x.ndim, y.ndim)       # ndarray.ndim:秩,即轴的数量和维度的数量
print('**********************')
print(x.shape, y.shape)

输出结果:

[[[1 2]]

 [[3 4]]]


**********************
2 3


**********************
(2, 2) (2, 1, 2)
原文地址:https://www.cnblogs.com/keye/p/15383035.html