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

Viewed 937

I have a numpy array with dimensions (100,50,20). I understand what np.expand_dims(X_val, axis=0) does but cant wrap my head around the -1.

1 Answers

It is just like np.newaxis, directly np.newaxis should be faster as it is skip all intermidiate steps.

I took a quick look at code base and for axis=-1. I will explain below.

How expand_dim works inside

  • There are other checks and validations inside, I am skipping for simplicity
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)
  • So yeah, axis=-1 is like adding new axis, just changing the view actually

Debug

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

Related