ML Math with NumPy
Every formula in this course becomes a few lines of NumPy. This lesson sets up the translation table once: how vectors, matrices, sums, norms and expectations look as array code, and the three habits that prevent most bugs (check shapes, vectorize, seed your random numbers).
From notation to arrays
| Math | NumPy | Notes |
|---|---|---|
x = np.array([...]), shape (D,) |
a 1-D array; NumPy does not distinguish rows and columns | |
X.shape == (N, D) |
one example per row | |
x @ y |
inner (dot) product | |
| , | A @ x, A @ B |
matrix products |
| , | A.T, np.linalg.inv(A) |
prefer solve over inv |
x.sum() |
axis=0 sums over examples |
|
np.linalg.norm(x) |
Euclidean length | |
X.mean(axis=0) |
the sample mean, shape (D,) |
|
np.outer(x, y) |
outer product, a matrix |
Vectorization: one formula, no loops
The mean squared error of a linear model over a dataset is
The right-hand form is one matrix-vector product and one norm. Both versions give the same number, but the vectorized one is shorter and, on real data, much faster.
import numpy as np
rng = np.random.default_rng(0)
N, D = 1000, 3
X = rng.normal(size=(N, D))
theta_true = np.array([2.0, -1.0, 0.5])
y = X @ theta_true + 0.1 * rng.normal(size=N)
theta = np.array([1.5, -1.0, 0.0])
loop = 0.0
for n in range(N):
loop += (y[n] - theta @ X[n]) ** 2
loop /= N
vec = np.mean((y - X @ theta) ** 2)
print("shapes:", X.shape, theta.shape, (X @ theta).shape)
print("loop MSE:", round(loop, 6), " vectorized MSE:", round(float(vec), 6))shapes: (1000, 3) (3,) (1000,)
loop MSE: 0.514664 vectorized MSE: 0.514664
Broadcasting: centring and standardizing
Many ML formulas subtract a vector from every row: centring , or standardizing . NumPy broadcasting stretches a shape (D,) array across the N rows automatically.
import numpy as np
rng = np.random.default_rng(1)
X = rng.normal(loc=[10.0, -3.0], scale=[2.0, 0.5], size=(500, 2))
mu, sigma = X.mean(axis=0), X.std(axis=0)
Z = (X - mu) / sigma # (500, 2) - (2,) broadcasts row by row
print("mean before:", np.round(mu, 3), " std before:", np.round(sigma, 3))
print("mean after: ", np.round(Z.mean(axis=0), 6) + 0, " std after:", np.round(Z.std(axis=0), 6))mean before: [ 9.804 -3.005] std before: [1.936 0.501]
mean after: [0. 0.] std after: [1. 1.]
Warning: Broadcasting also happily combines shapes you did not mean to combine.
y - X @ thetais(N,), but ifyhad shape(N, 1)the difference would silently become(N, N). When a loss looks wrong, print the shapes.
Reproducible randomness
Initial weights, mini-batches and synthetic data all use random numbers. A seeded generator np.random.default_rng(seed) makes every run identical, which is essential for debugging and for comparing two versions of an algorithm fairly. All examples in this course are seeded, so your output matches the saved output exactly.
In software
- scikit-learn, PyTorch and JAX all use the row-per-example convention
(N, D)(PyTorch calls the first axis the batch dimension). - Libraries call optimized BLAS routines for
@; a vectorized formula gets that speed for free. np.linalg.solve(A, b)factorizes instead of forming , which is faster and more accurate (Numerical Linear Algebra).
Exercises
Exercise 1: Translate a formula
Write the NumPy expression for , given X of shape (N, D).
Answer
np.mean(np.sum(X**2, axis=1)) (or (X**2).sum() / len(X)).
Solution
is a sum over the feature axis (axis=1), giving one number per example; the outer average is a mean over those numbers. Summing all squared entries and dividing by gives the same value.
Exercise 2: Shape check
X has shape (200, 5) and w has shape (5,). What are the shapes of X @ w, X.T @ X and X - X.mean(axis=0)?
Answer
(200,), (5, 5) and (200, 5).
Solution
X @ w contracts the length-5 axis, leaving one value per row. X.T @ X is . X.mean(axis=0) has shape (5,) and broadcasts across the 200 rows, so the result keeps the shape of X.
Exercise 3: Outer products (code)
Compute for and , and verify that its rank is 1.
Answer
, rank 1.
Solution
Entry is , so every row is a multiple of and the rank is 1.
import numpy as np
M = np.outer([1, 2], [3, 4, 5])
print(M)
print("rank:", np.linalg.matrix_rank(M))[[ 3 4 5]
[ 6 8 10]]
rank: 1
Test yourself
Which NumPy expression computes ?
np.mean((y - X @ theta)**2)np.sum(y - X @ theta)(y - X @ theta).max()np.mean(y) - np.mean(X @ theta)
X.mean(axis=0) on an data matrix returns…
- one mean per example, shape
- one mean per feature, shape
- a single number
- an array
Why do the examples use np.random.default_rng(seed)?
- It is faster than other generators
- It makes random numbers reproducible, so every run gives the same output
- It produces truly random numbers
- NumPy requires it for matrices