1Learning from data
What it means for a model to learn, why least squares is the default, where it comes from in probability, and what changes when you pick a different loss.
The question
You measured a rate constant at six temperatures and want the activation energy. You computed the adsorption energy of a molecule on twenty surfaces and want to predict it for a twenty-first. In both cases you have pairs and want a rule that turns a new into a good guess of . That is supervised learning, and almost everything in this course is a version of it: the rule gets more flexible (a line, a neural network, an interatomic potential), but the recipe stays the same.
The recipe has three ingredients:
- a model , a family of functions indexed by parameters ;
- a loss that says how bad a prediction is when the truth is ;
- an optimiser that searches for the parameters with the smallest average loss on the data.
Minimising the average loss over a data set is called empirical risk minimisation:
The word empirical matters. What we really want is a small error on data we have not seen, the expected loss over the whole population. We can only measure it on the sample we have, which is why the lesson on generalisation exists.
The simplest model: a straight line
Take and the squared loss . The objective is the sum of squared residuals
is a smooth bowl in , so the minimum is where both partial derivatives vanish:
The first equation says the residuals sum to zero, so the line passes through the centroid . Substituting into the second gives the familiar result
Fit a line by hand, then let least squares do it
Loading the interactive figure…
Try three things in the lab. First, fit the line yourself with the sliders and notice how hard it is to beat least squares; no other line has a smaller mean squared error, by construction. Second, press Add an outlier and watch the least-squares line swing towards it. Third, switch to least absolute deviation with the outlier still there. The squared loss punishes a residual of 4 sixteen times more than a residual of 1, so a single bad point can dominate; the absolute loss punishes it only four times more.
The matrix form, which every later model reuses
Stack the inputs into a design matrix whose rows are feature vectors, here , and the targets into . Then and
Setting the gradient to zero gives the normal equations
Geometrically, is the orthogonal projection of onto the column space of : the residual vector is perpendicular to every feature column. Numerically, never form explicitly; squaring squares its condition number. Libraries solve the problem with a QR or singular-value decomposition instead (numpy.linalg.lstsq uses the SVD).
Where least squares comes from: maximum likelihood
Why squares and not absolute values or fourth powers? Suppose each measurement is the true line plus independent Gaussian noise of width :
The probability density of the whole data set, viewed as a function of the parameters, is the likelihood
Taking the negative logarithm,
and the only part that depends on and is the sum of squares. Least squares is maximum likelihood under Gaussian noise. Every other loss corresponds to a different noise model: the absolute loss is maximum likelihood for Laplace (double-exponential) noise, whose heavier tails make outliers less surprising, which is why that fit ignored the outlier.
The same view tells you what to do when the error bars differ from point to point. If point has standard deviation , the likelihood gives weighted least squares, : precise points count more. Fitting instead of silently changes the weights, because a constant relative error in is a constant absolute error in . That is usually what you want for rate constants, and it is worth knowing you chose it.
How good is the fit?
Three numbers are worth reporting.
- The root-mean-square error, , in the units of . Compare it with the measurement uncertainty: a fit far better than your error bars is suspicious.
- The coefficient of determination, , the fraction of the variance of the model explains. says nothing about whether the model is right: a straight line through curved data can still give . Always look at the residuals; they should look like noise, with no trend.
- Uncertainties on the parameters. Under the Gaussian model the covariance of the estimate is with for parameters. An activation energy without an error bar is not a result.
In practice
The calculation in NumPy, here for an Arrhenius plot (run it locally, or in the Python lesson):
import numpy as np
T = np.array([300., 310., 320., 330., 340., 350.]) # K
k = np.array([1.2e-3, 2.4e-3, 4.6e-3, 8.5e-3, 1.5e-2, 2.6e-2]) # 1/s
R = 8.314462618 # J/(mol K)
X = np.column_stack([np.ones_like(T), 1.0 / T]) # features (1, 1/T)
y = np.log(k)
theta, res, rank, sv = np.linalg.lstsq(X, y, rcond=None)
lnA, slope = theta
N, p = X.shape
s2 = res[0] / (N - p) # residual variance
cov = s2 * np.linalg.inv(X.T @ X) # acceptable for a tiny 2×2 problem
Ea = -slope * R / 1000 # kJ/mol
dEa = np.sqrt(cov[1, 1]) * R / 1000
print(f"Ea = {Ea:.1f} ± {dEa:.1f} kJ/mol, A = {np.exp(lnA):.2e} 1/s")
This prints Ea = 53.7 ± 0.1 kJ/mol, A = 2.65e+06 1/s. For nonlinear models, where no normal equations exist, scipy.optimize.curve_fit does the same job iteratively; the next lesson explains how such iterative optimisers work.
Check yourself
- You fit against with ordinary least squares. Which assumption about the measurement errors in are you implicitly making?A constant relative error becomes a constant absolute error in , because . Ordinary least squares on weights all points equally, which matches that assumption.
- Which of these models is a linear regression problem?Linear regression means linear in the parameters. is a weighted sum of fixed features . The other two have parameters inside a nonlinear function.
- One data point is a gross outlier. Which fit is least affected by it?The squared loss grows quadratically with the residual, so one large residual dominates the sum. The absolute loss grows linearly; it corresponds to maximum likelihood under heavier-tailed Laplace noise.
- A straight-line fit gives . What does that tell you?measures explained variance, not correctness. Curved data can give a high for a straight line; a systematic pattern in the residuals reveals it.
References and further reading
- C. M. Bishop, Pattern Recognition and Machine Learning, Springer (2006), §1.1–1.2 and chapter 3 (linear models for regression).
- T. Hastie, R. Tibshirani and J. Friedman, The Elements of Statistical Learning, 2nd ed., Springer (2009), chapter 3.
- K. P. Murphy, Probabilistic Machine Learning: An Introduction, MIT Press (2022), chapters 4 (statistics) and 11 (linear regression).
- W. H. Press, S. A. Teukolsky, W. T. Vetterling and B. P. Flannery, Numerical Recipes, 3rd ed., Cambridge University Press (2007), chapter 15 (modelling of data), including why the SVD is preferred to the normal equations.
- P. J. Huber, “Robust estimation of a location parameter,” Annals of Mathematical Statistics 35, 73–101 (1964), the origin of robust losses.