ML Foundations
Remove one NumPy singleton axis without losing the batch axis
Specify the axis to squeeze when another length-one dimension must remain.

Evidence and testing
Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.
Two axes can both have length one
A model input or output may contain a batch dimension of length one and a separate trailing channel dimension of length one. Calling NumPy squeeze without an axis removes all axes whose length is one. That may remove the batch dimension as well as the intended trailing dimension. [1]
If downstream code expects a batch axis even for one item, identify which axis is safe to remove and pass that axis explicitly. The resulting shape is an interface contract, so inspect it before handing the array to another operation. [1]
References: [1]
Squeeze only the trailing axis
Run python examples/numpy_squeeze_explicit_axis.py. The fixture has shape (1, 3, 1). Default squeeze produces shape (3,), while specifying axis minus one removes only the trailing dimension and preserves shape (1, 3). The value assertion checks the remaining row. [1]
The example also tries to squeeze axis one, whose length is three, and catches the resulting ValueError. An explicit axis therefore makes an unexpected non-singleton dimension visible instead of silently removing a different axis. [1]
Executed with Python 3.12.14; stdout and checksum recorded in private evidence.
import numpy as np
values = np.arange(3).reshape(1, 3, 1)
all_singletons = np.squeeze(values)
channel_only = np.squeeze(values, axis=-1)
print('input shape:', values.shape)
print('default shape:', all_singletons.shape)
print('channel-only shape:', channel_only.shape)
try:
np.squeeze(values, axis=1)
except ValueError:
print('non-singleton rejected:', True)
assert channel_only.shape == (1, 3)
assert np.array_equal(channel_only[0], values[0, :, 0])
Recorded output
input shape: (1, 3, 1) default shape: (3,) channel-only shape: (1, 3) non-singleton rejected: True
References: [1]
Preserve meaning when restoring dimensions
NumPy expand_dims can insert a length-one axis, but choose the position according to the consumer’s expected layout. Adding a dimension at an arbitrary position may produce a valid shape with a different interpretation. [2]
This example uses a three-dimensional integer array with one intended batch axis. It does not cover framework-specific tensors, axis naming metadata or performance. NumPy documents squeeze as returning the input or a view, so consider shared storage if the result will be mutated. [1]