np.expand_dims(X_val, -1) 有什么作用?不明白-1的意义

What does np.expand_dims(X_val, -1) peform? Don't understand the significance of -1

我有一个维度为 (100,50,20) 的 numpy 数组。我了解 np.expand_dims(X_val, axis=0) 的作用,但无法理解 -1.

就像np.newaxis一样,直接np.newaxis应该会更快,因为它跳过了所有中间步骤。

我快速查看了代码库并找到了 axis=-1。我会在下面解释。

expand_dim 内部是如何工作的

  • 里面还有其他检查和验证,为了简单起见,我跳过了
a = np.ones((100,50,20))
# For axis = -1
axis = -1
# inside expand_dim, convert int to tuple
# https://github.com/numpy/numpy/blob/main/numpy/lib/shape_base.py#L594
if type(axis) not in (tuple, list):
    axis = (axis,)
print('-1 is changed to ', axis)

# Calculate size of new dims
out_ndim = len(axis) + a.ndim

# Normalize axis = -1 to proper value which is out_ndim - 1
"""
https://www.kite.com/python/docs/numpy.core.multiarray.normalize_axis_index
Examples
--------
>>> normalize_axis_index(0, ndim=3)
0
>>> normalize_axis_index(1, ndim=3)
1
>>> normalize_axis_index(-1, ndim=3)
2
"""
axis = tuple([np.core.multiarray.normalize_axis_index(ax, out_ndim, None) for ax in axis])
print('(-1,) changed to ', axis)
# (-1,) changed to  (3,)
shape_it = iter(a.shape)
shape = [1 if ax in axis else next(shape_it) for ax in range(out_ndim)]
print('Final Shape', shape)
# print('Final Shape', shape)
a.reshape(shape)
# (100, 50, 20, 1)
  • 是的,axis=-1 就像添加新轴,实际上只是改变视图

调试

https://github.com/numpy/numpy/blob/main/numpy/lib/shape_base.py#L594

https://github.com/numpy/numpy/blob/b235f9e701e14ed6f6f6dcba885f7986a833743f/numpy/core/numeric.py#L1385

https://www.kite.com/python/docs/numpy.core.multiarray.normalize_axis_index