Almost every piece of AI code in Python sits on top of NumPy, the library for working with arrays of numbers. Data tables, images, embeddings and a model’s weights are all arrays, and PyTorch’s tensors behave the same way. Three ideas make NumPy click: shapes and axes, broadcasting, and vectorization. Stop writing loops over numbers: tell NumPy what to do to the whole array, and let it do the looping. Here you’ll squash a table along each axis, line up shapes until they fit (or don’t), and time a loop against NumPy.
Arrays have shapes#
A NumPy array is a grid of numbers, all of the same type. Its shape says how big it is in each direction. Ice-cream sales for three shops over five days make an array of shape (3, 5): 3 rows, 5 columns. A batch of 32 grey 28-by-28-pixel images has shape (32, 28, 28). Each direction is an axis, numbered from 0: in the sales table, axis 0 runs down the rows (the shops) and axis 1 runs across the columns (the days).
Most NumPy functions that summarise an array, such as sum, mean and max, take an axis argument that says which direction to combine along. It’s the single most common source of confusion in NumPy, so try it before reading on.
Predict first
sales has shape (3, 5): 3 shops, 5 days. What shape is sales.sum(axis=0)?
The axis you name is the one that disappears. axis=0 squashes the shops together and leaves one number per day: Friday is the big day, with 89 sold. axis=1 squashes the days together and leaves one number per shop: the Station shop sold 122. With no axis, everything is combined into a single number, 259. keepdims=True keeps the squashed axis with size 1, so a per-shop total has shape (3, 1) instead of (3,). That looks like a detail, but it’s exactly what makes the next idea work.
Broadcasting: combining different shapes#
Arithmetic on arrays works element by element: add two (3, 5) arrays and each cell is added to its partner. But you often want to combine arrays of different shapes, such as subtracting each day’s average from every shop’s sales for that day. NumPy’s rule for this is called broadcasting:
- Line the two shapes up from the right.
- Each pair of sizes must be equal, or one of them must be 1. A missing size counts as 1.
- Wherever a size is 1, that array is stretched to match the other, as if it were copied.
Predict first
sales.mean(axis=1) is each shop’s average, shape (3,). What does sales - sales.mean(axis=1) do?
Subtracting each day’s average works straight away: (5,) lines up with the 5 days and is stretched down all three rows. Subtracting each shop’s average fails, because lined up from the right it meets the days. Keep the axis with keepdims=True, or add one with avg[:, None], and the averages have shape (3, 1), which stretches across the days. The last pair stretches both ways at once: a column and a row make a full grid of every combination. Per-column operations just work; per-row ones need a size-1 axis. That last pattern is everywhere in AI code: the distances between every pair of points, or the attention scores between every pair of words, are built the same way.
Vectorization: why NumPy is fast#
Writing np.sum(x * x) instead of a for loop isn’t just shorter. In a Python loop, the interpreter handles one number at a time, and each number is a separate Python object. NumPy stores the whole array as one block of raw numbers of a single type and runs the loop in compiled C, often using processor instructions that handle several numbers at once. Here’s the sum of squares of a million numbers both ways:
import timeit
import numpy as np
x = np.random.default_rng(0).random(1_000_000) # a million numbers
values = x.tolist() # the same numbers as a Python list
def python_loop():
total = 0.0
for v in values: # one at a time, in Python
total += v * v
return total
def with_numpy():
return np.sum(x * x) # all at once, in NumPy
loop = min(timeit.repeat(python_loop, number=1, repeat=7))
vec = min(timeit.repeat(with_numpy, number=1, repeat=7))
print(f"Python loop: {loop * 1000:.0f} ms NumPy: {vec * 1000:.1f} ms ({loop / vec:.0f} times faster)")
# Python loop: 25 ms NumPy: 1.0 ms (25 times faster)Across our runs NumPy was 17 to 25 times faster; on your machine the numbers will differ, and for heavier work such as matrix multiplication the gap is usually much wider. The habit to build is the same either way: when you catch yourself looping over the numbers in an array, look for the NumPy function that does it in one call.
Everyday NumPy#
The figures’ table in code (pip install numpy), with two more everyday moves: dividing by a keepdims total, and a boolean mask, an array of True and False that picks out the values you want:
import numpy as np
sales = np.array([[12, 15, 9, 20, 31], # Harbour, Mon to Fri
[ 7, 8, 6, 11, 18], # Park
[22, 19, 17, 24, 40]]) # Station
print(sales.shape) # (3, 5)
print(sales.sum(axis=0)) # one total per day
print(sales.sum(axis=1)) # one total per shop
share = sales / sales.sum(axis=1, keepdims=True) # each day's share of that shop's week
print(share.round(2))
print(sales[sales > 20]) # a boolean mask picks out the busy days
print((sales > 20).sum()) # True counts as 1, so this counts them
# (3, 5)
# [41 42 32 55 89]
# [ 87 50 122]
# [[0.14 0.17 0.1 0.23 0.36]
# [0.14 0.16 0.12 0.22 0.36]
# [0.18 0.16 0.14 0.2 0.33]]
# [31 22 24 40]
# 4Every shop sells about a third of its week’s ice cream on Friday. The same code works on PyTorch tensors with almost no changes, since PyTorch follows NumPy’s broadcasting rules; there the axis argument is usually called dim.
What to remember
- Every array has a shape; reductions such as sum and mean take an axis, and the axis you name is the one that disappears.
- Broadcasting lines shapes up from the right and stretches sizes of 1; use keepdims or [:, None] for per-row operations, and print shapes when results look odd.
- Vectorized NumPy runs the loop in compiled code, many times faster than a Python loop over the same numbers.