The exact answer: normal equations
Last updated
For linear regression, you don’t have to walk down the bowl: the bottom is where the gradient is zero, and that can be solved for directly. This lesson derives the normal equations, solves them in one line of NumPy, checks the answer against gradient descent and scikit-learn’s LinearRegression, and shows the one way they can fail. It also says why, for nearly every other model, gradient descent is still the way.
By the end of this lesson you can
- Derive the normal equations by setting the gradient to zero
- Solve for the weights with np.linalg.lstsq and with LinearRegression, and match gradient descent
- Explain the answer as a projection, and why two identical columns break it
Set the gradient to zero
At the bottom of a bowl the ground is flat: the gradient is zero in every direction. For linear regression that's a condition you can solve.
First, a tidy trick: put a column of ones in front of . Its weight multiplies 1 for every example, so it plays the part of , and the model becomes just , with as the first entry of . Lesson 3.4's gradient is then . Set it to zero:
These are the normal equations: one equation per weight. is a small square matrix, , however many examples there are. If it can be inverted (lesson 1.4), multiply both sides by its inverse:
The star marks the best weights. No learning rate, no steps, no loop.
Solving it
This time, use the penguins' measurements as they are, in millimetres, unstandardised:
The first cell types the formula in directly. The second uses np.linalg.lstsq ("least squares"), which gets the same answer without forming an inverse, more accurately and safely; use it in practice. (The *_ throws away the other things it returns.)
The answer: g, and each millimetre of bill length adds 4.16 g, of bill depth 20.05 g, of flipper length 50.27 g. The root-mean-square error is 391.1 g, exactly what gradient descent reached in lesson 3.4. It's the same model: standardising changes the units of the weights, not the predictions. (The negative is the mass of a penguin with no bill and no flippers, far outside the data, so it means nothing on its own.)
The picture: a projection
There's a picture of what the normal equations say. Think of the labels as a single point in a space with one axis per example. With three examples, that's ordinary 3-D space.
Every prediction is some mixture of 's columns, so all possible predictions form a flat plane through the origin (with more features, a higher-dimensional flat). The best prediction is the point on the plane closest to : its projection, where the residual meets the plane at a right angle. "At a right angle to every column" is : the normal equations again. ("Normal" is an old word for "at right angles".)
ŷ = (1, 2, 3). The residual y − ŷ has length 1.414, so the loss, its length squared over 3, is 0.667. Its dot products with 1 and x are 0 and −1; both are 0 only at the best line.
LinearRegression, and why gradient descent still matters
scikit-learn's LinearRegression solves the same least-squares problem, adding the intercept for you:
The same weights, with in intercept_. So why did lesson 3.3 bother with gradient descent?
- Most models have no formula. Set the gradient of logistic regression (lesson 3.9) or of a neural network to zero and you can't solve it. Walking downhill is the only way.
- Big problems. has entries and solving it takes about steps. With a million features that's , while each gradient step costs about .
- Data that doesn't fit in memory. Gradient descent can learn from a few examples at a time (lesson 3.6). The normal equations need everything at once.
For linear regression on a few thousand features, use the exact answer. For almost everything else, gradient descent.
Wrong way: two identical columns
Suppose flipper length gets into the table twice, by a copy-paste mistake or because the same thing was measured in two units:
is , but its rank (lesson 1.4) is only 2: the last two rows are identical, so it squashes some direction flat and can't be inverted. The formula gives nan. (On your own computer you may instead get LinAlgError: Singular matrix, or enormous weights, depending on rounding.)
The reason is that the question no longer has one answer. Flipper length is worth 49.68 g per mm, and with two copies, any split works: 49.68 and 0, 0 and 49.68, or 1,000 and ; all give the same predictions. The bowl has a flat-bottomed trough instead of a single lowest point. lstsq picks the split with the smallest weights, 24.84 each.
The same trouble, milder, comes from columns that are nearly copies, like height in centimetres and height in inches rounded differently: can be inverted, but barely, and the weights swing wildly. Lesson 3.8's ridge regression fixes both.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- Goodfellow, Bengio and Courville, Deep Learning, chapter 5: Machine Learning Basics: the normal equations for linear regression (5.1.4)
- NumPy: numpy.linalg.lstsq: least-squares solutions, even when XᵀX can’t be inverted
- scikit-learn: LinearRegression: ordinary least squares, with coef_ and intercept_