The Math Toolkit
Vectors, matrices, probability and derivatives you will use everywhere.
Machine learning is written in four languages: vectors and matrices for data, derivatives for learning, probability for uncertainty, and logarithms for turning products into sums. This lesson gives you each in working form, with the one derivation or picture that makes it usable, and derives the gradient that trains a linear model.
What you’ll learn
- Write a dataset as a design matrix and translate sums over examples into matrix products such as , and .
- Interpret the eigenvalues and eigenvectors of a symmetric matrix, and read a covariance matrix's principal directions from them.
- Derive the gradient of the squared loss of a linear model with the chain rule, and the normal equations from it.
- Compute expectations, variances and posteriors with Bayes' rule, and explain why learning works with log-probabilities.
Data as vectors, datasets as matrices
An example with features is a vector , and examples stacked as rows form the design matrix , with the targets in . Almost every formula in this course is a sum over examples, and almost every sum over examples is a matrix product. Seeing one in the other is the first skill of the toolkit.
| Sum over examples | Matrix form | Shape | Meaning |
|---|---|---|---|
| for every | the predictions of a linear model | ||
| how strongly each feature moves with the target | |||
| sums of products of every pair of features | |||
| for all pairs | the Gram matrix: similarities between examples | ||
| the sample covariance matrix ( has centered columns) |
The dot product is also geometry: , where is the angle between the vectors. So the cosine similarity measures alignment regardless of length, which is how embeddings are compared, and the Cauchy–Schwarz inequality follows at once. Norms measure size: the Euclidean , the behind the lasso, and . Distances expand into dot products: .
holds examples of features. What are the shape and the meaning of ?
- : the sum of each feature
- : the dot product of every pair of examples
- It is undefined, because is not square
- : entry is , the product of features and summed over all examples
Show the answer
D. : entry is , the product of features and summed over all examples
is and is , so the product is , with entry . It equals , a sum of outer products, and for centered data it is times the covariance matrix. Its size depends on the number of features, not of examples, which keeps the normal equations cheap for tall datasets.
Matrices as maps, and their eigenvectors
A matrix also acts: is a combination of 's columns with weights , and is a linear map that can stretch, rotate and project. An eigenvector is a direction the map only stretches, , by a factor , its eigenvalue. For the symmetric matrices that fill machine learning (covariances, Gram matrices, Hessians), the spectral theorem guarantees real eigenvalues and an orthonormal basis of eigenvectors, so : in eigenvector coordinates, simply rescales each axis. The Convergence lesson on linear algebra proves it.
For a covariance matrix , the quadratic form is the variance of the data projected onto a unit vector . It is never negative, so is positive semidefinite, and it is largest along the top eigenvector, where it equals the top eigenvalue . That direction is the first principal component; PCA keeps the top few.
Two-dimensional data have covariance matrix . What percentage of the total variance lies along the first principal component?
Show the answer
75 %
The eigenvalues are 3 and 1, and the total variance is the trace, . The first principal direction, , carries ; the second carries 25%. Each feature alone carries only half the total: the correlation between the two features is what concentrates the variance along the diagonal.
Derivatives, gradients and the chain rule
For a function , the gradient collects the partial derivatives, . It gives the best linear approximation of near : . Among unit directions , the rate of change is largest, by Cauchy–Schwarz, at , where it equals . The gradient points uphill, and gradient descent steps the other way, , with a learning rate .
Models are compositions, and the chain rule differentiates compositions. In one variable, . With vectors: if and , then , where the Jacobian is the matrix of partial derivatives . Backpropagation is this rule applied layer by layer, from the loss backward. Second derivatives form the Hessian , and the second-order Taylor expansion describes curvature: a twice-differentiable is convex exactly when its Hessian is positive semidefinite everywhere.
The gradient of the squared loss
Now the payoff. A linear model predicts (a column of ones in absorbs the intercept), and least squares minimizes the mean squared error over the training set:
Differentiate one term with the chain rule. The inside is the residual , and :
Collect the partial derivatives into a vector: each example pulls on along its own input, in proportion to its residual.
Average over the examples and use the table of the first step, with :
The Hessian is positive semidefinite, so is convex and every point where the gradient vanishes is a global minimum. Setting the gradient to zero gives the normal equations, with a unique solution when has full column rank:
Think first One feature, no intercept, two examples: and . What is the derivative of at , and which minimizes ?
, so : the loss falls as grows. In one dimension the normal equation reads , so , exactly where .
import numpy as np
rng = np.random.default_rng(0)
n, d = 200, 3
X = rng.normal(size=(n, d))
w_true = np.array([1.0, -2.0, 0.5])
y = X @ w_true + 0.1 * rng.normal(size=n)
w = np.zeros(d)
eta = 0.1
for t in range(500):
grad = (2 / n) * X.T @ (X @ w - y) # gradient of the mean squared error
w -= eta * grad
w_exact = np.linalg.solve(X.T @ X, X.T @ y) # the normal equations
print(np.abs(w - w_exact).max()) # agrees to machine precisionGradient descent and the normal equations find the same minimizer. Forming and solving costs about operations; for many features or streaming data the gradient route scales better, and numerically careful solvers factor (QR or SVD) instead of forming , as the Convergence lesson explains.
Random variables, expectation and variance
A random variable assigns a number to each outcome of an experiment, with a distribution given by a probability mass function or a density. Its expectation (an integral for densities) is its long-run average, and expectation is linear: for any random variables, dependent or not. The variance measures spread, and the covariance measures how two variables move together. Independent variables have zero covariance, but zero covariance does not imply independence.
Let be independent with mean and variance , and let . Linearity gives its mean:
Variances of independent variables add, because every cross term with vanishes, and constants come out squared:
So the spread of the average, its standard error, shrinks like : four times the data halves it. The law of large numbers and the central limit theorem sharpen this, and the Convergence lesson Probability & Concentration Inequalities turns it into finite-sample guarantees.
A classifier errs on 10% of a test set of 400 independent examples. Each example's error indicator is a Bernoulli variable with variance . What is the standard error of the estimated error rate, in percentage points?
Show the answer
1.5 points
, or 1.5 percentage points. Two classifiers whose error rates differ by 1 point on this test set are not reliably different, and quadrupling the test set to 1,600 examples only halves the standard error, to 0.75 points.
The Gaussian has density ; about 68%, 95% and 99.7% of its mass lies within 1, 2 and 3 standard deviations of the mean. In dimensions, the multivariate Gaussian with a positive definite covariance has density
Conditional probability, Bayes' rule and logarithms
The probability of given is . Writing both ways, , and dividing gives Bayes' rule, which turns the probability of evidence under a hypothesis into the probability of the hypothesis given the evidence:
Why logarithms. Learning multiplies many probabilities: the likelihood of independent examples is . A thousand factors of 0.01 multiply to , far below the smallest positive double-precision number (about ), so computers work with instead. Because the logarithm is increasing, maximizing the log-likelihood picks the same parameters as maximizing the likelihood, and sums are what averages and gradients handle best. Exponentials go the other way: softmax turns scores into probabilities , computed stably with the log-sum-exp identity:
Key takeaways
- A dataset is a design matrix , and sums over examples are matrix products: predictions , , the feature-by-feature and the example-by-example Gram matrix .
- Dot products measure alignment, . Symmetric matrices have real eigenvalues and orthonormal eigenvectors; a covariance matrix's top eigenvector is the direction of greatest variance, and its eigenvalue is that variance.
- The gradient points uphill with slope , and the chain rule composes derivatives. For least squares, , and setting it to zero gives the normal equations .
- Expectation is linear; the mean of independent variables has standard deviation ; Bayes' rule weighs evidence by base rates.
- Learning works with log-probabilities: logs turn products into sums, prevent underflow and leave maximizers unchanged, and the log-sum-exp identity computes softmax stably.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
At the current weights the gradient of the loss is . You move a short distance . Which direction lowers the loss fastest, and by about how much?
- Along , lowering the loss by about
- Along , lowering the loss by about
- Along , lowering the loss by about
- Along , the coordinate with the largest partial derivative
Show the answer
B. Along , lowering the loss by about
The steepest descent direction is , and to first order the loss changes by .
Setting the gradient of to zero gives which equation?
Show the answer
C.
gives : the residual must be orthogonal to every column of . With more examples than features, usually has no solution at all.
You average independent measurements, each with standard deviation . How does the standard deviation of the average scale?
- , unchanged
Show the answer
B.
, so the standard deviation is . Halving an error bar takes four times the data, a square-root law that recurs in every generalization bound of this course.
A test with sensitivity 90% and false-positive rate 9% comes back positive for a disease with 1% prevalence. Why is the probability of disease only about 9%?
- Because the test is only 90% accurate
- Because a single test can never raise a probability above 10%
- Because the disease and the test result are independent
- Because healthy people are 99 times as numerous, so their false alarms (about 89 per 1,000 people) outnumber the true positives (about 9)
Show the answer
D. Because healthy people are 99 times as numerous, so their false alarms (about 89 per 1,000 people) outnumber the true positives (about 9)
. The prior multiplies the likelihood: a small error rate applied to a huge healthy population produces many false positives.
For a covariance matrix , what does its largest eigenvalue equal?
- The variance of the data projected onto the top eigenvector, the largest projected variance over all unit directions
- The largest variance of any single feature
- The determinant of
- The number of features
Show the answer
A. The variance of the data projected onto the top eigenvector, the largest projected variance over all unit directions
For a unit vector , is the variance along , and its maximum over unit vectors is , attained at the top eigenvector. It is at least every diagonal entry (a single feature's variance) and larger when features are correlated: for , .
Go deeper
- Linear Algebra for ML: Eigenvectors & the SVD · Spectral theorems, low-rank approximation and why the SVD is everywhere.
- Probability & Concentration Inequalities · From the law of large numbers to Hoeffding and Bernstein.
- Information Theory for ML · Entropy, cross-entropy and KL divergence as the language of learning.
Further reading
- M. P. Deisenroth, A. A. Faisal & C. S. Ong, Mathematics for Machine Learning (Cambridge University Press, 2020).
- I. Goodfellow, Y. Bengio & A. Courville, Deep Learning (MIT Press, 2016), chapters 2–4.
- L. Wasserman, All of Statistics (Springer, 2004), chapters 1–5.