Machine learning notes, part 2: linear regression¶
Linear regression is the first model of almost every machine learning course, and it deserves the place. It is small enough to solve on paper, and it already contains the ideas that the rest of the subject keeps returning to: a loss function, two ways of minimising it, overfitting, regularisation, the probabilistic meaning of a loss, and the trade-off between bias and variance. This post goes through all of them in one sitting, with the derivations written out and every number checked in code.
Part 1 set up the vocabulary. This part is the first real model. The material follows chapters 1 and 3 of Bishop's Pattern Recognition and Machine Learning, and so does the running example: fitting a curve to a few noisy points of a sine. I wrote out the derivations that a textbook leaves to the reader, and I computed every figure myself, so that I can stand behind each number. One difference in notation: Bishop writes \(t\) for the target and \(y\) for the prediction. I write \(y\) for the target and \(\hat y\) for the prediction, as most code does. Handwritten digits, the example of part 1, come back when the series reaches classification.
Some background is assumed: derivatives and gradients, matrices and their eigenvalues, and the Gaussian distribution.
The problem¶
In supervised learning we are given \(N\) examples \((\mathbf{x}_n, y_n)\), an input and the answer that belongs to it. When \(y_n\) is one of a few categories the task is classification. When \(y_n\) is a real number it is regression, and that is the case here: predict the price of a flat from its size, age and location, or the yield of a reaction from temperature and pressure.
Every learning method has two phases. In training we use the examples to build a model. In testing we give the model inputs it has never seen and it returns predictions. The only thing that counts in the end is how good the predictions are on those unseen inputs. This sentence is easy to agree with and easy to forget, and half of this post exists because of it.
The figure names the parts.
- The data are the points. Each one is a pair: an input \(x\) and the target \(y\) that was observed with it.
- The training set is the part of the data that the method is allowed to learn from, here 30 of the 40 points, chosen at random.
- The model is the line. Among all possible lines, training picks the one that passes closest to the training points. The vertical distance between a point and the line is the residual of that point, the amount by which the model is wrong there.
- The test set is the rest of the data, 10 points that are put aside before training and play no part in it. They stand in for the future. For each of them the model predicts \(\hat y\) from \(x\) alone, and the prediction is compared with the \(y\) that was held back.
In this example the root-mean-square error is 0.24 on the training points and 0.30 on the test points. The second number is the honest one. It is usually the larger of the two, because the line was chosen to suit the training points and the test points had no say.
Part 1 arrived at one recipe of five steps for designing a learning method: experience, target, representation, evaluation and optimisation. For linear regression the five steps read as follows.
- Experience: the data. \(N\) examples, each an input together with its answer. The input features have to be found, by exploring the data, and their number \(D\) must be known exactly, because it fixes the shape of everything that follows.
- Target: what is to be learned. A function that takes the features and returns a real number. What that number is, a price or a yield, usually comes with the problem.
- Representation: the model. A family of functions from the feature space to the target space, with unknown parameters. Here it is the family of linear functions.
- Evaluation: the loss function. It says how badly a given setting of the parameters fits the training data. Here it is the squared error.
- Optimisation. Find the parameters that make the loss as small as possible. Here there are two ways, an exact formula and gradient descent.
Steps 1 and 2 are done once the data are on the table. The sections below take steps 3, 4 and 5 in turn, and the rest of the post is about what happens when the choices made in them are changed.
Two spaces appear in this recipe, and it helps to keep them apart. The data live in data space, with one axis per feature and one for the target. The model lives in parameter space, also called weight space, with one axis per parameter. A single point in parameter space is a whole function in data space. The loss is a function on parameter space, not on data space, and training is a walk through parameter space.
Line A is the least-squares fit, and its loss, defined in the next sections, is 0.03. Line B is too flat and line C too steep, with losses of 0.34 and 0.26. In data space we see why they are worse: they miss the points. In parameter space we see where to go: downhill on the contours, towards A. The figure on gradient descent further down shows such a walk in both spaces.
The model¶
The simplest model that can use all the features is a weighted sum of them plus a constant:
The weights \(w_1, \dots, w_D\) say how much each feature counts, and the bias \(w_0\) moves the whole function up or down. With one feature this is the line \(\hat y = w x + b\) from school. With two features it is a plane, \(\hat y = w_0 + w_1 x_1 + w_2 x_2\). With \(D\) features it is a hyperplane: a flat surface of \(D\) dimensions inside the data space, which has \(D + 1\) dimensions, one per feature and one for the target.
Almost every figure in this post has a single feature, and the only reason is that it can be drawn on a page. Nothing in the method depends on it. All the formulas below are written for any \(D\), and the code is the same for one feature or for ten thousand: the design matrix simply gets more columns. The plane in the figure was fitted to 40 points generated with the weights \((1, 1.2, 0.8)\), and least squares returns \((0.72, 1.27, 0.91)\). Real problems have tens to millions of features. What is lost there is only our ability to look at the data and at the fit, and that is why the numbers that replace looking, such as the error on a test set, matter so much.
The parameter space grows in the same way. A line has two parameters, a plane three, and a hyperplane \(D + 1\), so the loss is a surface over \(D + 1\) axes. The two-dimensional pictures of parameter space in this post are again the one case that can be drawn.
Carrying the bias separately makes every formula longer, so we absorb it. Give every input an extra feature that is always one, \(x_0 = 1\). Then
with \(\mathbf{w} = (w_0, w_1, \dots, w_D)^\top\) and \(\mathbf{x} = (1, x_1, \dots, x_D)^\top\). Stack the inputs as the rows of a matrix and the targets in a vector:
\(\mathbf{X}\) is called the design matrix. It has \(N\) rows and \(D + 1\) columns, and the predictions for all training inputs at once are \(\hat{\mathbf{y}} = \mathbf{X}\mathbf{w}\). Writing the model this way is called vectorisation. It is shorter on paper, and in code it replaces a loop over examples with one matrix product, which NumPy hands to compiled linear algebra routines that are hundreds of times faster than a Python loop.
The loss¶
Two numbers belong to every training example. The first is \(y_n\), the target: the value that was observed and that comes with the data. The second is \(\hat y_n = \mathbf{w}^\top\mathbf{x}_n\), the prediction: the value that the model computes for the same input with its current weights. The hat always marks something the model computed, and a letter without a hat is data. In the figures, \(y_n\) is the height of a point and \(\hat y_n\) is the height of the line below or above it.
For one example the model is wrong by the residual \(y_n - \hat y_n\), the vertical step from the line to the point. It is positive when the point lies above the line and negative when it lies below. We need one number that summarises all \(N\) residuals. The first idea is the sum of the distances between the predictions and the targets. Whether that is the best choice is worth a look at the candidates.
- The sum of the residuals is useless: a residual of \(+5\) and one of \(-5\) cancel, and a terrible fit can score zero.
- The sum of the absolute residuals fixes that. It is a legitimate loss with its own merits, and it returns further down. But \(|r|\) has a kink at zero, so the loss has no derivative exactly where we want to end up, and there is no formula for its minimum.
- The sum of the squared residuals is smooth everywhere, has a minimum that can be written in closed form, and turns out to be exactly the right choice when the noise in the data is Gaussian, as the probabilistic view shows.
The line in the figure passes through the centre of the points with the wrong slope, and the sum of its residuals is exactly zero. The best line through the same points scores zero too, so this sum cannot tell the two apart. The other two can: the sum of the absolute residuals falls from 3.86 for the flat line to 1.82 for the best one, and the sum of the squares from 3.82 to 0.74. The figure also shows how the two differ from each other. An absolute value counts every unit of error the same. A square counts large errors more than in proportion, so the squared error cares most about the points that are furthest from the line.
So we use the mean squared error, with a conventional factor:
The \(\tfrac12\) cancels the 2 that differentiation produces. The \(\tfrac1N\) makes the loss an average, so that its size, and with it a good learning rate, does not depend on how many examples there are. Neither factor moves the minimum. Books differ on both, and Bishop for instance keeps the \(\tfrac12\) and drops the \(\tfrac1N\). It matters only when a formula contains a regularisation constant, and I will point it out there.
Training is now an optimisation problem. The loss gives one number to every possible weight vector, and the best model is the one with the smallest loss value, so we have to find the minimum of \(J(\mathbf{w})\). But the minimum value itself is not what we take home. We need the weights at which it is reached, because those weights are the model. Writing \(\mathbf{w}^*\) for them:
The two operators answer different questions. \(\min_{\mathbf{w}} J\) is a number: how small the loss can get. \(\arg\min_{\mathbf{w}} J\) is the argument at which it gets that small, a point in parameter space. In the figure of the two spaces, the minimum of the loss is 0.03, and the arg min is the point A, the pair \((w_0, w_1) = (0.76, 1.72)\). The first tells us how well the best line fits. The second is the line.
Two tools: gradients and convexity¶
Derivatives with respect to a vector¶
A function of one variable has a derivative. A function of many variables, such as \(J(\mathbf{w})\), has a gradient: the vector of its partial derivatives,
It points in the direction in which \(J\) grows fastest, and it is zero at a minimum. We could compute it one component at a time, but a handful of identities gives it directly in matrix form. For a constant vector \(\mathbf{a}\) and a constant matrix \(\mathbf{A}\):
| Function of \(\mathbf{w}\) | Gradient |
|---|---|
| \(\mathbf{a}^\top\mathbf{w}\) | \(\mathbf{a}\) |
| \(\mathbf{w}^\top\mathbf{w}\) | \(2\mathbf{w}\) |
| \(\mathbf{w}^\top\mathbf{A}\mathbf{w}\) | \((\mathbf{A} + \mathbf{A}^\top)\mathbf{w}\), which is \(2\mathbf{A}\mathbf{w}\) when \(\mathbf{A}\) is symmetric |
| \(\lVert\mathbf{A}\mathbf{w} - \mathbf{b}\rVert^2\) | \(2\mathbf{A}^\top(\mathbf{A}\mathbf{w} - \mathbf{b})\) |
Each of them can be checked by writing out the sum and differentiating with respect to one \(w_j\). They are the vector versions of \(\tfrac{d}{dw}(aw) = a\) and \(\tfrac{d}{dw}(aw^2) = 2aw\).
One warning about tables of matrix derivatives. There are two conventions. In the numerator layout the derivative of a scalar with respect to a column vector is a row vector, so the first line reads \(\partial(\mathbf{a}^\top\mathbf{w})/\partial\mathbf{w} = \mathbf{a}^\top\). In the denominator layout it is a column vector, \(\mathbf{a}\), and that is the gradient as I use it here. The two differ only by a transpose, but mixing them inside one calculation gives products whose shapes do not match. Pick one, and check the shapes of every line.
This section has only what linear regression needs. The full set of rules, for scalars, vectors and matrices in both layouts, with Jacobians, Hessians and a way to check a derivative numerically, is in a post of its own: derivatives of vectors and matrices.
Convex functions¶
A function is convex if the straight line between any two points on its graph never goes below the graph:
This is the chord test: connect two points of the graph, and if the chord dips below the function anywhere, for any pair of points, the function is not convex. A bowl passes it. Anything with two valleys fails, because the chord from one valley floor to the other passes under the hill between them.
Convexity matters because of what it says about minima. A convex function has no local minima other than the global one. Wherever the gradient is zero, we are done. A non-convex function can have many minima of different depths, and also saddle points, where the gradient is zero without there being a minimum at all.
For a function with second derivatives, convexity is the same as a Hessian matrix that is positive semidefinite everywhere. The Hessian of the squared error is constant:
So the mean squared error of a linear model is convex, whatever the data. It is a bowl in parameter space, and if the columns of \(\mathbf{X}\) are linearly independent it is strictly convex and has exactly one lowest point. This is a property of this loss and this model together. It is not true of losses in general, and not all losses even have a derivative everywhere: the absolute error has a kink, and the number of misclassified examples is a staircase with zero gradient almost everywhere.
Optimisation I: the normal equations¶
Because \(J\) is a smooth bowl, its minimum is where the gradient vanishes. Expand the square,
and apply the identities from the table. \(\mathbf{X}^\top\mathbf{X}\) is symmetric, so
Setting this to zero gives the normal equations,
a system of \(D + 1\) linear equations in \(D + 1\) unknowns. A dimension check is a good habit: \(\mathbf{X}\) is \(N \times (D+1)\), so \(\mathbf{X}^\top\mathbf{X}\) is \((D+1)\times(D+1)\) and \(\mathbf{X}^\top\mathbf{y}\) has \(D + 1\) entries. If \(\mathbf{X}^\top\mathbf{X}\) can be inverted, the solution is
The matrix \((\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{X}^\top\) is the pseudo-inverse of \(\mathbf{X}\). It plays the role of \(\mathbf{X}^{-1}\) for a matrix that is not square: with more examples than parameters there is in general no \(\mathbf{w}\) with \(\mathbf{X}\mathbf{w} = \mathbf{y}\) exactly, and the pseudo-inverse returns the one that comes closest.
What the equations say¶
The name has nothing to do with the normal distribution. Normal means perpendicular here. Rewrite the equations as
Each row of this says that one column of \(\mathbf{X}\) is perpendicular to the vector of residuals. The picture is this. The \(N\) targets are one point \(\mathbf{y}\) in an \(N\)-dimensional space. The predictions \(\mathbf{X}\mathbf{w}\) are combinations of the columns of \(\mathbf{X}\), so whatever \(\mathbf{w}\) we choose, they stay in the subspace that those \(D + 1\) columns span, a thin sheet inside the big space. The closest point of a sheet to a point outside it is the foot of the perpendicular. Least squares is an orthogonal projection of \(\mathbf{y}\) onto the column space of \(\mathbf{X}\), and the residual is what sticks out.
Two useful facts follow at once. The column of ones is one of the columns, so the residuals sum to zero: a least-squares fit with a bias is right on average. And the residuals are uncorrelated with every feature, so no linear use of the features can improve the fit any further.
When the inverse does not exist¶
\(\mathbf{X}^\top\mathbf{X}\) is invertible exactly when the columns of \(\mathbf{X}\) are linearly independent. Its determinant is then non-zero, but nobody computes a determinant to find out: it costs as much as solving the system, and for a matrix that is nearly singular it is numerically meaningless. In practice the inverse fails to exist in two situations.
- Redundant features. One column is a combination of others: a temperature in Celsius and again in Fahrenheit, three percentages that always sum to 100, or a one-hot code for every category together with the bias. The data then cannot tell these features apart, and infinitely many weight vectors give the same predictions.
- Fewer examples than parameters, \(N < D + 1\). There are not enough equations to pin down the unknowns.
The loss is still convex in these cases, but its bowl has a flat valley floor, and every point on the floor is a minimum. The usual choices are to remove the redundant features, to take the solution of smallest norm, which is what a pseudo-inverse computed by singular value decomposition returns, or to add a regularisation term, which makes the matrix invertible in every case. That is one of the reasons for ridge regression below.
A matrix that is almost singular is nearly as bad as a singular one. The condition number of \(\mathbf{X}^\top\mathbf{X}\), the ratio of its largest to its smallest eigenvalue, says how strongly errors in the data are amplified in the weights. Strongly correlated features give a large condition number, and with it weights that are huge, of opposite signs, and different on every new sample of data.
What it costs¶
Building \(\mathbf{X}^\top\mathbf{X}\) takes of the order of \(ND^2\) operations and solving the system another \(D^3\). The matrix needs memory for \(D^2\) numbers. For a hundred features this is nothing. For \(D = 10^5\), which is small for text or image data, \(\mathbf{X}^\top\mathbf{X}\) has \(10^{10}\) entries, 80 GB in double precision, and the solve needs about \(10^{15}\) operations. The closed form is exact, has nothing to tune, and is the right tool up to a few thousand features. Beyond that we need a method that never builds the matrix.
One practical rule: even when the closed form is the right tool, do not compute the inverse. Solving the linear system directly is faster and more accurate, and a least-squares routine based on QR or singular value decomposition never forms \(\mathbf{X}^\top\mathbf{X}\) at all, which matters because the condition number of \(\mathbf{X}^\top\mathbf{X}\) is the square of that of \(\mathbf{X}\). In NumPy this is np.linalg.lstsq(X, y).
Optimisation II: gradient descent¶
Gradient descent finds the minimum by walking. Start anywhere in parameter space, compute the gradient there, take a step against it, and repeat:
The gradient points uphill, so the minus sign takes us downhill. The gradient also shrinks as we approach the minimum, so the steps become smaller by themselves. The number \(\eta > 0\) is the learning rate. It multiplies the gradient and sets the length of the step. One step costs two matrix-vector products, of the order of \(ND\) operations, and needs no memory beyond the data.
An example small enough to do by hand¶
Take one parameter and the loss \(J(\theta) = \theta^2\), with derivative \(2\theta\) and minimum at zero. Start at \(\theta_0 = 3\) with \(\eta = 0.1\). The update is \(\theta \leftarrow \theta - 0.1 \cdot 2\theta = 0.8\,\theta\):
| Step | \(\theta\) | step taken, \(\eta \cdot 2\theta\) |
|---|---|---|
| 1 | 3 | 0.6 |
| 2 | 2.4 | 0.48 |
| 3 | 1.92 | 0.384 |
| 4 | 1.536 | 0.307 |
| 5 | 1.229 | 0.246 |
| 10 | 0.403 | 0.081 |
Every step multiplies \(\theta\) by \(1 - 2\eta\), and everything about the learning rate can be read off this factor. With \(\eta = 0.01\) the factor is 0.98, and the walk needs hundreds of steps. With \(\eta = 0.5\) it is zero, and one step lands on the minimum. With \(\eta = 0.9\) it is \(-0.8\): each step overshoots to the other side of the valley, but lands closer than before. With \(\eta = 1\) it is \(-1\), and \(\theta\) jumps between 3 and \(-3\) for ever. With any larger value the jumps grow and the method diverges.
How large can the learning rate be?¶
For the squared error the same calculation works in any number of dimensions. The gradient is linear in \(\mathbf{w}\) and vanishes at \(\mathbf{w}^*\), so \(\nabla J(\mathbf{w}) = \mathbf{H}(\mathbf{w} - \mathbf{w}^*)\) with the Hessian \(\mathbf{H} = \mathbf{X}^\top\mathbf{X}/N\), and the distance to the minimum obeys
Along each eigenvector of \(\mathbf{H}\), with eigenvalue \(\lambda_i\), the error is multiplied by \(1 - \eta\lambda_i\) at every step. The eigenvalue is the curvature of the bowl in that direction. The descent converges if all these factors lie between \(-1\) and \(1\), that is, if
The steepest direction of the bowl sets the limit. But the flattest direction sets the speed, because its factor \(1 - \eta\lambda_{\min}\) is the one closest to one. The best fixed learning rate is \(\eta = 2/(\lambda_{\min} + \lambda_{\max})\), and with it the error shrinks by \((\kappa - 1)/(\kappa + 1)\) per step, where \(\kappa = \lambda_{\max}/\lambda_{\min}\) is the condition number again. A round bowl, \(\kappa = 1\), is solved in one step. A long narrow valley, with large \(\kappa\), takes for ever.
The figure shows this on 50 points scattered around the line \(y = 1 + 1.5x\) with \(x\) between 0 and 2. The eigenvalues of \(\mathbf{H}\) are 0.137 and 2.251, so \(\kappa = 16.5\) and the learning rate must stay below 0.888.
With \(\eta = 0.5\) the steep direction is done after one or two steps, since its factor is \(1 - 0.5 \cdot 2.251 = -0.13\). The flat direction has the factor \(1 - 0.5 \cdot 0.137 = 0.93\), and the descent needs 175 steps to come within \(10^{-6}\) of the exact weights. The best fixed rate, 0.838, needs 119.
Scale the features¶
The narrow valley in the figure is not a property of the problem. It comes from the units of \(x\). Subtract from each feature its mean and divide by its standard deviation, and for this one-feature example the Hessian becomes the identity matrix: the bowl is round, and gradient descent with \(\eta = 1\) reaches the exact minimum in a single step instead of 175. With several features the bowl does not become perfectly round, because the features are correlated with each other, but standardising them removes the part of the bad conditioning that comes only from units, such as an area in square metres next to a number of rooms. It is the cheapest way to speed up gradient descent, and it should be done by default. The mean and the standard deviation must be computed on the training data and then reused, unchanged, for the test data.
Batch, stochastic and mini-batch¶
The update above uses all \(N\) examples for every step. This is batch gradient descent. When \(N\) is in the millions, one step is expensive, and most of that work is redundant, because the examples resemble each other.
Stochastic gradient descent uses one example per step:
This is the least-mean-squares rule of part 1, there with the sign written the other way round. The gradient of one example is a noisy estimate of the full gradient: right on average, wrong in detail. Each step costs only \(D\) operations, the path jitters instead of gliding, and with a fixed learning rate it never settles but keeps moving around the minimum, so the rate is usually reduced over time. Mini-batch gradient descent is the compromise that everybody uses: average the gradient over a small random batch, 32 or 256 examples, which is less noisy than one example and fits the way hardware does linear algebra.
Local minima and momentum¶
For linear regression the bowl has one lowest point, and gradient descent with a suitable learning rate finds it from any starting point. For almost every other model this guarantee is lost. The loss of a neural network is a function of thousands, millions or billions of parameters, and it is not convex. Gradient descent then stops wherever the gradient vanishes, and which minimum that is depends on where it started. In practice nobody finds the global minimum of such a loss. What is reported is a good local minimum, and much of the competition between optimisation algorithms is about finding better ones, faster.
There are two simple remedies. The first is to start from several random points and keep the best result. The second is momentum. Plain gradient descent has no memory: the step depends only on the slope under its feet. Momentum gives it a velocity \(\mathbf{v}\) that accumulates past gradients and decays by a factor \(\beta\), usually 0.9:
The picture is a ball with mass rolling down the surface. It does two useful things. In a long narrow valley the components of the gradient that flip sign from step to step cancel in the velocity, and the consistent component along the valley adds up, so the crawl along the floor becomes a run. And a ball that arrives at a shallow dip with enough speed rolls through it. The right panel of the convexity figure shows exactly this: from the same start and with the same learning rate, plain descent settles in the local minimum at \(w = 2.07\), where \(J = 1.40\), and descent with momentum ends in the global minimum at \(w = -2.37\), where \(J = 0.06\). This is help, not a guarantee. With a different start or a higher barrier the ball stays where it is, and too much momentum can carry it out of a good minimum as easily as out of a bad one.
The challenges of gradient descent¶
Gradient descent is simple to write and not simple to use well. The difficulties met so far, and two that have not come up yet, in one list:
| Challenge | What it looks like | Usual remedy |
|---|---|---|
| The learning rate | Too small: thousands of steps. Too large: oscillation or divergence. The right value depends on the curvature of the loss, which is not known in advance. | Try values on a logarithmic grid, reduce the rate over time, or use a method that adapts it. |
| Ill-conditioning | A long narrow valley. The steep direction limits the learning rate, and the flat direction then takes for ever. | Standardise the features, add momentum, or use curvature as Newton's method does. |
| Local minima | On a non-convex loss, the descent ends in whichever valley it started above. | Several random starts, momentum, the noise of stochastic gradients. |
| Saddle points and plateaus | The gradient is nearly zero although there is no minimum, and the steps become tiny. In many dimensions these are far more common than local minima. | Momentum and noise, which keep the iterate moving. |
| The cost of a gradient | Every step reads all \(N\) examples. | Mini-batches. |
| Noisy gradients | With mini-batches the path jitters and never quite settles. | A learning rate that decreases, or averaging the iterates. |
| When to stop | The loss keeps falling by ever smaller amounts, and nothing announces the minimum. | Stop when the gradient or the change in the loss is below a tolerance, or when the error on validation data stops improving. |
For linear regression only the first two rows and the fifth matter, because the loss is a convex bowl. For neural networks all seven do. Each of them deserves more than a row in a table, and they have a post of their own: gradient descent and its difficulties.
Both methods in code¶
The two ways of fitting a line take a few lines of NumPy each. This is the data of the figure:
import numpy as np
rng = np.random.default_rng(1)
N = 50
x = rng.uniform(0.0, 2.0, N)
y = 1.0 + 1.5 * x + 0.3 * rng.standard_normal(N)
X = np.column_stack([np.ones(N), x]) # the column of ones carries the bias
# 1. Normal equations, solved without forming an inverse.
w_exact = np.linalg.lstsq(X, y, rcond=None)[0]
# 2. Batch gradient descent on J(w) = ||Xw - y||^2 / (2N).
w = np.zeros(2)
eta = 0.5
for step in range(200):
grad = X.T @ (X @ w - y) / N
w -= eta * grad
print(w_exact.round(3), w.round(3)) # [0.956 1.513] [0.956 1.513]
Both return a bias of 0.956 and a slope of 1.513, close to the 1 and 1.5 that generated the data. Which one to use is a question of size:
| Normal equations | Gradient descent | |
|---|---|---|
| Result | exact, in one go | approximate, improves with every step |
| To tune | nothing | learning rate, number of steps |
| Cost | about \(ND^2 + D^3\) | about \(ND\) per step |
| Memory | \(D^2\) for \(\mathbf{X}^\top\mathbf{X}\) | only the data, or one batch of it |
| Feature scaling | not needed for the solution | needed for speed |
| Other models and losses | only where a closed form exists | anything with a gradient |
The last row is the real reason gradient descent matters. The normal equations are special to the squared error of a linear model. Gradient descent is the same loop for logistic regression and for a transformer.
Beyond straight lines: basis functions¶
A straight line is a poor model of most things. The way out does not need a new method. Replace the raw input by fixed non-linear functions of it, the basis functions \(\phi_j\), and take a weighted sum of those:
The idea is to map the data to another space, the feature space with coordinates \(\phi_j\), in which the relation between input and output is linear, and to do linear regression there. As a function of \(\mathbf{x}\) the model can now bend as much as the basis functions allow. As a function of \(\mathbf{w}\) it is exactly as linear as before, and that is the only linearity the mathematics ever used. "Linear regression" means linear in the parameters.
Nothing in the previous sections changes except the design matrix, whose entries become \(\Phi_{nj} = \phi_j(\mathbf{x}_n)\):
The loss is still convex, the normal equations still hold, and gradient descent still works. Some common choices, for a single input \(x\):
- Polynomials, \(\phi_j(x) = x^j\). Global: changing one weight changes the function everywhere.
- Gaussians, \(\phi_j(x) = \exp\bigl(-(x - \mu_j)^2 / 2s^2\bigr)\), bumps of width \(s\) centred at \(\mu_j\). Local: each one affects the function only near its centre.
- Sigmoids, \(\phi_j(x) = \sigma\bigl((x - \mu_j)/s\bigr)\) with \(\sigma(a) = 1/(1 + e^{-a})\), smooth steps.
- Sines and cosines, \(\sin(jx)\) and \(\cos(jx)\), for periodic signals. This is a Fourier series.
- Exponentials and logarithms, when the physics of the problem suggests them.
There is no rule that selects the basis. Any function can serve, and the choice is where knowledge about the problem enters the model. This freedom has a price in higher dimensions. A polynomial of order 3 in one variable has 4 terms. In 10 variables it has 286, and in 100 variables 176,851, because of all the products between variables. Fixed basis functions do not scale to many inputs. Two later models can be read as answers to that problem: a support vector machine places its basis functions on the training points, and a neural network learns its basis functions from the data.
How complex should the model be?¶
Basis functions raise a question that the straight line did not: how many of them? The standard example is a polynomial of order \(M\),
fitted to \(N = 10\) points. The points are \(y = \sin(2\pi x)\) at ten evenly spaced values of \(x\) between 0 and 1, with Gaussian noise of standard deviation 0.3 added. The order \(M\) fixes the search space. \(M = 0\) contains only horizontal lines. \(M = 1\) adds all straight lines, \(M = 2\) all parabolas, and so on. Each space contains the previous ones, since a parabola with \(w_2 = 0\) is a line.
Underfitting. A constant and a straight line cannot follow a sine, however the weights are chosen. The best function is simply not in the search space. A polynomial of order \(M\) has at most \(M - 1\) turning points, so a curve with one maximum and one minimum needs at least order 3. A model that is too simple for the data has a large error on the training data and on new data alike.
A good fit. The cubic follows the sine closely, although it knows nothing about sines.
Overfitting. The polynomial of order 9 has ten weights for ten points, so it can pass through every point exactly, and it does: its training error is zero. Between the points it swings far away from the sine, and near the ends it leaves the plot. It has fitted the noise. The model looks perfect on the data it was trained on and is the worst of all on new data.
| Order \(M\) | Training error | Test error | Largest weight, in absolute value |
|---|---|---|---|
| 0 | 0.630 | 0.720 | 0.05 |
| 1 | 0.482 | 0.520 | 1.28 |
| 3 | 0.192 | 0.304 | 27.9 |
| 9 | 0.000 | 0.851 | 684,065 |
The training error can only go down as \(M\) grows, because each search space contains the previous one. It is therefore no guide to the choice of \(M\). The test error falls, stays near the noise level from \(M = 3\) to \(M = 8\), and jumps at \(M = 9\). This is the sentence from the beginning in numbers: the aim is to predict new data well, and the training data are only there to help.
The last column shows how the order-9 polynomial manages to hit every point. Its weights are enormous and alternate in sign, so that huge terms cancel almost exactly at the ten training inputs and nowhere else. Large weights are the fingerprint of overfitting, and the next section turns this observation into a method.
Overfitting is not a matter of the model alone. It is the model measured against the amount of data. The same order-9 polynomial fitted to 15 points has a test error of 0.317, and fitted to 100 points one of 0.294, at the noise level. More data is the best cure for overfitting, when it can be had. "Enough" data is not only a count, though. The points must also cover the region where the model will be used: a hundred points with \(x\) below 0.3 say nothing about the rest of the curve.
Choosing the order without cheating¶
If the test data decide the order, they are no longer unseen, and the error we report is too optimistic. The honest procedure splits the data in three. The training set fits the weights. The validation set compares models of different complexity and picks one. The test set is used once, at the very end, to report how good the chosen model is.
With little data, holding out a validation set is wasteful, and cross-validation is used instead. Cut the training data into \(K\) parts, typically 5 or 10. Train on \(K - 1\) of them, measure the error on the part left out, repeat so that each part is left out once, and average the \(K\) errors. Every point is used for training and for validation, at the cost of \(K\) training runs per candidate model.
Regularisation¶
Choosing \(M\) controls complexity in coarse steps: a basis function is in the model or out of it. Regularisation is a finer control. Keep the flexible model, and change the loss so that large weights cost something:
The first term asks for a good fit to the data. The second, the penalty \(R\), asks for small weights. "Changing the loss function" and "adding a penalty" are one step, described two ways: the new loss is the old loss plus the penalty. The two terms pull in different directions and live on different scales, and the regularisation parameter \(\lambda \ge 0\) sets the exchange rate between them. It cannot be negative: a negative \(\lambda\) would reward large weights, and with a strong enough reward the loss would have no minimum at all. Otherwise there is no natural range for it. It does not have to lie between 0 and 1, and depending on the scales of the targets and of the features a good value can be \(10^{-5}\) or \(10^{3}\).
Ridge regression¶
The first choice of penalty is the squared length of the weight vector. The result is called \(L_2\) regularisation, ridge regression, or weight decay:
The penalty (the term \(\tfrac{\lambda}{2}\lVert\mathbf{w}\rVert^2\)) is quadratic, so everything that worked for the squared error still works. The gradient is
and setting it to zero gives a closed form again:
The \(N\) next to \(\lambda\) comes from the \(\tfrac1N\) in my definition of the loss. Books that define the loss as a sum write \(\lambda\mathbf{I}\), and their \(\lambda\) is \(N\) times mine. Four remarks.
It always has a solution. \(\boldsymbol{\Phi}^\top\boldsymbol{\Phi}\) has eigenvalues that are positive or zero, and adding \(N\lambda\mathbf{I}\) raises every one of them by \(N\lambda\). For any \(\lambda > 0\) the matrix is invertible, and its condition number is smaller than before. Redundant features and fewer examples than parameters are no longer a problem. This numerical repair, and not overfitting, was the original motivation for ridge regression.
It is weight decay. One step of gradient descent on the ridge loss is
Before the usual step, every weight is shrunk by the same factor a little below one. A weight survives only if the data keep pushing it back.
It shrinks most where the data say least. Write the singular value decomposition \(\boldsymbol{\Phi} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top\), with singular values \(\sigma_i\). The fitted values of ridge regression are
Without the fraction this is the orthogonal projection of ordinary least squares. With it, each direction is scaled down by a factor between zero and one. Directions in which the data vary a lot, with large \(\sigma_i\), are hardly touched. Directions in which the data barely vary, with small \(\sigma_i\), are the ones along which the weights were poorly determined and noise was amplified, and they are suppressed. The sum of these factors is called the effective number of parameters. It falls smoothly from the number of basis functions at \(\lambda = 0\) towards zero as \(\lambda\) grows, which is the sense in which \(\lambda\) is a continuous version of \(M\).
Two details of practice. The bias \(w_0\) is normally left out of the penalty. Otherwise adding a constant to all targets would change the fit by more than that constant. And the penalty treats all weights alike, which is only fair if the features are on the same scale, so the features are standardised first.
In code, the penalty can be written as extra data: \(M + 1\) imaginary examples that say "this weight should be zero", each with a strength of \(\sqrt{N\lambda}\). The same least-squares routine then solves the problem without forming \(\boldsymbol{\Phi}^\top\boldsymbol{\Phi}\):
def fit_ridge(Phi, y, lam):
"""Minimise ||Phi w - y||^2 / (2N) + lam / 2 * ||w[1:]||^2."""
N, P = Phi.shape
D = np.eye(P)
D[0, 0] = 0.0 # do not penalise the bias
A = np.vstack([Phi, np.sqrt(N * lam) * D])
b = np.concatenate([y, np.zeros(P)])
return np.linalg.lstsq(A, b, rcond=None)[0]
Applied to the order-9 polynomial and the ten points from before:
| \(\ln\lambda\) | \(\lVert\mathbf{w}\rVert\) without the bias | Training error | Test error |
|---|---|---|---|
| \(-\infty\), no penalty | 1,110,000 | 0.000 | 0.851 |
| \(-18\) | 168 | 0.118 | 0.324 |
| \(-10\) | 20.9 | 0.150 | 0.302 |
| \(-2\) | 0.52 | 0.492 | 0.569 |
A penalty of \(\lambda = e^{-18} \approx 10^{-8}\), far too small to see in the loss, already brings the weights down from a million to a hundred and the test error from 0.85 to 0.32. At \(\ln\lambda = -10\) the order-9 polynomial predicts as well as the cubic. At \(\ln\lambda = -2\) it has been flattened into something close to a straight line and underfits. The parameter moves the model continuously from overfitting, at \(\lambda = 0\), to underfitting, at large \(\lambda\), and the right value lies in between.
Parameters and hyperparameters¶
The weights \(\mathbf{w}\) are parameters: the optimisation finds them from the training data. \(\lambda\) is a different kind of quantity. It cannot be found by minimising the training loss together with the weights, because the answer would always be \(\lambda = 0\): with no penalty the training error is lowest. Quantities that are fixed before training and steer it from outside are called hyperparameters. The order \(M\), the width of a Gaussian basis function, the learning rate and the batch size are others.
Hyperparameters are chosen on data that the training did not use, by validation or cross-validation as described above. The simplest search is a grid. For \(\lambda\) the grid should be logarithmic, \(10^{-6}, 10^{-5}, \dots, 10^{2}\), because what matters is its order of magnitude. With several hyperparameters a grid becomes expensive quickly, and random search or Bayesian optimisation is used. Regularisation has not removed the problem of choosing the complexity of the model. It has turned an integer into a continuous number, which is easier to tune and can sit between two orders.
Lasso¶
The second choice of penalty is the sum of the absolute values of the weights, the \(L_1\) norm. The method is called the lasso, for least absolute shrinkage and selection operator:
The change looks small, and it has one large consequence. The lasso sets some weights to exactly zero. Its solutions are sparse, and a zero weight means that the feature has been removed from the model. The lasso fits the model and selects the features in one step.
Why does the absolute value produce exact zeros when the square does not? The cleanest way to see it is the case of orthonormal features, \(\boldsymbol{\Phi}^\top\boldsymbol{\Phi}/N = \mathbf{I}\), where the problem falls apart into one equation per weight. Write \(w^{\text{LS}}_j\) for the least-squares weight. Then
Ridge divides every weight by the same number. A weight becomes smaller, but never zero. The lasso subtracts the same amount \(\lambda\) from the size of every weight, and any weight smaller than \(\lambda\) is gone. This operation is called soft thresholding. The right panel of the figure further down draws both rules for \(\lambda = 1\): a least-squares weight of 3 becomes 1.5 under ridge and 2 under the lasso, and a weight of 0.5 becomes 0.25 under ridge and exactly zero under the lasso. The reason is in the slopes of the two penalties. The pull of the ridge penalty towards zero is its derivative, \(\lambda w\), which fades away as the weight gets small, so the data always win in the end. The pull of the lasso penalty is \(\lambda\operatorname{sign}(w)\), which has the same strength however small the weight is, so a weight that the data support only weakly is pulled all the way to zero and held there.
The geometric interpretation. The same argument can be drawn, and the drawing is found in every textbook. Minimising the penalised loss is the same as minimising the squared error subject to a budget on the weights: \(\lVert\mathbf{w}\rVert_1 \le t\) for the lasso and \(\lVert\mathbf{w}\rVert_2 \le t\) for ridge. A larger \(\lambda\) corresponds to a smaller budget \(t\). The budget marks out a part of weight space that the solution may not leave, the constraint region, and the two penalties differ in the form of that region. For ridge it is a disc, round everywhere. For the lasso it is a diamond, with its corners on the axes.
The contours of the squared error are ellipses around the least-squares solution, which lies outside the region. The solution under the budget is the point of the region on the lowest contour, the place where an ellipse growing outwards from the least-squares solution first touches the region. A disc has no special points, so the ellipse touches it somewhere on the rim, where both weights are different from zero. A diamond reaches furthest at its corners, so the ellipse usually meets a corner first, and at a corner one of the weights is exactly zero. In more dimensions the diamond has many more corners and edges, all of them places where some weights vanish. This is the whole difference in one picture: the lasso can set coefficients to zero, while the superficially similar ridge regression cannot.
The next figures show it on data built for the purpose: 60 examples with 12 standardised features, of which only the first three influence the target, with weights 3, \(-2\) and 1.5, plus noise of standard deviation 1. The data are simulated, so the truth is known. First the data themselves, before any fit.
The number \(r\) in these figures is the correlation coefficient of two quantities, here of one feature \(x\) and the target \(y\):
It measures how closely the points follow a straight line, and it always lies between \(-1\) and \(1\). At \(+1\) the points lie exactly on a rising line and at \(-1\) on a falling one. At 0 there is no linear trend, and the cloud is shapeless. The sign gives the direction of the trend and the size its strength. It is tied to the fit of a line in two ways. The slope of the least-squares line through the points is \(r\) times the spread of \(y\) divided by the spread of \(x\). And \(r^2\) is the \(R^2\) of that line, the share of the variance of the target that this one feature explains: 0.56 for the first feature and 0.21 for each of the other two that matter.
Two things can be seen before any model is fitted. The three features that matter show up clearly, with correlations of 0.75, \(-0.46\) and 0.46 with the target. And the nine that do not matter are not at zero. Their true effect is exactly nothing, and still their correlations with the target reach 0.16 in size, and the correlations among the features themselves run from \(-0.32\) to \(+0.27\). With only 60 examples, chance alone produces numbers of that size. This is the raw material of overfitting: a model with a weight for every feature will make use of those chance correlations. The next figure shows what each penalty does about it.
Ordinary least squares gives all twelve features a non-zero weight. The nine irrelevant ones get values between \(-0.25\) and \(0.17\), which is noise that the model has taken for signal. The lasso with \(\lambda = 0.3\) keeps exactly the three features that matter, with weights 2.58, \(-1.50\) and 1.18. Above \(\lambda = 2.92\) every weight is zero. Ridge keeps all twelve at every \(\lambda\).
The regularisation path. The left and middle panels have a name. A plot of every weight as a curve over \(\lambda\) is called a regularisation path, and it is the standard picture of a penalised model. One value of \(\lambda\) gives one model. The path shows all of them at once.
A path is read from right to left. At the far right the penalty is so strong that every weight is zero. As \(\lambda\) gets smaller the weights leave zero, and under the lasso they do so one after another, each at a definite value of \(\lambda\). Three things can be read off.
- Which features matter, and in what order. The first weights to leave zero belong to the features that the model can least do without. Here the three relevant features enter first, the strongest at \(\lambda = 2.92\), and the nine irrelevant ones only below about 0.2.
- How well a weight is determined. A curve that runs flat over a wide range of \(\lambda\) belongs to a weight that the data pin down. A curve that swings, or changes sign, belongs to a feature that is entangled with others.
- Where the chosen model sits. Choosing \(\lambda\) by cross-validation picks one vertical line through the picture. The path shows what the neighbouring choices would have given, and how many features each of them keeps.
For ridge the path differs in one respect: the curves fade towards zero together and never reach it. One caution when reading a path in a book or a paper: check the axis first. Some authors plot against \(-\log\lambda\) or against the size of the weight vector, and then the picture is mirrored, with the empty model on the left.
The example also shows the price. The three surviving weights are too small, 2.58 where least squares gives 2.88, because the lasso shrinks what it keeps by about \(\lambda\). A common repair is to use the lasso only to select the features and then to fit ordinary least squares to the selected ones.
How it is solved. \(|w|\) has no derivative at zero, so there is no closed form, and plain gradient descent does not produce exact zeros. The loss is still convex, though, and three algorithms are in common use. Coordinate descent optimises one weight at a time by soft thresholding, with the others held fixed, and cycles until nothing changes. Proximal gradient descent, or ISTA, alternates a gradient step on the squared error with a soft-thresholding step. And least angle regression, LARS, computes the whole path of solutions for all values of \(\lambda\) at once, at about the cost of one least-squares fit. It can do this because the lasso path is piecewise linear in \(\lambda\): straight pieces joined at kinks. The kinks can be seen in the middle panel, where the pieces look bent only because the axis is logarithmic. scikit-learn has all of them:
from sklearn.linear_model import Lasso, LassoCV, LassoLars, LinearRegression, Ridge
lam = 0.3
ols = LinearRegression().fit(X, y)
ridge = Ridge(alpha=N * lam).fit(X, y) # scikit-learn's alpha is N * lambda here
lasso = Lasso(alpha=lam).fit(X, y) # and plain lambda here: coordinate descent
lars = LassoLars(alpha=lam).fit(X, y) # the same problem, solved by LARS
best = LassoCV(cv=5).fit(X, y) # lambda chosen by 5-fold cross-validation
On the data of the figure, ols and ridge have 12 non-zero weights and lasso and lars have 3, the same three to six decimal places. LassoCV chooses \(\lambda = 0.19\) and also keeps exactly those three. The comments are worth a second look: scikit-learn defines the two losses with different factors, and a value of alpha copied from one model to the other means something else.
Ridge or lasso? The \(L_1\) norm is often called one of the best regularisers, and the preference behind that is simple: if something can be zero, let it be zero and not a value close to zero. A sparse model is cheaper to store and to evaluate, and it can be read: it says which features it uses. But the preference holds in one situation and not in another. The lasso does better when the truth is sparse, with a few features that matter and many that do not, as in the example. Ridge does better when many features each contribute a little, and it is the more stable of the two when features are strongly correlated, where the lasso picks one of a correlated group more or less arbitrarily and drops the rest. The elastic net, the subject of the next section, uses both penalties together and is a good default when it is unclear which case applies. The \(L_2\) penalty is also much easier to analyse, since it has derivatives everywhere, which is why it comes first in every course.
Elastic net¶
The lasso has two weaknesses. Faced with a group of strongly correlated features, it keeps one or two of them and drops the rest, and which ones it keeps can change with a small change in the data. And when there are more features than examples, it can select at most as many features as there are examples. The elastic net removes both by using the two penalties at once:
There are now two hyperparameters. \(\lambda\) sets the strength of the penalty as a whole, as before. The mixing parameter \(\alpha\), between 0 and 1, sets how the penalty is divided: \(\alpha = 1\) is the lasso, \(\alpha = 0\) is ridge, and anything in between is a blend.
Each part contributes what it is good at. The \(L_1\) part produces exact zeros, so the model still selects features. The \(L_2\) part makes the loss strictly convex, so the solution is unique even when two features are identical, and it ties correlated features together: features that carry the same information receive similar weights. This is called the grouping effect.
For orthonormal features the solution can again be written down, and it is the two earlier rules applied one after the other:
The numerator is the soft threshold of the lasso, with \(\lambda\alpha\) in the place of \(\lambda\). The denominator is the shrinkage of ridge, with \(\lambda(1 - \alpha)\). With \(\lambda = 1\) and \(\alpha = 0.5\), a least-squares weight of 3 becomes \((3 - 0.5)/1.5 = 1.67\), and a weight of 0.4 becomes exactly zero.
The constraint region shows the same blend. It lies between the diamond and the disc. It keeps the corners of the diamond, which is why weights can still be exactly zero, and its edges are curved, which is why the solution is unique.
The right panel is an experiment made for the purpose. There are 60 examples and 12 features. The first three features are near-copies of one hidden quantity, with correlations of 0.97 among them, and the next three are near-copies of a second one. The target depends on the two hidden quantities. The last six features are pure noise. For each method \(\lambda\) was chosen by five-fold cross-validation, and the elastic net used \(\alpha = 0.5\). The table gives averages over 200 data sets drawn in this way.
| Lasso | Elastic net | Ridge | |
|---|---|---|---|
| Group features kept, out of 6 | 5.00 | 5.88 | 6 |
| Data sets in which all six are kept | 29% | 92% | 100% |
| Spread of the weights inside a group | 0.58 | 0.21 | 0.20 |
| Noise features kept, out of 6 | 2.40 | 3.58 | 6 |
| Root-mean-square error on test data | 1.136 | 1.124 | 1.137 |
The lasso divides a group unevenly. On the data set of the figure it gives the three features of the first group the weights 0.37, 1.02 and 1.21, although all three carry the same information, and it nearly drops the middle feature of the second group. Across the 200 data sets it keeps all six group features in fewer than a third of them, and the weights inside a group differ widely.
The elastic net keeps a group together. Its weights for the first group are 0.70, 0.91 and 0.94, and it keeps all six group features in 92% of the data sets. In this respect it behaves like ridge.
It still selects, but less sharply than the lasso. Ridge keeps every noise feature. The elastic net removes some of them, 2.4 out of 6 on average, where the lasso removes 3.6. That is the price of the \(L_2\) part: the model is less sparse.
The predictions hardly differ. The three test errors are within 1% of each other. On these data the choice between the methods is a choice about the weights, about which features appear in the model and how stable that list is. It is not a choice about accuracy.
The regularisation path of the elastic net. With two hyperparameters there is no longer a single path. There is one path in \(\lambda\) for each value of \(\alpha\), and together they form a surface: every weight is a function of the pair \((\lambda, \alpha)\). In practice \(\alpha\) is fixed at a few values, and the usual picture is drawn once for each.
Read from right to left, as before, the three panels differ in how a group enters the model.
- Under the lasso the members of a group enter one at a time. One feature of group one enters at \(\lambda = 2.55\) and carries the group alone. Its weight climbs to 1.81, where least squares gives it 0.72. The second member enters only at \(\lambda = 0.75\), and the third at 0.22, by which point the first noise feature is about to come in, at 0.21. Each entry bends the curves of the others, and that is what the sharp kinks are.
- Under the elastic net a group enters together. With \(\alpha = 0.5\) the first member enters at \(\lambda = 5.10\) and all three are in the model by 4.37. From there the three curves run side by side over a wide range of \(\lambda\). The noise features stay out until \(\lambda\) falls below 0.48. This is the grouping effect, seen in the path.
- A smaller \(\alpha\) stretches the picture to the right. Every weight is zero once \(\lambda\alpha\) exceeds the largest \(|\boldsymbol{\phi}_j^\top\mathbf{y}|/N\), so the dotted line moves from 2.55 to 5.10 and to 25.5. The curves also become smoother. As \(\alpha\) goes to zero the corner where a weight meets zero moves off to infinity, and what remains is the ridge path, in which no weight is ever zero.
- At the left edge the three panels agree. With almost no penalty every method returns the least-squares weights, and those are uneven: 0.68, 0.72 and 1.31 for the three members of group one. The grouping happens in the middle of the path, where the penalty is strong enough to matter.
The shape of the pieces differs too. The lasso path is made of straight pieces in \(\lambda\), which look bent here only because the axis is logarithmic. Between two kinks the elastic net path is curved, because of the denominator \(1 + \lambda(1 - \alpha)\) in the formula above.
Choosing the two hyperparameters by cross-validation picks one point on the surface: one of the panels, and one vertical line in it. A handful of values of \(\alpha\) is usually enough, since the error changes little with \(\alpha\), as the table showed.
In scikit-learn the model is ElasticNet, and the names of its arguments need care: its alpha is the \(\lambda\) of this post, and its l1_ratio is the mixing parameter \(\alpha\).
from sklearn.linear_model import ElasticNet, ElasticNetCV
model = ElasticNet(alpha=lam, l1_ratio=0.5).fit(X, y) # one lambda, an even blend
best = ElasticNetCV(l1_ratio=[0.1, 0.5, 0.9, 1.0], cv=5).fit(X, y) # both chosen by cross-validation
The elastic net is the method to reach for when features come in correlated groups and a selection is still wanted, and when there are more features than examples. Genes that act together, neighbouring pixels and overlapping survey questions are typical cases.
Regularisation is not special to linear regression. The same penalties are added to the loss of logistic regression and, as weight decay, to the loss of deep networks. And one caution belongs here: regularisation does not solve overfitting. It reduces its effects, and it gives us a dial to turn.
Other ways to measure the error¶
The squared error is one choice among several. Two roles should be kept apart: the loss, which the optimisation minimises, and the metric, which we report at the end. They can differ. It is common to train with the squared error and to report something easier to interpret.
Mean absolute error, \(\text{MAE} = \frac1N\sum_n |y_n - \hat y_n|\). It is in the units of the target and treats every unit of error alike, where the squared error makes one error of 10 count as much as a hundred errors of 1. This makes it robust to outliers. The two also aim at different things: the constant that minimises the squared error of a set of numbers is their mean, and the constant that minimises the absolute error is their median.
Mean relative error, \(\text{MRE} = \frac1N\sum_n |y_n - \hat y_n| / |y_n|\), called MAPE when given in per cent. It has no units, so it compares problems on different scales: an error of 10 is bad for a target of 20 and negligible for one of 20,000. It is undefined when a target is zero and explodes when one is close to zero.
Coefficient of determination,
where \(\bar y\) is the mean of the targets. It compares the model with the most trivial one, which predicts \(\bar y\) for every input. \(R^2 = 1\) is a perfect fit, and \(R^2 = 0\) is no better than the mean. On the training data of a least-squares fit with a bias it lies between 0 and 1 and is the fraction of the variance of the targets that the model explains. On test data it can be negative, which means the model is worse than predicting the mean. And on training data it can only go up when a feature is added, even a random one, so like the training error it cannot be used to choose between models of different size.
The middle panel shows what makes the relative error different. The second and the third point miss the line by about the same amount, but the target of the second is half as large, so its relative error is 29% against 13%. In the right panel the line leaves only 8% of the squared distances that the mean leaves, and \(R^2\) is 0.92.
The probabilistic view¶
Up to here the squared error was a choice justified by convenience. It can also be derived from an assumption about the data, and the derivation is worth following line by line, because the same three steps, a model of the noise, a likelihood and its maximum, produce the loss functions of most other models too.
Maximum likelihood¶
Assume that each target is a deterministic function of the input plus noise, and that the noise is Gaussian with mean zero and variance \(\sigma^2\):
Given the input, the target is then itself Gaussian, centred on the prediction:
Assume also that the examples are independent. The probability of the whole training set is then the product over the examples. Seen as a function of the parameters, with the data fixed, it is called the likelihood:
The principle of maximum likelihood chooses the parameters under which the data we actually observed are most probable. A product of many small numbers is awkward, so we take the logarithm, which turns the product into a sum and does not move the maximum:
Only the second term depends on \(\mathbf{w}\), and it is the sum of squared errors with a negative constant in front. Maximising the likelihood over \(\mathbf{w}\) is therefore the same as minimising the squared error:
Least squares is maximum likelihood under Gaussian noise. The loss was never arbitrary. It encodes three assumptions: the noise is added to the target, it is Gaussian, and it is independent from example to example with the same variance everywhere.
The noise level has a maximum-likelihood estimate too. Differentiating \(\ln L\) with respect to \(\sigma^2\) and setting the result to zero gives
the mean squared residual. So the probabilistic model returns more than the least-squares fit did. For a new input it gives a whole distribution, \(\mathcal{N}\bigl(\mathbf{w}_{\text{ML}}^\top\boldsymbol{\phi}(\mathbf{x}),\, \sigma^2_{\text{ML}}\bigr)\): a prediction and an error bar. The error bar is too narrow, though. The fit has used the same data to place the curve, so the residuals are smaller than the true noise, and dividing by \(N\) minus the number of weights instead of \(N\) corrects this on average. For the order-9 polynomial through ten points, \(\sigma^2_{\text{ML}}\) is zero: maximum likelihood is certain that there is no noise at all. Overfitting has a probabilistic face as well.
Other noise, other losses¶
The derivation tells us what to do when the assumptions are wrong: change the noise model, and the loss changes with it.
- Laplace noise, \(p(\varepsilon) \propto \exp(-|\varepsilon|/b)\), has heavier tails than a Gaussian. Repeating the derivation with it is a good exercise. Its log-likelihood contains \(\sum_n |y_n - \hat y_n|\), so maximum likelihood is the minimisation of the absolute error. This is why the MAE is the robust choice: it is the right loss for data with occasional large errors.
- A variance that differs between examples, \(\sigma_n^2\), gives weighted least squares, where each squared residual is divided by its variance, and precise measurements count for more.
-
Counts. What if the noise is Poisson instead of Gaussian? The natural form of that question is a target that is a count: the number of spikes of a neuron in a time window, or of customers in an hour. A count is never negative, and its variance grows with its mean, so "a line plus the same noise everywhere" is the wrong model. The standard one takes \(y\) as Poisson with a mean that depends on the input, \(\mu(\mathbf{x}) = \exp(\mathbf{w}^\top\mathbf{x})\), where the exponential keeps the mean positive. The negative log-likelihood is then
\[ -\ln L(\mathbf{w}) = \sum_{n=1}^{N}\bigl(\mu(\mathbf{x}_n) - y_n\ln\mu(\mathbf{x}_n)\bigr) + \text{const}. \]This is Poisson regression. It is no longer a squared error and has no closed-form minimum, but it is convex, and gradient descent or Newton's method finds the minimum. The recipe has not changed: a model, a loss, an optimiser. Only the loss is different, because the assumption about the data is different.
Maximum a posteriori: where the penalty comes from¶
Maximum likelihood asks which parameters make the data most probable. It does not ask whether those parameters are plausible, and for the order-9 polynomial they were not: weights of several hundred thousand, for a curve that stays between \(-1\) and 1. Bayes' theorem lets us say so in advance. Before seeing data we describe what we believe about the weights by a prior distribution \(p(\mathbf{w})\). The data enter through the likelihood \(p(\mathcal{D} \mid \mathbf{w})\). Together they give the posterior, what we believe after seeing the data:
The maximum a posteriori estimate, MAP, is the weight vector with the highest posterior probability. Take as the prior a Gaussian around zero, independent for each weight, with variance \(\tau^2\): we expect small weights and have no idea of their sign. The negative logarithm of the posterior is then
Multiply by \(\sigma^2/N\), which does not move the minimum, and this is the ridge loss, with
Ridge regression is MAP estimation with a Gaussian prior on the weights. The penalty that began as a heuristic, keep the weights small, is a statement of prior belief, and the formula for \(\lambda\) says what the regularisation parameter is: the variance of the noise divided by the variance of the prior, per data point. Noisy data or a tight prior call for strong regularisation. And as \(N\) grows, \(\lambda\) falls: with enough data the likelihood outweighs the prior, which is the Bayesian version of "more data cures overfitting".
The lasso fits the same scheme. A Laplace prior, \(p(w_j) \propto \exp(-|w_j|/b)\), has a sharp peak at zero, and its negative logarithm is \(|w_j|/b\). MAP estimation with it gives the lasso, with \(\lambda = \sigma^2/(Nb)\).
| Estimate | Maximises | Equivalent loss |
|---|---|---|
| Maximum likelihood, Gaussian noise | \(p(\mathcal{D} \mid \mathbf{w})\) | squared error |
| Maximum likelihood, Laplace noise | \(p(\mathcal{D} \mid \mathbf{w})\) | absolute error |
| MAP, Gaussian noise, Gaussian prior | \(p(\mathcal{D} \mid \mathbf{w})\,p(\mathbf{w})\) | squared error + \(L_2\) penalty: ridge |
| MAP, Gaussian noise, Laplace prior | \(p(\mathcal{D} \mid \mathbf{w})\,p(\mathbf{w})\) | squared error + \(L_1\) penalty: lasso |
Bias and variance¶
The polynomial example showed that a model can be too simple or too flexible. The bias-variance decomposition says exactly what goes wrong in each case, and why one dial cannot fix both.
The decomposition¶
Suppose the data come from \(y = h(\mathbf{x}) + \varepsilon\), with an unknown true function \(h\) and noise of mean zero and variance \(\sigma^2\). A training set \(\mathcal{D}\) of \(N\) examples is one random draw from this source, and the model fitted to it, \(\hat y(\mathbf{x}; \mathcal{D})\), is random too: another training set would have given another fit. The question is how large the squared error is at an input \(\mathbf{x}\), on average over training sets and over the noise in the new target.
Write \(\bar y(\mathbf{x}) = \mathbb{E}_{\mathcal{D}}\bigl[\hat y(\mathbf{x}; \mathcal{D})\bigr]\) for the average fit, the prediction averaged over all the training sets we might have drawn. First split off the noise. The new target is \(h + \varepsilon\), the noise in it is independent of the training set, and its mean is zero, so
Then add and subtract the average fit inside the remaining square:
Average over training sets. In the last term, \(h - \bar y\) does not depend on \(\mathcal{D}\), and the average of \(\bar y - \hat y\) is zero by the definition of \(\bar y\), so the term vanishes. What remains is
The three terms are three different ways of being wrong.
- Bias is the error of the average fit. It says how far the method is from the truth even with unlimited repetitions. A model that is too rigid has a high bias: no training set can make a straight line into a sine. High bias is underfitting.
- Variance is how much the fit changes from one training set to the next. A model that is too flexible follows the noise of whichever data set it was given, so each fit is different. High variance is overfitting.
- Noise is in the data. No model can remove it, and it is the floor under the test error.
Making the model more flexible lowers the bias and raises the variance. Making it more rigid does the opposite. The best model is the one where the sum is smallest, and this is the trade-off.
An experiment¶
The decomposition is an average over training sets, and in practice we have only one. In a simulation we can have as many as we like. I drew 100 training sets, each of 25 points with \(x\) uniform between 0 and 1 and \(y = \sin(2\pi x)\) plus noise of standard deviation 0.3. Each set was fitted with the same flexible model: 24 Gaussian basis functions and a bias, 25 weights for 25 points, with a ridge penalty. That gives 100 fits for every value of \(\lambda\).
| \(\ln\lambda\) | Bias² | Variance | Bias² + variance + noise | Measured test error | Training error |
|---|---|---|---|---|---|
| 1 | 0.272 | 0.026 | 0.388 | 0.392 | 0.337 |
| \(-3\) | 0.004 | 0.022 | 0.116 | 0.116 | |
| \(-4\) | 0.002 | 0.027 | 0.119 | 0.119 | 0.062 |
| \(-9\) | 0.001 | 0.091 | 0.183 | 0.181 | 0.049 |
All columns are mean squared errors, and the noise contributes \(0.3^2 = 0.09\) to every row.
With the strong penalty, top row of the figure, the 100 fits are nearly the same and all of them are wrong in the same way: low variance, high bias. With the weak penalty, bottom row, each fit follows the accidents of its own data set, and no two agree: the bias is nearly zero and the variance has more than tripled. The sum is smallest in between, at \(\ln\lambda = -3\), where the test error is 0.116 against a floor of 0.09. The last two columns of the table confirm two things. The decomposition is exact: the sum of the three terms agrees with the test error measured on new points. And the training error keeps falling while the test error rises, as in the polynomial example.
The average fit does not overfit¶
The bottom row of the figure contains the most interesting observation of the experiment. Each of the 100 fits with the weak penalty overfits. Their average, in the middle column, is almost exactly the sine. The individual errors point in different directions, because each one comes from the noise of a different data set, and they cancel in the average.
This is the idea behind ensemble methods. If one flexible model has low bias and high variance, average many of them. The bias stays as it was, and the variance of the average is much smaller than that of a single model. In practice there is only one training set, so the 100 data sets are imitated by resampling the one we have with replacement, which is called the bootstrap. Fitting one model to each resampled set and averaging them is bagging, and bagging applied to decision trees is the random forest.
The limit of the idea is also visible in the figure. Averaging removes variance and nothing else. The average of the 100 fits with the strong penalty, top row, is as wrong as each of them.
What comes next: keeping all the weights¶
Maximum likelihood and MAP each return one weight vector, the single best one, and throw away the information about how well it was determined. The Bayesian treatment of linear regression keeps the whole posterior distribution over the weights. With a Gaussian prior and Gaussian noise the posterior is again a Gaussian, with a mean and a covariance that can be written down:
The mean \(\mathbf{m}_N\) is the ridge solution from above. What is new is the covariance \(\mathbf{S}_N\), which says how uncertain each weight still is. A prediction is then an average over all weight vectors that the posterior considers plausible, weighted by their probability. It comes with an error bar that grows away from the data, which the maximum-likelihood error bar could not do.
This average over models is close in spirit to the average over data sets in the experiment, and it is the reason behind a claim that is often made: Bayesian linear regression does not have the overfitting problem. I read it this way. Overfitting comes from committing to the one weight vector that fits the training data best. A method that never commits to one, and averages over all of them, cannot fit the noise in that way. It still depends on its assumptions. The prior and the noise model must be reasonable, and a bad prior gives bad predictions with honest-looking error bars. Working this out is the subject of the next part of these notes.
Summary¶
| Step of the recipe | Choice in this post | What it brings |
|---|---|---|
| Model | \(\hat y = \mathbf{w}^\top\boldsymbol{\phi}(\mathbf{x})\), linear in the weights | a convex loss, whatever the basis functions |
| Loss | mean squared error | maximum likelihood under Gaussian noise |
| Optimisation, exact | normal equations \(\boldsymbol{\Phi}^\top\boldsymbol{\Phi}\mathbf{w} = \boldsymbol{\Phi}^\top\mathbf{y}\) | the minimum in one step, for up to a few thousand weights |
| Optimisation, iterative | gradient descent, \(\eta < 2/\lambda_{\max}\) | works at any size and for any differentiable loss |
| Complexity | number of basis functions, or \(\lambda\) | too little underfits, too much overfits |
| Ridge, \(L_2\) | \(+\,\tfrac{\lambda}{2}\lVert\mathbf{w}\rVert^2\) | small weights, always solvable. MAP with a Gaussian prior |
| Lasso, \(L_1\) | \(+\,\lambda\lVert\mathbf{w}\rVert_1\) | sparse weights, feature selection. MAP with a Laplace prior |
| Elastic net | \(+\,\lambda\bigl(\alpha\lVert\mathbf{w}\rVert_1 + \tfrac{1-\alpha}{2}\lVert\mathbf{w}\rVert^2\bigr)\) | sparse weights that keep correlated features together |
| Model selection | validation set or cross-validation | an honest choice of \(M\) and \(\lambda\) |
| Error of a method | bias² + variance + noise | underfitting is bias, overfitting is variance |
If I had to keep three sentences, they would be these. The training error measures the optimisation and the test error measures the model, and only the second one matters. Every loss function is an assumption about the noise, and every penalty is an assumption about the weights. And a model is neither too simple nor too complex by itself, but only for a given amount of data.
Code¶
All figures and all numbers in this post come from one script, scripts/ml_linear_regression.py in this site's repository. It needs NumPy, Matplotlib and scikit-learn, and it prints every number quoted here while it draws:
pip install -r scripts/requirements.txt
python scripts/ml_linear_regression.py
python scripts/ml_linear_regression.py --only bias-variance
Three exercises that are worth the time: fit the ten points with nine Gaussian basis functions instead of a polynomial and compare the size of the weights. Replace batch gradient descent by the stochastic version and watch the path in parameter space. And repeat the bias-variance experiment with 100 points per data set instead of 25, to see which of the three terms moves.
Further reading¶
Online:
- On momentum: the momentum chapter of the Predictive Science Lab's course on scientific machine learning.
Books:
- C. M. Bishop, Pattern Recognition and Machine Learning (Springer, 2006). Section 1.1 is the polynomial example, sections 3.1 and 3.2 are least squares, regularisation and the bias-variance decomposition, and section 3.3 is Bayesian linear regression. These notes follow it closely.
- T. Hastie, R. Tibshirani and J. Friedman, The Elements of Statistical Learning (2nd edition, Springer, 2009), chapter 3. The best treatment of ridge, the lasso and least angle regression, and free to download.
- K. B. Petersen and M. S. Pedersen, The Matrix Cookbook. Every matrix derivative one is likely to need, in one place.
Original papers:
- A. E. Hoerl and R. W. Kennard, "Ridge regression: biased estimation for nonorthogonal problems", Technometrics 12, 55–67 (1970). doi:10.1080/00401706.1970.10488634
- R. Tibshirani, "Regression shrinkage and selection via the lasso", Journal of the Royal Statistical Society B 58, 267–288 (1996). doi:10.1111/j.2517-6161.1996.tb02080.x
- H. Zou and T. Hastie, "Regularization and variable selection via the elastic net", Journal of the Royal Statistical Society B 67, 301–320 (2005). doi:10.1111/j.1467-9868.2005.00503.x
- B. Efron, T. Hastie, I. Johnstone and R. Tibshirani, "Least angle regression", Annals of Statistics 32, 407–499 (2004). doi:10.1214/009053604000000067
- S. Geman, E. Bienenstock and R. Doursat, "Neural networks and the bias/variance dilemma", Neural Computation 4, 1–58 (1992). doi:10.1162/neco.1992.4.1.1
If you find a mistake in a derivation, or know a better way to explain one of these steps, write to me by email or on LinkedIn.