Skip to content

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.

I want to… Use… Math
turn one row into a feature vector df.loc[i, cols].to_numpy(dtype=float) x∈Rp\mathbf{x} \in \mathbb{R}^p
build the data matrix df[cols].to_numpy(dtype=float) X∈Rn×pX \in \mathbb{R}^{n \times p}
standardize every column (X - X.mean(axis=0)) / X.std(axis=0) z=(x−μ)/σz = (x - \mu)/\sigma
take a weighted sum w @ x w⋅x=∑iwixi\mathbf{w} \cdot \mathbf{x} = \sum_i w_i x_i
predict for every row X @ w + b y^=Xw+b\hat{\mathbf{y}} = X\mathbf{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) ∥x∥2\lVert \mathbf{x} \rVert_2
get the L1 norm np.linalg.norm(x, ord=1) ∥x∥1\lVert \mathbf{x} \rVert_1
measure the distance from one row to all rows np.linalg.norm(X - q, axis=1) ∥xi−q∥2\lVert \mathbf{x}_i - \mathbf{q} \rVert_2
compare directions u @ v / (norm(u) * norm(v)) cos⁡θ\cos\theta
make a unit vector v / np.linalg.norm(v) v/∥v∥\mathbf{v} / \lVert \mathbf{v} \rVert
transpose X.T X⊤X^\top
solve a square system np.linalg.solve(A, b) Ax=bA\mathbf{x} = \mathbf{b}
fit least squares np.linalg.lstsq(A, y)[0] min⁡w∥Aw−y∥2\min_\mathbf{w} \lVert A\mathbf{w} - \mathbf{y} \rVert^2
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) 2nA⊤(Aw−y)\frac{2}{n}A^\top(A\mathbf{w} - \mathbf{y})
take one gradient descent step w = w - lr * grad w←w−η∇L\mathbf{w} \leftarrow \mathbf{w} - \eta\nabla L
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) max⁡i∣ai−bi∣≤10−6\max_i \lvert a_i - b_i \rvert \le 10^{-6}
compute an expected value values @ probs E[T]=∑kk P(T=k)\mathbb{E}[T] = \sum_k k\,P(T=k)
compute a conditional probability a[b].mean() (boolean arrays) P(A∣B)P(A \mid B)
turn a score into a probability 1 / (1 + np.exp(-z)) σ(z)\sigma(z)
compute log loss -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p)) binary cross-entropy
Math Read as NumPy
xix_i element ii (math counts from 1) x[i - 1]
xijx_{ij} row ii, column jj X[i - 1, j - 1]
∑i=1nai\sum_{i=1}^{n} a_i add a1a_1 to ana_n a.sum()
1n∑iai\frac{1}{n}\sum_i a_i the mean a.mean()
∏iai\prod_i a_i multiply all np.prod(a) (underflows; prefer a sum of logs)
y^\hat{y} prediction y_pred
w1:\mathbf{w}_{1:} all weights but the first w[1:]
∂L∂wj\frac{\partial L}{\partial w_j} slope of LL in direction wjw_j grad[j]
∇L\nabla L the gradient vector grad
η\eta (eta), λ\lambda (lambda) learning rate, penalty strength lr, lam
eze^z, log⁡z\log z exponential, natural log np.exp(z), np.log(z)
import numpy as np
np.set_printoptions(precision=3, suppress=True)
x = np.array([2420.0, 4, 3.5]) # sqft, bedrooms, bathrooms of one house
w = np.array([0.2, 5, 15]) # weights, thousand USD per unit
print(w @ x, np.sum(w * x)) # dot product two ways
d = np.array([-810.0, -2, -1.5]) # difference between two houses
norms = [np.linalg.norm(d, ord=o) for o in (2, 1, np.inf)] # L2, L1, L-infinity
print(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: 1
Output
556.5 556.5
[810.004 813.5 810. ]
1.0
Norm Formula NumPy ML use
L2 ∑ixi2\sqrt{\sum_i x_i^2} norm(x) Euclidean distance, KNN, k-means, gradient size
squared L2 ∑ixi2\sum_i x_i^2 x @ x MSE, Ridge penalty λ∥w∥22\lambda\lVert\mathbf{w}\rVert_2^2
L1 ∑i∣xi∣\sum_i \lvert x_i \rvert norm(x, ord=1) Manhattan distance, MAE, Lasso penalty λ∥w∥1\lambda\lVert\mathbf{w}\rVert_1
L-infinity max⁡i∣xi∣\max_i \lvert x_i \rvert norm(x, ord=np.inf) worst-case difference, tolerance checks
Similarity Range Ignores length? Use
dot product u⋅v\mathbf{u}\cdot\mathbf{v} any no scores, linear models
cosine u⋅v∥u∥∥v∥\frac{\mathbf{u}\cdot\mathbf{v}}{\lVert\mathbf{u}\rVert\lVert\mathbf{v}\rVert} −1 to 1 (0 to 1 for counts) yes text, embeddings, profiles
Euclidean distance 0 and up no nearest neighbors, clustering
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. AB≠BAAB \ne BA in general. (AB)⊤=B⊤A⊤(AB)^\top = B^\top A^\top. AI=AAI = A.

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 squares
print(w_ls, rank)
print(np.allclose(w_ls, np.linalg.solve(A.T @ A, A.T @ y))) # normal equations
Output
[ 79.99 249. 1299. ]
[ 2.994 2.01 -1.017] 3
True
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
Rule Formula Example
power ddwwk=kwk−1\frac{d}{dw} w^k = k w^{k-1} ddww2=2w\frac{d}{dw} w^2 = 2w
constant factor ddwc f(w)=c f′(w)\frac{d}{dw} c\,f(w) = c\,f'(w) ddw3w=3\frac{d}{dw} 3w = 3
sum (f+g)′=f′+g′(f + g)' = f' + g' a mean of losses has the mean of the slopes
chain dLdw=dLdu⋅dudw\frac{dL}{dw} = \frac{dL}{du}\cdot\frac{du}{dw} L=(wx−y)2⇒2(wx−y) xL = (wx - y)^2 \Rightarrow 2(wx - y)\,x
exponential ddzez=ez\frac{d}{dz} e^z = e^z
log ddzlog⁡z=1/z\frac{d}{dz} \log z = 1/z
sigmoid σ′(z)=σ(z)(1−σ(z))\sigma'(z) = \sigma(z)(1 - \sigma(z)) largest (0.25) at z=0z = 0
Loss Formula Gradient
MSE 1n∥Aw−y∥22\frac{1}{n}\lVert A\mathbf{w} - \mathbf{y}\rVert_2^2 2nA⊤(Aw−y)\frac{2}{n}A^\top(A\mathbf{w} - \mathbf{y})
MSE + Ridge +λ∥w1:∥22+\lambda\lVert\mathbf{w}_{1:}\rVert_2^2 + 2λDw+\,2\lambda D\mathbf{w}
log loss −1n∑i[yilog⁡pi+(1−yi)log⁡(1−pi)]-\frac{1}{n}\sum_i [y_i\log p_i + (1-y_i)\log(1-p_i)], pi=σ(zi)p_i = \sigma(z_i) 1nA⊤(σ(Aw)−y)\frac{1}{n}A^\top(\sigma(A\mathbf{w}) - \mathbf{y})

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)
Output
True
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))
Output
67 True

