Sub topic 6
Keeping the reduced axis with keepdims
This chapter assumes you can create arrays with np.array and np.arange, read an array's shape, and compute sum, mean, max, and min with an axis argument. It also assumes you know the basic broadcasting rule, described below.
The problem: the reduced axis disappears
When you reduce an array along an axis, NumPy removes that axis from the result. A (2, 3) array summed over axis=1 gives shape (2,), not (2, 1).
That is usually what you want. It becomes a problem when you try to combine the result with the original array in the same expression, for example to divide each row by its total. Broadcasting compares shapes from the rightmost dimension backward. Two dimensions are compatible if they are equal or one of them is 1. A missing dimension is treated as 1.
Here is the failure:
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
row_totals = a.sum(axis=1)
print(a.shape, row_totals.shape) # (2, 3) (2,)
try:
a / row_totals
except ValueError:
print("ValueError: shapes (2, 3) and (2,) do not broadcast")NumPy lines up the last dimensions: 3 against 2. They are neither equal nor 1, so the operation fails.
What keepdims does
Passing keepdims=True tells the reduction to keep the reduced axis with length 1. The result has the same number of dimensions as the input, so it broadcasts against the input.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
row_totals = a.sum(axis=1, keepdims=True)
print(row_totals) # [[ 6]
# [15]]
print(row_totals.shape) # (2, 1)
shares = a / row_totals
print(np.round(shares, 3))
# [[0.167 0.333 0.5 ]
# [0.267 0.333 0.4 ]]The shapes (2, 3) and (2, 1) are compatible. The length-1 axis is stretched across the three columns, so each row is divided by its own total.
Why axis=0 seems to work without it
Reducing over axis=0 gives shape (3,). Against a (2, 3) array, the last dimensions match (3 and 3), and the missing leading dimension counts as 1. So this works without keepdims:
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
centered = a - a.mean(axis=0)
centered_kd = a - a.mean(axis=0, keepdims=True)
print(a.mean(axis=0).shape) # (3,)
print(a.mean(axis=0, keepdims=True).shape) # (1, 3)
print(np.array_equal(centered, centered_kd)) # TrueBoth forms give the same result. The version without keepdims only works because the reduced axis is the first one. Reducing over the last axis, or a middle axis, needs keepdims. If you always pass keepdims=True when you plan to broadcast the result, you don't have to work out which case you are in.
A practical example: stable softmax
Softmax turns each row of scores into probabilities. Subtracting the row maximum first prevents np.exp from overflowing on large scores. Both steps need a per-row value broadcast against every row.
import numpy as np
scores = np.array([[1.0, 2.0, 3.0],
[1000.0, 1001.0, 1002.0]])
shifted = scores - scores.max(axis=1, keepdims=True)
exps = np.exp(shifted)
probs = exps / exps.sum(axis=1, keepdims=True)
print(np.round(probs, 3))
# [[0.09 0.245 0.665]
# [0.09 0.245 0.665]]
print(probs.sum(axis=1)) # [1. 1.]Softmax is unchanged when you subtract the same constant from every score in a row. That is why both rows give identical probabilities. Without the shift, np.exp(1000.0) overflows to inf and the second row becomes nan.
keepdims in three dimensions
In a three-dimensional array, keepdims puts a length-1 axis where each reduced axis was. This works with a tuple of axes too.
import numpy as np
b = np.arange(24).reshape(2, 3, 4)
print(b.sum(axis=1).shape) # (2, 4)
print(b.sum(axis=1, keepdims=True).shape) # (2, 1, 4)
print(b.sum(axis=(0, 2)).shape) # (3,)
print(b.sum(axis=(0, 2), keepdims=True).shape) # (1, 3, 1)
centered = b - b.mean(axis=(0, 2), keepdims=True)
print(centered.shape) # (2, 3, 4)The last line subtracts one mean per index along axis 1, computed over all values in the other two axes. Without keepdims, the mean has shape (3,). Against (2, 3, 4) it would line up with the last axis (length 4) and raise a ValueError.
The rule to remember is that keepdims=True gives a result whose shape equals the input shape with each reduced axis set to 1.
| Input shape | axis | Without keepdims | With keepdims |
|---|---|---|---|
| `(2, 3)` | `0` | `(3,)` | `(1, 3)` |
| `(2, 3)` | `1` | `(2,)` | `(2, 1)` |
| `(2, 3, 4)` | `1` | `(2, 4)` | `(2, 1, 4)` |
| `(2, 3, 4)` | `(0, 2)` | `(3,)` | `(1, 3, 1)` |
| `(2, 3)` | `None` | `()` (a scalar) | `(1, 1)` |
Edge cases
axis=None
With no axis, every dimension is reduced. Combined with keepdims=True, you get an array with all dimensions of length 1, not a scalar.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.sum()) # 21
print(a.sum(keepdims=True)) # [[21]]
print(a.sum(keepdims=True).shape) # (1, 1)The (1, 1) result broadcasts against an array of any shape with two or more dimensions. The shape stays an array, so use .item() if you need a plain Python number.
Which functions accept keepdims
The reduction functions and methods take it: sum, prod, mean, std, var, min, max, any, all, median, and the NaN-aware versions such as nansum and nanmean. Since NumPy 1.22, argmax and argmin accept it too. Cumulative functions such as cumsum do not, because they keep the input shape already.
The argmax case combines well with np.take_along_axis, which expects indices with the same number of dimensions as the array:
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
idx = a.argmax(axis=1, keepdims=True)
print(idx) # [[2]
# [2]]
print(np.take_along_axis(a, idx, axis=1)) # [[3]
# [6]]Alternatives and their limits
You can restore the axis by hand with np.newaxis or reshape:
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
totals = a.sum(axis=1)[:, np.newaxis]
print(totals.shape) # (2, 1)This produces the same shape, but you must write the index for the right position yourself. If you later change the axis, or the array gains a dimension, the indexing silently becomes wrong. keepdims=True follows the axis argument automatically.
Dtype and zero totals
Dividing integer arrays with / gives floats, so a / a.sum(axis=1, keepdims=True) is safe. A row that sums to zero produces nan or inf with a runtime warning. If zero totals are possible, check for them before dividing or use np.divide with its where argument.
Checking your work
Before running a broadcast expression, print the shapes of both operands. Check the last dimensions first, then move left. Each pair must be equal or contain a 1. After normalizing, verify the result: shares.sum(axis=1) should be all ones, and centered.mean(axis=0) should be all zeros, up to floating-point error.
Exercise
A float array x has shape (4, 5, 6). You want to subtract from every element the minimum taken over axis 1. Write the expression, and give the shape of the minimum with and without keepdims=True.
Show answer
Use x - x.min(axis=1, keepdims=True). With keepdims=True the minimum has shape (4, 1, 6), which broadcasts against (4, 5, 6). Without it the shape is (4, 6). Broadcasting would line (4, 6) up with the last two axes of (4, 5, 6), comparing 6 with 5 on the middle axis, so it raises a ValueError.
Exercise
For a = np.array([[2, 4], [6, 8]]), what does a / a.sum(axis=0, keepdims=True) return, and what does each column sum to?
Show answer
The column sums are [8, 12], kept as shape (1, 2). The result is [[0.25, 0.3333...], [0.75, 0.6667...]]. Each column sums to 1, so result.sum(axis=0) is [1., 1.].