'np.squeeze what means axis=-1?
The numpy.squeeze function takes an axis parameter which should be an integer. Sometimes I see the axis parameter being set to axis=-1, however the documentation does not explain what a negative integer does in this case.
What does numpy.squeeze do exactly when axis=-1 is set?
Solution 1:[1]
According to the docs, the axis parameter
Selects a subset of the single-dimensional entries in the shape.
Basically you choose along which axis you want to apply squeeze.
Eg
a = numpy.ones((1,2,2,1))
a.shape
(1,2,2,1)
numpy.squeeze(a,axis=0).shape
(2,2,1)
numpy.squeeze(a,axis=-1).shape
(1,2,2)
So axis=-1 chooses the last axis by numpy convention
If the size of the last axis is more than one, it raises an error.
Solution 2:[2]
According to documentation, squeeze simply removes axes of length one from the array.
you can specify the axis to remove:
x = np.array([[[0], [1], [2]]])
x.shape
(1, 3, 1)
np.squeeze(x, axis=0).shape
(3, 1)
or not, where it will remove all axes with length One:
np.squeeze(x).shape
(3,)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Arun |
| Solution 2 | Mohammad Fasha |
