Normalize array shapes
Normalize inputs from APIs or batches that add singleton dimensions before downstream numerical operations.
NumPy · Function
Removes axes of length one from an array. Use axis to restrict removal to specific singleton dimensions.
np.squeeze returns an array with axes whose length is one removed. With axis=None, every singleton axis is removed; with an integer or tuple, only the selected axes are considered, and each selected axis must have length one.
numpy.squeeze(a, axis=None)| Name | Type | Description |
|---|---|---|
a | array_like | Input data. |
axis | None or int or tuple of ints, optional | Selects a subset of the entries of length one in the shape. If an axis is selected with shape entry greater than one, an error is raised. |
squeezed — ndarray. The input array with all or a subset of dimensions of length 1 removed; it is always a itself or a view into a.
import numpy as np
x = np.array([[[0], [1], [2]]])
print(x.shape) # (1, 3, 1)
print(np.squeeze(x).shape) # (3,)
print(np.squeeze(x, axis=0).shape) # (3, 1)
Use no axis to remove every length-one axis, or provide an axis to remove only selected length-one axes.
Normalize inputs from APIs or batches that add singleton dimensions before downstream numerical operations.
Remove only a known singleton batch or channel dimension while preserving other dimensions.
Convert a shape such as (1, 1) to a 0-dimensional ndarray when scalar-like array behavior is required.
It removes axes of length one from an array. By default, every such axis is removed; an integer or tuple restricts removal to selected axes.
Follow-up: What happens when a selected axis has size greater than one? NumPy raises ValueError because that axis cannot be squeezed.
The input may be array-like, and the result is an ndarray with all or the selected length-one dimensions removed. If no axes remain, the result is a 0-dimensional array.
Follow-up: How would you obtain the contained value from a 0-dimensional result? Index it with [()] as shown in the documentation example.
axis may be None, an integer, or a tuple of integers. None targets all singleton dimensions, while an integer or tuple selects a subset; selected dimensions must have size one.
Follow-up: Why might specifying axis be safer than leaving it as None? It prevents unrelated singleton dimensions from being removed.
numpy.expand_dimsnumpy.reshape