NumPy Essentials
Most ML coding rounds are graded on whether the math comes out right and whether it is vectorized. Vectorized
means the work happens inside NumPy's compiled loops, not in Python's, and getting there takes a small set of
tools used fluently: dtypes, broadcasting, axis arguments, einsum and indexing with arrays. This page covers
each one with the mistakes that cost candidates time.
Every example is runnable, and every one ends with an assert. That habit matters as much as the tools: in an
interview you want each line checked on a tiny input before you build on it.
Arrays, Dtypes and Views
An array has a shape, a dtype and a block of memory, and two of the three cause silent bugs. The dtype is fixed when the array is made, so writing a float into an integer array truncates it without a warning. Slicing returns a view onto the same memory, so writing into a slice changes the original.
import numpy as np
a = np.array([1, 2, 3]) # int64: built from Python ints
a[0] = 2.7 # assigning a float into an int array truncates
assert a.dtype == np.int64 and a[0] == 2
assert (a / 2).dtype == np.float64 # true division always gives floats
x = np.zeros((2, 3)) # float64 by default
row = x[0] # basic slicing returns a view
row[:] = 1.0
assert x[0].sum() == 3.0 # writing to the view changed x
safe = x[0].copy() # an independent array
small = np.array([200], dtype=np.uint8)
assert (small + 100)[0] == 44 # uint8 wraps around at 256, no error
Three rules cover most of it. Build float data with dtype=float or np.asarray(X, dtype=float) at the top of
your function, so integer inputs from a test case can't truncate your updates. Call .copy() whenever you will
modify something you were given, because mutating the caller's array is the kind of bug
debugging rounds plant on purpose. And keep float64 for interview code unless you
are asked about memory; float32 has about 7 significant digits, which is enough for training but makes
gradient checks noisy.
Broadcasting
Broadcasting is how NumPy combines arrays of different shapes without copying, and it replaces most loops. Line the shapes up from the right; each pair of sizes must be equal, or one of them must be 1, and a missing size counts as 1. A size-1 axis is stretched to match the other.
X = np.arange(6.0).reshape(2, 3) # (2, 3)
Z = X - X.mean(axis=0) # (2, 3) - (3,) -> (2, 3): center each column
assert np.allclose(Z.sum(axis=0), 0)
try:
X / X.sum(axis=1) # (2, 3) / (2,): trailing sizes 3 and 2 clash
except ValueError as e:
print("error:", e)
P = X / X.sum(axis=1, keepdims=True) # (2, 3) / (2, 1) -> (2, 3): normalize each row
assert np.allclose(P.sum(axis=1), 1)
The error is the good outcome. The bad one is when shapes happen to be compatible and broadcasting builds an
array you didn't mean. The classic case is subtracting a (n,) vector from a (n, 1) column, which produces an
(n, n) matrix instead of n differences:
y = np.array([1.0, 2.0, 3.0]) # (3,)
pred = np.array([[1.0], [2.0], [4.0]]) # (3, 1): e.g. the output of X @ W with W of shape (d, 1)
wrong = ((pred - y) ** 2).mean() # (3, 1) - (3,) -> (3, 3), averaged: no error
right = ((pred[:, 0] - y) ** 2).mean() # (3,) - (3,) -> (3,)
assert (pred - y).shape == (3, 3)
assert np.isclose(right, 1 / 3) and not np.isclose(wrong, right)
Here the wrong loss is 2.33 against the right 0.33, and nothing crashes. When a loss looks plausible but won't fall, print the shape of every intermediate; Getting Shapes Right has the habits that prevent this.
Turning Loops into Axes
To vectorize a loop, turn each loop index into an array axis, then reduce over the axis you were summing over.
A double loop over points i and centers j becomes an array of shape (n, k); a triple loop with an inner sum
over features becomes (n, k, d) summed over the last axis. Insert size-1 axes with None so broadcasting lines
the indices up.
rng = np.random.default_rng(0)
A, C = rng.normal(size=(5, 3)), rng.normal(size=(4, 3)) # (n, d), (k, d)
D_loop = np.zeros((5, 4))
for i in range(5):
for j in range(4):
D_loop[i, j] = ((A[i] - C[j]) ** 2).sum()
D_vec = ((A[:, None, :] - C[None, :, :]) ** 2).sum(axis=-1) # (n, 1, d) - (1, k, d) -> (n, k, d) -> (n, k)
assert np.allclose(D_loop, D_vec)
On 2,000 points and 500 centers in 32 dimensions, the double loop took about 1.8 seconds on a laptop and the
broadcast version about 0.1 seconds, more than 15 times faster. The broadcast version builds the full
(n, k, d) array, though, and that memory is what the expanded-square trick in K-Means
and KNN avoids. Write the loop version first when the math is unfamiliar; it becomes the
reference your vectorized version is tested against.
Axis Arguments
The axis argument names the axis that disappears. X.sum(axis=0) on a (n, d) array collapses the n rows
and returns one value per column, shape (d,); axis=1 returns one value per row. For a batch of sequences of
shape (B, T, D), the mean over time is axis=1, and negative axes count from the end, so axis=-1 is always
the feature axis no matter how many batch axes come first.
H = rng.normal(size=(2, 5, 4)) # (B, T, D)
assert H.mean(axis=1).shape == (2, 4) # average over time
assert H.max(axis=-1, keepdims=True).shape == (2, 5, 1) # keepdims leaves a size-1 axis to broadcast
labels = H.argmax(axis=-1) # (B, T): index of the largest feature per position
assert labels.shape == (2, 5) and labels.max() < 4
Use keepdims=True whenever the result will be combined with the original array, as in a softmax or a
normalization. Without it, a (B, T) result broadcasts against (B, T, D) by its trailing axis, which either
errors or, when T == D, quietly does the wrong thing. Test on shapes with all-different sizes, like
(2, 5, 4), so that mistake can't hide.
einsum
np.einsum writes a product of arrays as index notation: name each input's axes, name the output's axes, and
every index that is missing from the output is summed over. It is the clearest way to write batched and
multi-axis products, and the string doubles as documentation of the shapes.
Q, K = rng.normal(size=(2, 5, 4)), rng.normal(size=(2, 6, 4)) # (B, T, D), (B, S, D)
scores = np.einsum("btd,bsd->bts", Q, K) # (B, T, S)
assert np.allclose(scores, Q @ K.transpose(0, 2, 1))
M = rng.normal(size=(3, 3))
assert np.isclose(np.einsum("ii->", M), np.trace(M)) # repeated index, no output: trace
row_dots = np.einsum("nd,nd->n", A, A) # per-row dot product, (n,)
assert np.allclose(row_dots, (A ** 2).sum(axis=1))
Two cautions. einsum is not always the fastest path; for plain matrix products @ calls BLAS directly. And a
typo in the string produces a valid but wrong contraction, so check its shape and compare it once against an
explicit version, as above. Interviewers accept einsum when you can say what each letter means; one candidate's
report put it as "only a tool", with the round checking that you understand what it computes.
Fancy Indexing
Indexing with integer or boolean arrays selects arbitrary elements, and it is how you pick each row's label probability, gather neighbors or mask entries. Unlike slicing, it always returns a copy.
P = np.array([[0.7, 0.2, 0.1], [0.1, 0.3, 0.6]]) # (n, C) predicted probabilities
y = np.array([0, 2]) # (n,) true labels
picked = P[np.arange(2), y] # one element per row: P[0, 0], P[1, 2]
assert np.allclose(picked, [0.7, 0.6])
assert np.allclose(P[:, y], [[0.7, 0.1], [0.1, 0.6]]) # NOT the same: every row, columns y
big = P > 0.5 # boolean mask, (n, C)
assert P[big].tolist() == [0.7, 0.6] # 1D result: only the selected entries
order = np.argsort(-P, axis=1)[:, :2] # top-2 classes per row, (n, 2)
assert np.allclose(np.take_along_axis(P, order, axis=1), [[0.7, 0.2], [0.6, 0.3]])
P[np.arange(n), y] versus P[:, y] is the most common indexing bug in cross-entropy code: the second builds an
(n, n) matrix. Another trap is writing with repeated indices. counts[idx] += 1 applies each repeated index only
once, while np.add.at applies every one:
idx = np.array([0, 0, 1])
counts = np.zeros(2)
counts[idx] += 1 # buffered: index 0 counted once
assert counts.tolist() == [1, 1]
counts = np.zeros(2)
np.add.at(counts, idx, 1) # unbuffered: every occurrence counts
assert counts.tolist() == [2, 1]
assert np.bincount(idx, minlength=2).tolist() == [2, 1]
This is exactly the bug that makes k-means centroids drift toward the origin. For counts, np.bincount is faster
and clearer; for sums of rows grouped by label, use np.add.at or a one-hot matrix product.
Key Takeaways
- Convert inputs with
np.asarray(X, dtype=float)and.copy()anything you will modify. - Shapes line up from the right; a size-1 axis stretches. An unexpected
(n, n)from(n, 1) - (n,)is the most common silent bug. - To vectorize, make each loop index an axis, insert
Noneto line them up, then reduce over the summed axis. Keep the loop version as the test reference. axisnames the axis that disappears. Usekeepdims=Truewhen the result is combined with the input, and test on shapes whose sizes all differ.einsummakes multi-axis products readable; check its result once against@or a loop.P[np.arange(n), y]picks one entry per row. Repeated-index writes neednp.add.atornp.bincount.