12/26
Part 2 of 4 · BroadcastingLearn and do

A square table hides the mistake

Add a third student, Cal. Now the table is 3 students by 3 tests, and the same mistake runs with no error:

# Ana
square = np.array([[70, 80, 90],
                   # Ben
                   [50, 100, 60],
                   # Cal
                   [80, 70, 75]])
# wrong
print(square - square.max(axis=1))
# right
print(square - square.max(axis=1, keepdims=True))
[[-20 -20  10]
 [-40   0 -20]
 [-10 -30  -5]]
[[-20 -10   0]
 [-50   0 -40]
 [  0 -10  -5]]

The three best scores are 90, 100 and 80. Without keepdims they make a flat (3,), and 3 lines up with the 3 tests. So NumPy uses them like the bonus, one number per test: test 1 loses Ana's best, test 2 loses Ben's, test 3 loses Cal's. The numbers are wrong, the shape is right, and nothing warns you.

The square table, without and with keepdimsInteractive
Shapes, lined up on the right
rowscolumnssquare33square.max(axis=1)none3checknone: stretchesequalresult33

Red cells took another student's best. Only the diagonal is right.

square (3, 3)
test 1test 2test 3AnaBenCal
−
square.max(axis=1) (3,) stretched to (3, 3)
=
result (3, 3)
test 1test 2test 3AnaBenCal
Ben, test 3: 60 - 80 = -20. The 80 is Cal's best, but this row is Ben.
real numbers copies NumPy acts as if it madeTap a cell to see where its numbers come from.

Square tables are common: any table that compares a set of things with itself is one. When a result goes back onto the table it came from, keep the axis.

In the editor, write center_rows(x): each row minus its own mean. The checks include a square table, where a missing keepdims runs and gives wrong numbers.