Sub topic 10
Aligning shapes with np.newaxis and keepdims
This chapter assumes you know what an array's shape is and how reductions such as sum and mean take an axis argument. It also assumes you know the broadcasting rule: NumPy compares shapes starting from the trailing (rightmost) dimension, and two dimensions are compatible if they are equal or one of them is 1. Here you will learn to adjust shapes yourself so that broadcasting does what you intend.
Why shapes need adjusting
Broadcasting aligns dimensions from the right. It never guesses which axis you meant. A vector of shape (3,) is always treated as a row, and its single axis lines up with the last axis of the other operand.
That is convenient when you want a row, such as subtracting column means. It fails when you want a column, such as subtracting row means. In that case you must give the vector a second axis of length 1. A length-1 axis stretches to match any length, and an axis that is missing entirely does not. NumPy offers two tools for adding that axis:
np.newaxis(and its equivalents) adds a length-1 axis to an array you already have.keepdims=Truestops a reduction from removing the axis it collapsed, so the result already has the right shape.
Adding axes with np.newaxis
np.newaxis is an alias for None. Putting it inside an index inserts a new axis of length 1 at that position.
import numpy as np
v = np.array([10, 20, 30])
print(np.newaxis is None) # True
print(v.shape) # (3,)
print(v[:, np.newaxis].shape) # (3, 1) a column
print(v[np.newaxis, :].shape) # (1, 3) a row
print(v[None, :, None].shape) # (1, 3, 1)Read the index left to right. Each : consumes one existing axis, and each np.newaxis creates a new one in that slot. The new axis always has length 1, so the total number of elements never changes.
Indexing with np.newaxis is cheap. It returns a view, not a copy, so no data is duplicated. You can confirm this:
import numpy as np
v = np.arange(5)
col = v[:, np.newaxis]
print(np.shares_memory(v, col)) # TrueEquivalent spellings
Three other forms produce the same result. Pick the one that reads best in context.
| Goal | Indexing | reshape | expand_dims |
|---|---|---|---|
| Column from `(n,)` | `v[:, np.newaxis]` | `v.reshape(-1, 1)` | `np.expand_dims(v, axis=1)` |
| Row from `(n,)` | `v[np.newaxis, :]` | `v.reshape(1, -1)` | `np.expand_dims(v, axis=0)` |
| Append last axis to any array | `a[..., np.newaxis]` | `a.reshape(a.shape + (1,))` | `np.expand_dims(a, axis=-1)` |
The ... (Ellipsis) stands for "all the axes I did not mention". It makes a[..., np.newaxis] work whether a has one, two or five dimensions. That makes it a good choice in functions that accept arrays of unknown rank.
Use reshape(-1, 1) when you want NumPy to work out the length. Use np.newaxis when you want to say exactly where the new axis goes, especially with more than two dimensions.
Scaling rows with a column vector
Suppose each row of x should be multiplied by its own weight. The weights have shape (2,), but they must line up with axis 0, not axis 1.
import numpy as np
x = np.array([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]])
weights = np.array([10.0, 100.0]) # one weight per row
print(x * weights[:, np.newaxis])
# [[ 10. 20. 30.]
# [400. 500. 600.]]The shapes are (2, 3) and (2, 1). The trailing dimensions are 3 and 1, so the 1 stretches to 3. The leading dimensions are both 2. The result has shape (2, 3).
Without the new axis, x * weights compares (2, 3) with (2,). The trailing dimensions are 3 and 2, which do not match, so NumPy raises a ValueError.
Keeping reduced axes with keepdims
A reduction normally removes the axis it works along. x.sum(axis=1) turns shape (2, 3) into (2,). You can then restore the axis with np.newaxis, but passing keepdims=True is shorter and safer. It leaves the reduced axis in place with length 1.
import numpy as np
x = np.array([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]])
print(x.sum(axis=1).shape) # (2,)
print(x.sum(axis=1, keepdims=True).shape) # (2, 1)
p = x / x.sum(axis=1, keepdims=True) # each row now sums to 1
print(np.allclose(p.sum(axis=1), 1.0)) # TrueThe key property of keepdims=True is that the result always broadcasts against the original array. The kept axis has length 1, so it stretches back to the full size. This holds for any number of dimensions and for any axis, so you do not have to work out where the new axis belongs.
keepdims is accepted by sum, mean, std, var, min, max, prod, any, all and most other reductions, both as methods and as np. functions.
Reducing over several axes
The axis argument can be a tuple. Combined with keepdims=True, this gives a clean way to normalize each sample in a batch:
import numpy as np
a = np.arange(24).reshape(2, 3, 4) # 2 samples, each 3x4
m = a.mean(axis=(1, 2), keepdims=True)
print(m.shape) # (2, 1, 1)
print(m.ravel()) # [ 5.5 17.5]
print((a - m).shape) # (2, 3, 4)Without keepdims, m would have shape (2,). Subtracting it from a (2, 3, 4) array would compare 2 with 4 and fail. You would need m[:, np.newaxis, np.newaxis] instead.
Column operations need no help
Reductions along axis 0 on a 2D array give a result whose shape already lines up with the trailing axis:
import numpy as np
x = np.array([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]])
z = (x - x.mean(axis=0)) / x.std(axis=0) # shapes (2, 3) and (3,)
print(z)
# [[-1. -1. -1.]
# [ 1. 1. 1.]]This is why the column case works without extra code and the row case does not. For arrays with more than two dimensions, keepdims=True is the safest default for every reduction whose result you plan to combine with the original.
Choosing a tool
- Use
keepdims=Truewhen the vector comes from a reduction of the array you will combine it with. - Use
np.newaxisorreshape(-1, 1)when the vector comes from somewhere else, such as a weights array loaded from a file. - Use
np.expand_dimswhen the axis position is a variable. It takesaxisas an argument, which indexing syntax cannot do. - Use
a[..., np.newaxis]when you need a trailing axis and do not know the rank.
The diagram shows why the same reduction can succeed or fail depending on keepdims.
Common errors
The loud failure is a ValueError saying the operands could not be broadcast together. Read the shapes in the message and compare them from the right. If the dimension you wanted to stretch is not last, add an axis.
The dangerous failure is silent. When an array is square, a misaligned vector still broadcasts, but along the wrong axis:
import numpy as np
sq = np.arange(9).reshape(3, 3)
sums = sq.sum(axis=1) # [ 3 12 21]
wrong = sq - sums # (3, 3) - (3,): subtracts along columns
right = sq - sums[:, np.newaxis] # (3, 3) - (3, 1): subtracts along rows
print(wrong)
# [[ -3 -11 -19]
# [ 0 -8 -16]
# [ 3 -5 -13]]
print(right)
# [[ -3 -2 -1]
# [ -9 -8 -7]
# [-15 -14 -13]]No error is raised for wrong, so only a check of the values reveals the mistake. Two habits help:
- Print
.shapeof each operand whenever you write a new broadcast expression. - Test with a non-square array first, so a misalignment raises an error instead of passing silently.
A related mistake is combining (n,) with (n, 1). The result is an (n, n) array, not an (n,) array, because each shape stretches against the other. This is useful for pairwise computations, but it is a surprise if you did not intend it. It also costs n times more memory than you may expect.
Exercises
Exercise
You have x with shape (4, 5) and scale = np.array([1, 2, 3, 4]). Write an expression that multiplies row i of x by scale[i], and state the shapes being broadcast.
Show answer
x * scale[:, np.newaxis] (or x * scale.reshape(-1, 1)). The shapes are (4, 5) and (4, 1). The 1 stretches to 5, and the result has shape (4, 5). Without the new axis, the shapes (4, 5) and (4,) compare 5 with 4 and raise a ValueError.
Exercise
batch has shape (8, 3, 32, 32), holding 8 images with 3 channels each. You want to subtract each channel's mean over its height and width, for each image separately. Which call computes the means so that the subtraction works, and what shape does it return?
Show answer
batch.mean(axis=(2, 3), keepdims=True) returns shape (8, 3, 1, 1). It broadcasts against (8, 3, 32, 32), so batch - batch.mean(axis=(2, 3), keepdims=True) gives the centered batch with shape (8, 3, 32, 32).
Exercise
a = np.arange(3) and b = np.arange(3)[:, np.newaxis]. What is the shape of a + b, and why is it not (3,)?
Show answer
The shape is (3, 3). The shapes (3,) and (3, 1) are aligned from the right. a is treated as (1, 3), and both operands stretch along their length-1 axis, so every element of a is added to every element of b.