Sub topic 10
Aligning shapes with np.newaxis and keepdims
This chapter assumes you know the broadcasting rules: shapes are compared from the trailing dimension, and two dimensions match if they are equal or one of them is 1. It also assumes you know what axis does in a reduction. Here you will learn the two tools that make shapes line up when they don't at first.
The problem: the axis you reduced is gone
A reduction such as mean(axis=1) removes the axis it works along. A (2, 3) array becomes shape (2,). Broadcasting then compares (2, 3) with (2,). The trailing dimensions are 3 and 2, so they don't match.
Reducing along axis=0 happens to work. The result has shape (3,), which lines up with the trailing dimension of (2, 3).
keepdims: leave a size-1 axis behind
Passing keepdims=True to a reduction keeps the reduced axis with length 1. The result then broadcasts against the original array.
import numpy as np
x = np.array([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]])
col_centered = x - x.mean(axis=0) # mean has shape (3,)
row_centered = x - x.mean(axis=1, keepdims=True) # mean has shape (2, 1)
print(col_centered) # [[-1.5 -1.5 -1.5]
# [ 1.5 1.5 1.5]]
print(row_centered) # [[-1. 0. 1.]
# [-1. 0. 1.]]With keepdims=True, the row means have shape (2, 1). Broadcasting stretches the size-1 axis across the 3 columns. This works for any axis, so it is a good default whenever you reduce and then combine the result with the original array.
np.newaxis: insert a size-1 axis yourself
Sometimes the vector doesn't come from a reduction, so there is no keepdims to use. np.newaxis is an alias for None. Placing it in an index inserts an axis of length 1 at that position.
import numpy as np
m = np.ones((3, 4))
v = np.arange(3)
try:
m + v # shapes (3, 4) and (3,) do not align
except ValueError as err:
print('error:', err)
print((m + v[:, np.newaxis]).shape) # (3, 4)v[:, np.newaxis] turns shape (3,) into (3, 1). Each element of v now pairs with one row of m. Without it, NumPy tried to match v against the 4 columns.
The position of np.newaxis decides which axis the data lies along:
| Expression | Resulting shape | Lies along |
|---|---|---|
| `v` | `(3,)` | trailing axis |
| `v[:, np.newaxis]` | `(3, 1)` | rows |
| `v[np.newaxis, :]` | `(1, 3)` | columns |
v.reshape(3, 1) gives the same result as v[:, np.newaxis]. Use newaxis when you want to show which axis you are adding. Use reshape when you are changing the shape more broadly.
A habit that prevents mistakes
Before you write the operation, write both shapes beside each other, right-aligned, and decide where each size-1 axis should go. If a shape needs a 1 in a position, add it with np.newaxis or keepdims.
Exercise
An array x has shape (4, 5). You want to divide each row by its row sum. Which expression is correct, and what shape does the sum have?
Show answer
x / x.sum(axis=1, keepdims=True). The sum has shape (4, 1), so it broadcasts across the 5 columns. Without keepdims=True the sum has shape (4,), which fails against the trailing dimension 5.