TExcelTAD
Home › Math for Machine Learning › ML Math with NumPy

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∈RD\mathbf{x} \in \mathbb{R}^D x = np.array([...]), shape (D,) a 1-D array; NumPy does not distinguish rows and columns
X∈RN×DX \in \mathbb{R}^{N \times D} X.shape == (N, D) one example per row
xTy\mathbf{x}^T\mathbf{y} x @ y inner (dot) product
AxA\mathbf{x}, ABAB A @ x, A @ B matrix products
ATA^T, A−1A^{-1} A.T, np.linalg.inv(A) prefer solve over inv
∑n=1Nxn\sum_{n=1}^N x_n x.sum() axis=0 sums over examples
∥x∥2\lVert \mathbf{x} \rVert_2 np.linalg.norm(x) Euclidean length
1N∑nxn\frac{1}{N}\sum_n \mathbf{x}_n X.mean(axis=0) the sample mean, shape (D,)
xyT\mathbf{x}\mathbf{y}^T np.outer(x, y) outer product, a matrix

Vectorization: one formula, no loops

The mean squared error of a linear model f(x)=θTxf(\mathbf{x}) = \boldsymbol{\theta}^T\mathbf{x} over a dataset is

L(θ)=1N∑n=1N(yn−θTxn)2=1N∥y−Xθ∥2L(\boldsymbol{\theta}) = \frac{1}{N}\sum_{n=1}^{N} \left(y_n - \boldsymbol{\theta}^T\mathbf{x}_n\right)^2 = \frac{1}{N}\lVert \mathbf{y} - X\boldsymbol{\theta} \rVert^2

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.

python · try it yourself
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 xn−xˉ\mathbf{x}_n - \bar{\mathbf{x}}, or standardizing (xnd−μd)/σd(x_{nd} - \mu_d)/\sigma_d. NumPy broadcasting stretches a shape (D,) array across the N rows automatically.

python · try it yourself
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 @ theta is (N,), but if y had 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 AA instead of forming A−1A^{-1}, which is faster and more accurate (Numerical Linear Algebra).

Exercises

Exercise 1: Translate a formula

Write the NumPy expression for 1N∑n=1N∥xn∥2\frac{1}{N}\sum_{n=1}^{N} \lVert \mathbf{x}_n \rVert^2, given X of shape (N, D).

Answer

np.mean(np.sum(X**2, axis=1)) (or (X**2).sum() / len(X)).

Solution

∥xn∥2=∑dxnd2\lVert \mathbf{x}_n \rVert^2 = \sum_d x_{nd}^2 is a sum over the feature axis (axis=1), giving one number per example; the outer average is a mean over those NN numbers. Summing all squared entries and dividing by NN 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 (5×200)(200×5)=5×5(5 \times 200)(200 \times 5) = 5 \times 5. 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 uvT\mathbf{u}\mathbf{v}^T for u=(1,2)\mathbf{u} = (1, 2) and v=(3,4,5)\mathbf{v} = (3, 4, 5), and verify that its rank is 1.

Answer

[3456810]\begin{bmatrix} 3 & 4 & 5 \\ 6 & 8 & 10 \end{bmatrix}, rank 1.

Solution

Entry (i,j)(i, j) is uivju_i v_j, so every row is a multiple of v\mathbf{v} and the rank is 1.

python · try it yourself
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 1N∥y−Xθ∥2\frac{1}{N}\lVert \mathbf{y} - X\boldsymbol{\theta} \rVert^2?

  1. np.mean((y - X @ theta)**2)
  2. np.sum(y - X @ theta)
  3. (y - X @ theta).max()
  4. np.mean(y) - np.mean(X @ theta)

X.mean(axis=0) on an N×DN \times D data matrix returns…

  1. one mean per example, shape (N,)(N,)
  2. one mean per feature, shape (D,)(D,)
  3. a single number
  4. an N×DN \times D array

Why do the examples use np.random.default_rng(seed)?

  1. It is faster than other generators
  2. It makes random numbers reproducible, so every run gives the same output
  3. It produces truly random numbers
  4. NumPy requires it for matrices