32. Math for ML — Cheat sheet
The essentials of module 32 on one page: each formula next to its NumPy one-liner. Every runnable block on this page is checked against its output.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Math |
|---|---|---|
| turn one row into a feature vector | df.loc[i, cols].to_numpy(dtype=float) |
|
| build the data matrix | df[cols].to_numpy(dtype=float) |
|
| standardize every column | (X - X.mean(axis=0)) / X.std(axis=0) |
|
| take a weighted sum | w @ x |
|
| predict for every row | X @ w + b |
|
| add an intercept column | np.column_stack([np.ones(n), X]) |
design matrix |
| get the length of a vector | np.linalg.norm(x) |
|
| get the L1 norm | np.linalg.norm(x, ord=1) |
|
| measure the distance from one row to all rows | np.linalg.norm(X - q, axis=1) |
|
| compare directions | u @ v / (norm(u) * norm(v)) |
|
| make a unit vector | v / np.linalg.norm(v) |
|
| transpose | X.T |
|
| solve a square system | np.linalg.solve(A, b) |
|
| fit least squares | np.linalg.lstsq(A, y)[0] |
|
| check how fragile a matrix is | np.linalg.cond(A) |
condition number |
| get a numerical derivative | (f(w + h) - f(w - h)) / (2 * h) |
central difference |
| get the MSE gradient | 2 / n * A.T @ (A @ w - y) |
|
| take one gradient descent step | w = w - lr * grad |
|
| shuffle rows into mini-batches | np.array_split(rng.permutation(n), n // 32) |
|
| compare two weight vectors with a tolerance | np.allclose(a, b, rtol=0, atol=1e-6) |
|
| compute an expected value | values @ probs |
|
| compute a conditional probability | a[b].mean() (boolean arrays) |
|
| turn a score into a probability | 1 / (1 + np.exp(-z)) |
|
| compute log loss | -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p)) |
binary cross-entropy |
Read the notation
Section titled “Read the notation”| Math | Read as | NumPy |
|---|---|---|
| element (math counts from 1) | x[i - 1] |
|
| row , column | X[i - 1, j - 1] |
|
| add to | a.sum() |
|
| the mean | a.mean() |
|
| multiply all | np.prod(a) (underflows; prefer a sum of logs) |
|
| prediction | y_pred |
|
| all weights but the first | w[1:] |
|
| slope of in direction | grad[j] |
|
| the gradient vector | grad |
|
| (eta), (lambda) | learning rate, penalty strength | lr, lam |
| , | exponential, natural log | np.exp(z), np.log(z) |
Vectors, dot products and norms
Section titled “Vectors, dot products and norms”import numpy as np
np.set_printoptions(precision=3, suppress=True)x = np.array([2420.0, 4, 3.5]) # sqft, bedrooms, bathrooms of one housew = np.array([0.2, 5, 15]) # weights, thousand USD per unitprint(w @ x, np.sum(w * x)) # dot product two waysd = np.array([-810.0, -2, -1.5]) # difference between two housesnorms = [np.linalg.norm(d, ord=o) for o in (2, 1, np.inf)] # L2, L1, L-infinityprint(np.round(norms, 3))u, v = np.array([1.0, 1, 0]), np.array([2.0, 2, 0])cosine = u @ v / (np.linalg.norm(u) * np.linalg.norm(v))print(round(cosine, 3)) # same direction: 1556.5 556.5[810.004 813.5 810. ]1.0| Norm | Formula | NumPy | ML use |
|---|---|---|---|
| L2 | norm(x) |
Euclidean distance, KNN, k-means, gradient size | |
| squared L2 | x @ x |
MSE, Ridge penalty | |
| L1 | norm(x, ord=1) |
Manhattan distance, MAE, Lasso penalty | |
| L-infinity | norm(x, ord=np.inf) |
worst-case difference, tolerance checks |
| Similarity | Range | Ignores length? | Use |
|---|---|---|---|
| dot product | any | no | scores, linear models |
| cosine | −1 to 1 (0 to 1 for counts) | yes | text, embeddings, profiles |
| Euclidean distance | 0 and up | no | nearest neighbors, clustering |
Matrices and shapes
Section titled “Matrices and shapes”| Expression | Shapes | Result | Meaning |
|---|---|---|---|
X @ w |
(n, p) @ (p,) |
(n,) |
one prediction per row |
X @ W |
(n, p) @ (p, k) |
(n, k) |
k outputs per row |
X.T @ X |
(p, n) @ (n, p) |
(p, p) |
feature × feature sums; / n on standardized data is the correlation matrix |
X.T @ r |
(p, n) @ (n,) |
(p,) |
feature × error sums: the gradient core |
u @ v |
(p,) @ (p,) |
() |
dot product |
X * w |
(n, p) * (p,) |
(n, p) |
element-wise, broadcast over rows; not a product sum |
X - X.mean(axis=0) |
(n, p) - (p,) |
(n, p) |
center every column |
Rules: the inner sizes must match. in general. . .
Solving and least squares
Section titled “Solving and least squares”units = np.array([[101, 63, 31], [56, 34, 17], [42, 29, 11]])revenue = np.array([64034.99, 35028.44, 24869.58])print(np.linalg.solve(units, revenue)) # square system: exact answer
rng = np.random.default_rng(42)A = np.column_stack([np.ones(50), rng.normal(size=(50, 2))])y = A @ np.array([3.0, 2.0, -1.0]) + rng.normal(0, 0.1, 50)w_ls, residual_ss, rank, sv = np.linalg.lstsq(A, y) # tall system: least squaresprint(w_ls, rank)print(np.allclose(w_ls, np.linalg.solve(A.T @ A, A.T @ y))) # normal equations[ 79.99 249. 1299. ][ 2.994 2.01 -1.017] 3True| Situation | Use | Avoid |
|---|---|---|
| square system with one answer | np.linalg.solve(A, b) |
np.linalg.inv(A) @ b |
| tall least-squares problem | np.linalg.lstsq(X, y) |
inv(X.T @ X) @ X.T @ y |
| nearly dependent columns | lstsq (check rank and np.linalg.cond) |
any explicit inverse |
| Ridge closed form | solve(A.T @ A + n * lam * D, A.T @ y), D = identity with D[0, 0] = 0 |
penalizing the intercept |
Derivatives, gradients and the chain rule
Section titled “Derivatives, gradients and the chain rule”| Rule | Formula | Example |
|---|---|---|
| power | ||
| constant factor | ||
| sum | a mean of losses has the mean of the slopes | |
| chain | ||
| exponential | ||
| log | ||
| sigmoid | largest (0.25) at |
| Loss | Formula | Gradient |
|---|---|---|
| MSE | ||
| MSE + Ridge | ||
| log loss | , |
Gradient check: compare the analytic gradient with central differences.
def mse_loss(w, A, y): return float(np.mean((A @ w - y) ** 2))
def mse_grad(w, A, y): return 2 / len(y) * A.T @ (A @ w - y)
def numerical_grad(f, w, h=1e-5): eye = np.eye(len(w)) return np.array([(f(w + h * e) - f(w - h * e)) / (2 * h) for e in eye])
w0 = np.array([1.0, 1.0, 1.0])g_a = mse_grad(w0, A, y)g_n = numerical_grad(lambda w: mse_loss(w, A, y), w0)print(np.linalg.norm(g_a - g_n) / np.linalg.norm(g_a + g_n) < 1e-7)TrueGradient descent
Section titled “Gradient descent”def gradient_descent(A, y, lr=0.1, tol=1e-8, max_iter=10_000): w = np.zeros(A.shape[1]) for i in range(max_iter): grad = mse_grad(w, A, y) if np.linalg.norm(grad) < tol: # flat: at the minimum return w, i w = w - lr * grad # step against the gradient return w, max_iter
w_gd, steps = gradient_descent(A, y, lr=0.3)print(steps, np.allclose(w_gd, w_ls, rtol=0, atol=1e-6))67 TrueMini-batch epoch:
def minibatch_epoch(w, A, y, lr, batch_size, rng): for batch in np.array_split(rng.permutation(len(y)), max(len(y) // batch_size, 1)): w = w - lr * mse_grad(w, A[batch], y[batch]) return w
w_mb = np.zeros(3)for _ in range(30): w_mb = minibatch_epoch(w_mb, A, y, lr=0.05, batch_size=10, rng=rng)print(w_mb.round(2))[ 3. 2.01 -1.01]| Loss curve looks like | Diagnosis | Fix |
|---|---|---|
| falls in a slow, straight line | learning rate too small | raise it (×3 to ×10) |
| drops fast, then flat at the minimum | good | keep it |
| zig-zags but falls | close to the stability limit | lower it a little |
rises, then inf or nan |
too large: divergence | lower it (÷3 to ÷10); standardize the features |
| wobbles around a floor (mini-batch) | gradient noise | smaller rate, larger batch, or a learning-rate schedule |
| Variant | Rows per step | Gradient | Notes |
|---|---|---|---|
| batch | all n |
exact | reaches the closed-form answer |
| mini-batch | 32–256 | noisy | the deep-learning default; shuffle every epoch |
| stochastic | 1 | very noisy | streaming and online learning |
Probability for ML
Section titled “Probability for ML”| Idea | Formula | NumPy |
|---|---|---|
| expected value | values @ probs or t.mean() |
|
| variance | ((values - m) ** 2) @ probs or t.var() |
|
| conditional probability | a[b].mean() |
|
| independence | np.isclose(a[b].mean(), a.mean()) |
|
| Bayes’ rule | see below | |
| evidence | ||
| log-likelihood (0/1 data) | maximized at y.mean() |
|
| sigmoid | 1 / (1 + np.exp(-z)) |
|
| log-odds | np.log(p / (1 - p)) |
prior, p_e_given_a, p_e_given_not_a = 0.193, 0.174, 0.056 # churn, few loginsevidence = p_e_given_a * prior + p_e_given_not_a * (1 - prior)print(round(p_e_given_a * prior / evidence, 3)) # posterior
def log_loss(y, p, eps=1e-15): p = np.clip(p, eps, 1 - eps) # avoid log(0) return float(-np.mean(y * np.log(p) + (1 - y) * np.log(1 - p)))
z = np.array([-2.0, 0.0, 3.0])p = 1 / (1 + np.exp(-z))print(p.round(3), round(log_loss(np.array([0, 1, 1]), p), 3))0.426[0.119 0.5 0.953] 0.29Gotchas
Section titled “Gotchas”- Unscaled features. Distances, cosine similarities of profiles and gradient descent all assume comparable scales. Standardize with the training statistics first.
*is not@.X * wmultiplies element-wise and broadcasts;X @ wsums the products.- Shape
(n,)is not(n, 1).X @ wwithwof shape(p,)gives(n,). Mixing(n,)and(n, 1)in arithmetic broadcasts to(n, n), a silent bug. - No intercept column. Without
np.ones(n)in the design matrix, the fit is forced through the origin. - Inverting matrices.
inv(X.T @ X)squares the condition number and amplifies rounding errors. Uselstsqorsolve. lstsqreturns four values. Unpack them or take[0].- The sign of the update.
w - lr * grad, never+. - A wrong gradient trains silently. Check it with central differences at a random point.
hin a numerical derivative. About1e-5. Too small and rounding errors dominate.- “It matches” needs a number. Use
np.allclose(a, b, rtol=0, atol=tol)and print the largest difference. - Mini-batches need shuffling every epoch, and a smaller learning rate than full batches.
- . Name the condition every time. Bayes’ rule converts one into the other and needs the prior.
- Products of probabilities underflow to
0.0. Sum log-probabilities instead. np.log(0)in log loss gives-inf. Clip the probabilities.LogisticRegression()is penalized by default. UseC=np.infto compare with an unpenalized from-scratch model.