Mini-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))
Output
[ 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
Idea Formula NumPy
expected value E[T]=∑kk P(T=k)\mathbb{E}[T] = \sum_k k\,P(T=k) values @ probs or t.mean()
variance E[(T−E[T])2]\mathbb{E}[(T - \mathbb{E}[T])^2] ((values - m) ** 2) @ probs or t.var()
conditional probability P(A∣B)=P(A and B)/P(B)P(A \mid B) = P(A \text{ and } B) / P(B) a[b].mean()
independence P(A∣B)=P(A)P(A \mid B) = P(A) np.isclose(a[b].mean(), a.mean())
Bayes’ rule P(A∣B)=P(B∣A)P(A)P(B)P(A \mid B) = \frac{P(B \mid A)P(A)}{P(B)} see below
evidence P(B)=P(B∣A)P(A)+P(B∣¬A)P(¬A)P(B) = P(B \mid A)P(A) + P(B \mid \neg A)P(\neg A)
log-likelihood (0/1 data) ∑i[yilog⁡p+(1−yi)log⁡(1−p)]\sum_i [y_i\log p + (1-y_i)\log(1-p)] maximized at y.mean()
sigmoid σ(z)=1/(1+e−z)\sigma(z) = 1/(1 + e^{-z}) 1 / (1 + np.exp(-z))
log-odds z=log⁡p1−pz = \log\frac{p}{1-p} np.log(p / (1 - p))
prior, p_e_given_a, p_e_given_not_a = 0.193, 0.174, 0.056 # churn, few logins
evidence = 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))
Output
0.426
[0.119 0.5 0.953] 0.29
  • Unscaled features. Distances, cosine similarities of profiles and gradient descent all assume comparable scales. Standardize with the training statistics first.
  • * is not @. X * w multiplies element-wise and broadcasts; X @ w sums the products.
  • Shape (n,) is not (n, 1). X @ w with w of 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. Use lstsq or solve.
  • lstsq returns 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.
  • h in a numerical derivative. About 1e-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.
  • P(A∣B)≠P(B∣A)P(A \mid B) \ne P(B \mid A). 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. Use C=np.inf to compare with an unpenalized from-scratch model.