Sub topic 5
Predicting the Shape of the Result
This chapter assumes you can create arrays with np.array and np.arange, read an array's shape tuple, and know that axis picks the direction of a reduction. Here you will learn to state the shape of any aggregation result before you run it. That skill catches broadcasting bugs early.
The one rule
A reduction removes the axes you name from the shape tuple. The lengths of the remaining axes stay in their original order.
For an array of shape (2, 3):
| Call | Axes removed | Result shape |
|---|---|---|
| `a.sum()` | all | `()` |
| `a.sum(axis=0)` | 0 | `(3,)` |
| `a.sum(axis=1)` | 1 | `(2,)` |
| `a.sum(axis=-1)` | 1 | `(2,)` |
The length of the removed axis is the number of values that were combined into each output value. Reducing axis=0 of a (2, 3) array combines 2 values into each of 3 outputs. Reducing axis=1 combines 3 values into each of 2 outputs.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
total = a.sum()
print(total, np.ndim(total)) # 21 0
print(a.sum(axis=0).shape) # (3,)
print(a.sum(axis=1).shape) # (2,)
print(a.sum(axis=-1).shape) # (2,)The empty shape
With no axis, every axis is removed, so nothing is left in the shape tuple. The result has shape (), which means zero dimensions. NumPy returns it as a scalar such as numpy.int64, not as a one-element array.
This differs from shape (1,), which is a one-dimensional array holding one value. The two behave differently in broadcasting and in functions that expect arrays, so keep them apart.
Negative axes
A negative axis counts from the end of the shape. In an array with ndim dimensions, axis=-1 means the last axis and axis=-ndim means the first. Code that uses axis=-1 keeps working when the array later gains a leading dimension, such as a batch axis. For that reason it is common in library code.
An axis outside the range -ndim to ndim - 1 raises an error:
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
try:
a.sum(axis=2)
except ValueError as e:
print(e) # axis 2 is out of bounds for array of dimension 2NumPy's AxisError subclasses both ValueError and IndexError, so either except clause catches it.
Three dimensions and tuples of axes
The rule does not change with more dimensions. The axis argument can also be a tuple, and all the listed axes are removed at once.
import numpy as np
b = np.arange(24).reshape(2, 3, 4)
for axis in [None, 0, 1, 2, -1, (0, 1), (0, 2), (1, 2), (0, 1, 2)]:
print(axis, b.sum(axis=axis).shape)
# None ()
# 0 (3, 4)
# 1 (2, 4)
# 2 (2, 3)
# -1 (2, 3)
# (0, 1) (4,)
# (0, 2) (3,)
# (1, 2) (2,)
# (0, 1, 2) ()Reducing over (0, 2) of (2, 3, 4) leaves only the middle axis, so you get 3 values. Each value is the sum of 2 × 4 = 8 original elements. Reducing over all axes by tuple gives the same shape as axis=None.
A tuple must not repeat an axis. b.sum(axis=(0, 0)) raises ValueError: duplicate value in 'axis'.
Keeping the reduced axes
With keepdims=True, the reduced axes stay in the shape with length 1. The rank (number of dimensions) of the result then equals the rank of the input.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
b = np.arange(24).reshape(2, 3, 4)
print(a.sum(axis=0, keepdims=True).shape) # (1, 3)
print(a.sum(axis=1, keepdims=True).shape) # (2, 1)
print(a.sum(keepdims=True).shape) # (1, 1)
print(b.sum(axis=(0, 2), keepdims=True).shape) # (1, 3, 1)Shape (1, 1) from a full reduction can surprise you. It is a 2-D array holding one value, not a scalar. The table below shows how the two modes compare for b with shape (2, 3, 4).
| `axis` | `keepdims=False` | `keepdims=True` |
|---|---|---|
| `0` | `(3, 4)` | `(1, 3, 4)` |
| `2` | `(2, 3)` | `(2, 3, 1)` |
| `(0, 2)` | `(3,)` | `(1, 3, 1)` |
| `None` | `()` | `(1, 1, 1)` |
A checking procedure
The diagram shows the steps for predicting a shape by hand.
You can turn the procedure into a small function and compare it with what NumPy returns. This is a useful way to confirm you have the rule right.
import numpy as np
def predict_shape(shape, axis=None, keepdims=False):
ndim = len(shape)
if axis is None:
axes = set(range(ndim))
else:
raw = (axis,) if isinstance(axis, int) else tuple(axis)
axes = set()
for ax in raw:
if not -ndim <= ax < ndim:
raise ValueError(
f"axis {ax} is out of bounds for array of dimension {ndim}"
)
axes.add(ax % ndim)
if len(axes) != len(raw):
raise ValueError("duplicate value in 'axis'")
if keepdims:
return tuple(1 if i in axes else n for i, n in enumerate(shape))
return tuple(n for i, n in enumerate(shape) if i not in axes)
shape = (2, 3, 4)
for axis in [None, 0, 1, 2, -1, (0, 1), (0, 2), (1, 2), (0, 1, 2)]:
for keepdims in (False, True):
actual = np.zeros(shape).sum(axis=axis, keepdims=keepdims).shape
assert actual == predict_shape(shape, axis, keepdims)
print("all shapes match") # all shapes matchThe % ndim step is what converts a negative axis such as -1 into its positive equivalent.
Functions that do not remove the axis
Not every function that takes axis reduces. Check which kind you are using before you predict the shape.
- Reductions (
sum,mean,min,max,std,argmax,argmin) remove the axis. - Cumulative functions (
cumsum,cumprod) keep the full input shape when you give anaxis. - With
axis=None,cumsumflattens the array first and returns a 1-D result.argmaxreturns a single index into the flattened array.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(np.cumsum(a, axis=1).shape) # (2, 3)
print(np.cumsum(a).shape) # (6,)
print(a.argmax(axis=1).shape) # (2,)
print(a.argmax()) # 5The final value, 5, is the position of the largest element (6) in the flattened array [1 2 3 4 5 6].
Axes of length zero
An axis can have length 0. The shape rule still holds, and the values depend on the function.
import numpy as np
empty = np.zeros((0, 3))
print(empty.sum(axis=0)) # [0. 0. 0.]
print(empty.sum(axis=0).shape) # (3,)
try:
empty.max(axis=0)
except ValueError as e:
print(e) # zero-size array to reduction operation maximum which has no identitysum returns zeros because adding no numbers gives 0, the identity for addition. max has no identity value, so it raises an error. This often appears when a filter step removes every row of a table.
The shape mistake you will meet most
The common bug comes from forgetting that a reduction drops an axis. You then try to combine the result with the original array.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
try:
a - a.mean(axis=1) # (2, 3) with (2,)
except ValueError as e:
print(e) # operands could not be broadcast together with shapes (2,3) (2,)
print((a - a.mean(axis=1, keepdims=True)).shape) # (2, 3)Broadcasting lines up shapes from the right. The shape (2,) is compared with the last axis of (2, 3), which has length 3, so they do not match. With keepdims=True the mean has shape (2, 1), and the length-1 axis stretches across the columns.
The shape of the result does not tell you its dtype. Integer sum keeps an integer dtype, while mean returns floats. The later chapter on data types covers that.
Exercise
An array x has shape (5, 4, 3). Give the result shape of x.sum(axis=(0, 2)), of x.sum(axis=-2, keepdims=True), and of x.max(axis=None, keepdims=True).
Show answer
(4,), (5, 1, 3), and (1, 1, 1). The first removes axes 0 and 2 and leaves length 4. In the second, -2 is axis 1, so its length becomes 1 and the rest stay. The third reduces every axis but keeps all three as length 1.
Exercise
scores has shape (30, 4), with 30 students and 4 tests. You run centered = scores - scores.mean(axis=0). Does this work? What does it compute? Then write the line that subtracts each student's own mean instead.
Show answer
It works. scores.mean(axis=0) has shape (4,), which broadcasts against the last axis of (30, 4), so each test's average is subtracted from that test's column. For per-student centering, use scores - scores.mean(axis=1, keepdims=True). The (30, 1) mean broadcasts across the 4 columns. Without keepdims=True, the (30,) result fails against (30, 4).