NumPy arrays: shapes, axes and broadcasting
- Read a shape as rows, columns and how many tables, and say which axis an average or a max removes
- Use keepdims so a result still lines up with the grid it came from
- Work out by hand whether two shapes broadcast, and what the result's shape is
- Pick rows, columns and one entry per row, and add an axis with None
- Multiply stacks of matrices with @, and flip the last two axes with swapaxes
- Tell reshape from transpose, and build a masked softmax from all of it
Four functions, four array moves
Model coding rounds ask you to write attention, a small GPT or backprop in NumPy or PyTorch. Most lines of those programs make one of a few array moves: reduce along an axis and use the result on the same table, pick one entry per row, add an axis, or multiply stacks of matrices. A wrong move often runs with no error. This lesson's practice problem puts the moves in four small functions:
Write four NumPy functions with no Python loops over rows, positions or batches.
...means any number of leading axes, like a batch and heads.
normalize_rows(x):xis(..., n)with positive entries. Return the same shape, with each row divided by its own sum.standardize(x, eps=1e-5): return the same shape, with each row shifted to mean 0 and divided bysqrt(var + eps), wherevaris the row's variance.pick(probs, labels):probsis(..., k), andlabelsholds one class number per row, shape(...). Return each row's probability at its label.cosine_scores(a, b):ais(..., n, d)andbis(..., m, d). Return(..., n, m): the cosine similarity of every row ofawith every row ofb.
Call Returns normalize_rows([[1, 3], [2, 2]])[[0.25, 0.75], [0.5, 0.5]]standardize([[1, 2, 3]])[[-1.22, 0, 1.22]], roundedpick([[0.7, 0.2, 0.1], [0.1, 0.8, 0.1]], [0, 1])[0.7, 0.8]cosine_scores([[1, 0]], [[2, 0], [0, 3]])[[1, 0]]
The tests use square inputs on purpose. On a square table, a missing keepdims runs with no error and gives wrong numbers. By the end of Part 2 you'll see why, and you'll spot it on sight.
This lesson teaches the moves one at a time on one small table, students' scores on three tests: shapes and axes, keepdims, broadcasting, picking entries, and @ on stacks. Thirteen steps end with a small task in the editor. The whole problem comes back at the end, as the lesson's practice, from a blank file.
An array is a table with a shape
Every example in this lesson uses the same small table: students' scores on three tests. Here are two students.
import numpy as np
# Ana
scores = np.array([[70, 80, 90],
# Ben
[50, 100, 60]])
print(scores.shape)
(2, 3)
The shape is the size of the table: 2 rows and 3 columns. Each row is one student. Each column is one test.
scores (2, 3)down↓
Each direction is an axis. Axis 0 runs down the rows, from student to student. Axis 1 runs across the columns, from test to test.
You can also count axes from the end. Axis -1 is the last one. In this table that's axis 1, the tests.
More axes: a stack of tables
Now take two classes, each with two students and the same three tests.
# class 0: Ana
classes = np.array([[[70, 80, 90],
# Ben
[50, 100, 60]],
# class 1: Dee
[[85, 75, 95],
# Eli
[60, 70, 80]]])
print(classes.shape)
(2, 2, 3)
That's two tables, one per class.
classes[0] (2, 3)classes[1] (2, 3)Read a shape from the right. The last number is the columns: 3 tests. The one before it is the rows: 2 students. Anything in front of those two only counts tables: 2 classes.
That's the whole trick for big arrays. A batch of 32 images, each 28 by 28 pixels, is (32, 28, 28): 32 tables of 28 rows and 28 columns.
Average along an axis, and that axis is gone
Two questions about the same table. How many points did each test hand out? How many did each student score in all?
# down the rows: one number per test
print(scores.sum(axis=0))
# across the columns: one number per student
print(scores.sum(axis=1))
[120 180 150]
[240 210]
axis=0 runs down the rows, so it squashes the two students together and leaves one number per test. axis=1 runs across the columns, so it squashes the three tests together and leaves one number per student.
Pick an axis and watch which numbers get squashed together. Try max and mean too.
scores.sum(axis=0)(2, 3)→(3,)the 2 students are goneOne rule covers it: the axis you name is the axis that disappears. (2, 3) summed over axis 0 loses the 2 and becomes (3,). Summed over axis 1 it loses the 3 and becomes (2,).
mean, max, min and var, the variance, work the same way. scores.max(axis=1) is each student's best score: [ 90 100].
In the editor, scores is the same table. Fill in test_avgs, one average per test, and student_avgs, one average per student. Each line prints the result and its shape, so you can see which axis went away.
keepdims keeps the axis, with size 1
Here's the next question: how far is each score below that student's own best? To answer it, each student's best has to sit next to that student's row.
best = scores.max(axis=1)
print(best)
print(best.shape)
[ 90 100]
(2,)
That's the two best scores in a flat list. The list has lost track of which row each number came from. Ask for keepdims=True and the axis stays, with length 1:
best = scores.max(axis=1, keepdims=True)
print(best)
print(best.shape)
[[ 90]
[100]]
(2, 1)
Same two numbers. Now they stand in a column, one per row, beside the row they belong to.
Turn keepdims on and off, and watch where the two best scores go.
scores.max(axis=1)(2, 3)→(2,)the 3 tests are goneThe next part shows why the column matters.
In the editor, write row_max(scores): each row's largest number, kept as a column. Reduce over axis=-1, the last axis, so a stack of tables works too.
Karpathy wants each row of a 27 by 27 table of counts to add up to 1. He sums along one dimension and compares the shapes he gets back. With keepdim he gets a 1 by 27 row or a 27 by 1 column, and without it a flat 27. PyTorch says dim and keepdim where NumPy says axis and keepdims.
Broadcasting: a small array stretches to fit the table
You can add a smaller array to the table, or subtract one from it. NumPy acts as if it copies the small array until it is as big as the table, then works number by number. That copying is called broadcasting. NumPy never really makes the copies in memory, but picture it that way.
The teacher gives bonus points: 5 on test 1, none on test 2, 10 on test 3. Every student gets the same bonus, so the bonus is one number per test.
scores (2, 3)bonus (3,) stretched to (2, 3)The 3 bonus numbers sit under the 3 tests. NumPy copies them down onto every student's row, then adds. In code:
# one number per test
bonus = np.array([5, 0, 10])
print(scores + bonus)
[[ 75 80 100]
[ 55 100 70]]
One number per student, used for every test
Now the question from before: how far is each score below that student's best? best is the column from the keepdims section, one number per student.
scores (2, 3)best (2, 1) stretched to (2, 3)This time NumPy copies each student's best across that student's row:
# (2, 1): 90 for Ana, 100 for Ben
best = scores.max(axis=1, keepdims=True)
print(scores - best)
[[-20 -10 0]
[-50 0 -40]]
Ana's best is 90, so her scores drop by 90. Ben's best is 100, so his scores drop by 100.
In the editor, fill in below_best, each score minus that student's best, as printed here, and vs_test_avg, each score minus that test's average. One needs keepdims, and the other works without it. Work out which before you run it.
The rule NumPy uses
How does NumPy know which way to copy? It looks only at the two shapes:
- Line the two shapes up on the right.
- Compare the sizes one position at a time. Two sizes fit if they are equal, or if one of them is 1. A missing size counts as 1.
- Every 1 stretches to match the size across from it.
Here is the check for both examples, and for a third that fails:
scores + bonusscores23bonusnone3checknone: stretchesequalresult23scores - bestscores23best21checkequal1 stretchesresult23scores - scores.max(axis=1)scores23scores.max(axis=1)none2checknone: stretches3 vs 2resulterrorLining up on the right is why bonus lands on the tests. Its 3 numbers sit under the table's last size, the 3 tests. It has no size for the students, and a missing size stretches.
In the editor, a to e are five pairs of shapes. Work out each result's shape with the rule, and write it as a tuple, or None where the shapes don't fit. Then run it to check.
Karpathy asks whether a 27 by 27 table can be divided by a 27 by 1 column. He lines the shapes up on the right, checks each pair, and the 1 stretches to 27. PyTorch broadcasts by the same rule as NumPy.
When the shapes don't fit
The third example in the rule's figure, one step back, is the flat best, the one without keepdims:
scores - scores.max(axis=1)
ValueError: operands could not be broadcast together with shapes (2,3) (2,)
The flat best is (2,). Lined up on the right, its 2 sits under the table's 3 tests. 3 and 2 are not equal, and neither is 1, so NumPy stops.
scores23scores.max(axis=1)none2checknone: stretches3 vs 2resulterrorscores (2, 3)scores.max(axis=1) (2,), lined up on the rightAn error is the good outcome, because it tells you something is wrong. The bad outcome is next.
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.
square33square.max(axis=1)none3checknone: stretchesequalresult33Red cells took another student's best. Only the diagonal is right.
square (3, 3)square.max(axis=1) (3,) stretched to (3, 3)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.
Andrej Karpathy hits this exact bug in PyTorch, which broadcasts by the same rule. He normalizes the rows of a 27 by 27 table of counts, leaves out keepdim, and the code runs while normalizing the columns instead.
Picking things out of the table
This section uses the three-student table. The small numbers are the positions, counted from 0.
square (3, 3)0test 2
1test 3
20 Ana7080901 Ben50100602 Cal807075
Square brackets take one entry per axis: first the row, then the column. Counting starts at 0.
print(square[1]) # row 1: Ben
# column 2: test 3, for everyone
print(square[:, 2])
[ 50 100 60]
[90 60 75]
square[1] is Ben's row. square[:, 2] is test 3 for every student. The : means all of this axis, so [:, 2] reads as every row, column 2.
A number removes the axis. A slice keeps it
Picking a column can keep its axis or drop it.
print(square[:, 2].shape)
print(square[:, 2:3].shape)
(3,)
(3, 1)
2 is one number, so the column axis is gone and you get a flat list. 2:3 is a slice, a range that happens to hold one column, so the axis stays and you get a column. It's the same choice as keepdims.
... means every axis you didn't write. classes[..., 2] is test 3 for every student in every class, however many axes come first.
In the editor, fill in test3, test 3 for every student kept as a column, and vs_test3, each score minus that student's own test 3 score. square is square, so a flat test3 runs with no error.
None adds an axis of size 1
Which students beat which, on average? That's every student against every student, so the answer is a 3 by 3 table.
# one average per student
avg = square.mean(axis=1)
print(avg)
print(avg[:, None] > avg[None, :])
[80. 70. 75.]
[[False True True]
[False False False]
[False True False]]
None in the brackets adds an axis of size 1 at that spot. avg[:, None] turns the averages into a column (3, 1). avg[None, :] turns them into a row (1, 3). Comparing a column with a row stretches both, so every pair gets compared:
avg[:, None]31avg[None, :]13check1 stretches1 stretchesresult33avg[:, None] (3, 1) stretched to (3, 3)avg[None, :] (1, 3) stretched to (3, 3)Row i, column j answers one question: did student i's average beat student j's?
Ana beat Ben and Cal. Cal beat Ben. Ben beat nobody.
In the editor, fill in gaps: row i, column j holds student i's average minus student j's. gaps[0, 1] should be 10, Ana's 80 minus Ben's 70.
Two lists pick one entry per row
Each student chose one test to retake. Which score is that, for each student?
# Ana chose test 1, Ben test 3, Cal test 2
chosen = np.array([0, 2, 1])
print(square[np.arange(3), chosen])
[70 60 70]
np.arange(3) is [0, 1, 2], one number per row. The two lists pair up, position by position. The other two buttons are the usual mistakes.
square (3, 3)0test 2
1test 3
20 Ana7080901 Ben50100602 Cal807075
np.arange(3)chosenresultsquare[1, 2] is Ben, test 3: 60You get one number per student. In machine learning the same line pulls out the probability of the right answer for each example: probs[np.arange(n), labels].
Don't write square[:, chosen] for this. : keeps every row, and chosen then picks columns 0, 2 and 1 from each row. That's a (3, 3) table, not one score per student.
In the editor, write pick(probs, labels): entry i is probs[i, labels[i]]. The editor runs it on square with each student's chosen test, and the checks run it on probabilities.
Karpathy needs the probability his model gave the right next character, for each of 5 examples. He pairs torch.arange(5) with the labels to pull out one number per row, then averages their negative logs into the loss. NumPy indexes the same way.
A slice is a window, not a copy
A plain slice like square[0] is a window onto the same numbers, not a copy. Write into it and the table changes too:
table = square.copy()
# a window onto Ana's row
ana = table[0]
ana[:] = 0
print(table)
[[ 0 0 0]
[ 50 100 60]
[ 80 70 75]]
So a function that writes into its input changes the caller's array. table.copy() above made a real copy first, so square is untouched. np.where(mask, a, b) also builds a new array and leaves its inputs alone.
In the editor, drop_test1(x) sets test 1 to 0 for everyone. Fill in its first line so it writes into a copy and leaves the caller's table alone. The last line prints square, so you can see whether it changed.
@ multiplies the last two axes
The final grade weights the tests: 20% for test 1, 30% for test 2, 50% for test 3.
# one weight per test
weights = np.array([0.2, 0.3, 0.5])
print(square @ weights)
[83. 70. 74.5]
@ is matrix multiply. Here it multiplies each student's row by the weights, number by number, and adds them up. That's one final grade per student. Ana: 0.2*70 + 0.3*80 + 0.5*90 = 83.
Tap a grade to see its row of scores meet the weights:
square(3, 3)@weights(3,)→(3,)the two 3s meet, get added up, and disappearNow compare two ways of grading. Scheme A is the weights above. Scheme B counts only test 3. Put each scheme in a column:
# test 1
schemes = np.array([[0.2, 0.0],
# test 2
[0.3, 0.0],
# test 3
[0.5, 1.0]])
print(square @ schemes)
[[83. 90. ]
[70. 60. ]
[74.5 75. ]]
Each row is a student. Each column is a scheme. Entry [i, j] is student i's row times scheme j's column, added up. Ben gets 70 under scheme A and 60 under scheme B.
square(3, 3)@schemes(3, 2)→(3, 2)the two 3s meet, get added up, and disappearIn the editor, fill in schemes with one column per scheme. Scheme A is the weights above. Scheme B counts tests 2 and 3, half each. Then fill in grades with one @: one row per student, one column per scheme.
On a stack, @ works table by table
classes holds two tables. @ multiplies only the last two axes. The axes in front just count tables, and each table is done on its own:
print(classes @ weights)
[[83. 70.]
[87. 73.]]
Each table on its own is the same @ as before. Switch between the two classes:
classes[0](2, 3)@weights(3,)→(2,)the two 3s meet, get added up, and disappearClass 0 is Ana and Ben, 83 and 70. Class 1 is Dee and Eli, 87 and 73.
Use swapaxes, not .T, on a stack
To compare every student with every other student in the same class, multiply each table by its own flip. The flip turns rows into columns, so that each student's row meets every other student's row.
On a single table, .T is that flip. On a stack, .T flips every axis, including the class axis, and that's not what you want:
print(classes.T.shape)
print(np.swapaxes(classes, -1, -2).shape)
(3, 2, 2)
(2, 3, 2)
classes.T turned (2, 2, 3) into (3, 2, 2). It reversed all three axes. np.swapaxes(classes, -1, -2) swaps only the last two, students and tests, and leaves the class axis alone. Each class's (2, 3) table times its own (3, 2) flip gives a 2 by 2 table of student against student.
In the editor, write gram(x): entry [i, j] is row i dotted with row j, for one table or a stack of them. The editor prints the shape for classes, which should be (2, 2, 2).
reshape pours, transpose moves
Both of these turn the two-student table, (2, 3), into a (3, 2) table. Only one keeps the meaning.
print(scores.T)
print(scores.reshape(3, 2))
[[ 70 50]
[ 80 100]
[ 90 60]]
[[ 70 80]
[ 90 50]
[100 60]]
scores.T is the transpose: each test is now a row, and each student is a column. Every number still belongs to its student and its test.
scores.reshape(3, 2) reads the numbers in order, 70, 80, 90, 50, 100, 60, and pours them into rows of two. Its second row is [90, 50]: Ana's test 3 next to Ben's test 1. That row means nothing.
Each number below wears its student's color. Switch between the two and watch the colors.
scores (2, 3)scores.T (3, 2)scoresscores.Tscores and number 3 in the result. Transpose moved it, and every number still belongs to its student and its test.- reshape reads the numbers in order and pours them into the new shape. The order never changes. Only the line breaks move.
- transpose moves numbers. What was a column is now a row.
So use reshape to split one axis into two, or to join two axes that sit next to each other. Joining the class axis and the student axis of classes puts every student in one table:
print(classes.reshape(-1, 3))
[[ 70 80 90]
[ 50 100 60]
[ 85 75 95]
[ 60 70 80]]
-1 means: work this size out for me. Four students in all, Ana, Ben, Dee and Eli, each with 3 tests. That join is safe, because class and student sit next to each other and stay in order.
When axes must change places, use a transpose. np.transpose(classes, (2, 0, 1)) lists the old axes in their new order: tests first, then classes, then students, so the shape becomes (3, 2, 2).
The classic bug is a reshape where a transpose belongs. The shape comes out right and the numbers are scrambled, like the [90, 50] row above.
In the editor, fill in everyone, all four students of classes in one (4, 3) table, and by_test, the same scores with one row per test and one column per student.
Put it together: a masked softmax
A shop shows each user three products. It gives each product a match score for each user. Then it turns each user's scores into chances that add up to 1, so better matches get shown more often. That last step is a softmax.
One rule: a product the user already bought must get chance 0.
# user 0's score for products 0, 1, 2
match = np.array([[2., 1., 0.],
# user 1
[0., 3., 1.],
# user 2
[1., 1., 1.]])
# user 0 bought product 1
bought = np.array([[False, True, False],
# user 1 bought nothing
[False, False, False],
# user 2 bought product 0
[True, False, False]])
masked = np.where(bought, -np.inf, match)
print(masked)
[[ 2. -inf 0.]
[ 0. 3. 1.]
[-inf 1. 1.]]
np.where(bought, -np.inf, match) takes minus infinity where bought is True and the match score everywhere else. Minus infinity is the trick: in a softmax it becomes exactly 0.
Now the softmax. It turns each row into chances that add up to 1:
def softmax(x: np.ndarray, axis: int = -1) -> np.ndarray:
"""Turns each row of x into chances that add up to 1."""
# each row minus its max
z = x - x.max(axis=axis, keepdims=True)
# every number is positive
e = np.exp(z)
return e / e.sum(axis=axis, keepdims=True)
chance = softmax(masked, axis=-1)
print(chance.round(3))
print(chance.sum(axis=-1))
[[0.881 0. 0.119]
[0.042 0.844 0.114]
[0. 0.5 0.5 ]]
[1. 1. 1.]
The last line divides each row by its own total, so every row adds up to 1. Every product a user bought has chance 0, because exp(-inf) is 0. User 2 gave products 1 and 2 the same score, so they get the same chance, 0.5 each.
Subtracting each row's max first doesn't change the result. It keeps exp from overflowing when scores are large.
Look at what the function used: a max along an axis, keepdims, and broadcasting, twice. That's this lesson.
In the editor, write masked_softmax(match, bought) from the two pieces above: the np.where mask, then the softmax along the last axis. The checks use a stack of tables and very large scores.
The practice problem, start to finish
That's every move the practice problem needs. It asks for the four functions from the start of the lesson, from a blank file, one level at a time.
1.
sqis a(3, 3)array. What doessq - sq.max(axis=1)do?2.What shape does
np.ones((8, 1, 5)) + np.ones((3, 1))produce?3.
qis(2, 4, 8, 16)andkis(2, 4, 10, 16): stacks of grids with 16 numbers in each row. Which line dots every row ofqwith every row ofk, grid by grid?4.
x = np.arange(6).reshape(2, 3). What isx.reshape(3, 2)[0]?5.
pis(4, 3)class probabilities andyis(4,)labels. What isp[:, y].shape?6.You mask entries by setting their scores to 0 instead of -inf. What happens after the softmax?
Practice
Sources (5)
- numpy.sum · NumPy 2.5 documentation · Jun 21, 2026
“If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.”
- Broadcasting · NumPy 2.5 documentation · Jun 21, 2026
“When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing (i.e. rightmost) dimension and works its way left. Two dimensions are compatible when they are equal, or one of them is 1.”
- Indexing on ndarrays · NumPy 2.5 documentation · Jun 21, 2026
“All arrays generated by basic slicing are always views of the original array.”
- numpy.matmul · NumPy 2.5 documentation · Jun 21, 2026
“If either argument is N-D, N > 2, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly.”
- numpy.reshape · NumPy 2.5 documentation · Jun 21, 2026
“Read the elements of a using this index order, and place the elements into the reshaped array using this index order.”