Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 3: Classical Machine LearningCore Concepts

Linear regression

P3.A240 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

Linear regression is the smallest complete learning system: a model, a loss, and two ways to minimize it. Almost every later model reuses its pieces, so it is worth understanding fully.

Before this: The supervised learning setup, How a machine "learns", Projections and least squares, Gradient descent

After this lesson you can

  • Write the model ŷ = w·x + b for one or many features, treat the bias as a constant feature, and compute residuals and the mean squared error by hand
  • Find the best weights with the normal equations (solved, not inverted), and say what goes wrong when two features are copies of each other
  • Run gradient descent on the same loss with the same numbers, and explain when the closed form or gradient descent is the better tool and why feature scale changes how fast descent goes
  • Compute and read R², interpret a coefficient (with the correlated-features caveat), and state the assumptions and the weak spots of a linear fit

A student studied 1 hour and scored 2, studied 2 hours and scored 3, studied 3 hours and scored 7. How many points should we expect after 2.5 hours? Any answer needs a rule that turns hours into points, and the simplest rule is a straight line. This lesson is about choosing the best straight line, in two different ways, and about how far to trust it.

You met these three points in P0.2, where a loop found the line step by step. Here we find the same line in one calculation, check that both ways agree, and then ask the questions a careful practitioner asks: how good is the fit, what do the numbers mean, and when does a line mislead?

The model

With one input, the model is a line:

y^=w x+b.\hat{y}=w\,x+b .

Here ww is the weight (the slope) and bb is the bias (the height at x=0x=0), as in P0.2. With dd input features x1,…,xdx_1,\dots,x_d the model is a weighted sum plus a bias:

y^=w1x1+w2x2+⋯+wdxd+b=w⋅x+b.\hat{y}=w_1x_1+w_2x_2+\dots+w_dx_d+b=\mathbf{w}\cdot\mathbf{x}+b .

One weight per feature says how much that feature pushes the prediction. Geometrically, one feature gives a line, two give a flat sheet (a plane) above the two-feature plane, and more give a flat surface in higher dimensions. “Linear” here means linear in the weights: the prediction is a sum of weights times features.

The bias as a constant feature. Add a column of ones to the data. Then bb multiplies a feature that always equals 1, so it is just one more weight, and the whole model is a single matrix product. For the three points the data matrix has the feature xx in the first column and the constant 1 in the second:

X=(112131),w=(wb),y=(237),y^=Xw.\begin{aligned} \mathbf{X}&=\begin{pmatrix}1&1\\2&1\\3&1\end{pmatrix},& \mathbf{w}&=\begin{pmatrix}w\\b\end{pmatrix},\\[4pt] \mathbf{y}&=\begin{pmatrix}2\\3\\7\end{pmatrix},& \hat{\mathbf{y}}&=\mathbf{X}\mathbf{w}. \end{aligned}

From here on, X\mathbf{X} contains the column of ones, and w\mathbf{w} contains the bias. With NN examples and dd features, X\mathbf{X} has NN rows and d+1d+1 columns. (To keep the formulas short, the costs later on write dd for the number of columns.)

Residuals and the loss

The residual of an example is the gap between the true value and the prediction, ri=yi−y^ir_i=y_i-\hat{y}_i. (P0.2 wrote the error the other way round, y^−y\hat y-y. The sign does not matter once we square it.) A residual is the vertical distance from a point to the line, not the shortest distance.

To turn NN residuals into one number, square each one and average:

L(w)=1N∑i=1N(yi−y^i)2=1N∥y−Xw∥2.\mathcal{L}(\mathbf{w})=\frac1N\sum_{i=1}^{N}\bigl(y_i-\hat{y}_i\bigr)^2=\frac1N\lVert\mathbf{y}-\mathbf{X}\mathbf{w}\rVert^2 .

This is the mean squared error (MSE). The sum without the 1N\frac1N is the sum of squared errors (SSE). Its square root, the RMSE, is in the units of yy, so it is easier to read.

The line w=1, b=0w=1,\ b=0 of P0.2 has residuals 1, 1, 41,\ 1,\ 4, SSE =1+1+16=18=1+1+16=18 and MSE =6=6. The best line (found below) has w=2.5w=2.5, b=−1b=-1, predictions 1.5, 4, 6.51.5,\ 4,\ 6.5, residuals 0.5, −1, 0.50.5,\ -1,\ 0.5, SSE =1.5=1.5, MSE =0.5=0.5 and RMSE ≈0.71\approx0.71.

Why squared? Several reasons point the same way.

  • Squaring stops positive and negative residuals from cancelling, and it is smooth, so the slope of the loss exists everywhere (an absolute value has a corner).
  • For a linear model the squared loss is a bowl, so every local minimum is global (P1.F2), and the lowest point has a formula (next section).
  • The best single number to predict for a whole group under squared error is the group’s mean (P1.D4), and the best predictor of yy from xx is the conditional mean E[y∣x]\mathbb{E}[y\mid x] (P1.D5). A line fitted with squared error is the best straight-line approximation of that conditional mean.
  • If the data are a line plus Gaussian noise with a fixed spread, then maximizing the likelihood is the same as minimizing the squared error (P1.D10). Squared error is not an arbitrary choice: it is the right loss for that noise model.

The price is that squaring makes large residuals count a lot. We return to this under outliers.

The picture: drag the points

Use the widget with its default three points. The blue line is the least-squares line, the red segments are the residuals, and the readouts show ww, bb, the MSE and R² (explained below). Everything you see recomputes after each move.

Fit a line: drag the points

1234562468xy
least-squares line residuals
Least squares: w = 2.5, b = −1
MSE = 0.5
R² = 0.893

Best line: ŷ = 2.5 x − 1, with MSE 0.5 and R² 0.893.

Drag a point, or Tab to it and use the arrow keys (Shift for larger steps). Red segments are the residuals (vertical gaps between each point and the line). With “Show the squares” on, each residual gets a square of the same side: the MSE is the average area of the squares.

The least-squares line (blue) and its vertical residuals (red) for points you can drag. Optional extras: squares on the residuals, and a gradient descent line (pink, dashed) that starts at w = 1, b = 0. The “Last one moved” button loads six points with the last one far off the line.

Things to try (each checked against the widget):

  • The defaults. The readouts show w=2.5w=2.5, b=−1b=-1, MSE 0.50.5 and R² 0.8930.893, the numbers of P0.2. Tick “Show the squares”: the three squares have areas 0.250.25, 11 and 0.250.25, and their average is the MSE.
  • Pull the top point down. Move the point at x=3x=3 from y=7y=7 down to y=6y=6. The point is now closer to the line, so its square is smaller, and the line tilts less steeply to follow it.
  • Outlier. Press “6 near a line”: w=0.9w=0.9, b=0.55b=0.55, MSE 0.0330.033, R² 0.9860.986. Press “Last one moved”: one point is now far below the others, and the line flattens to w=0.257w=0.257, b=1.729b=1.729, with MSE 1.641.64 and R² 0.1050.105. One point changed the slope by a factor of 3.5.
  • Gradient descent. Tick “Gradient descent” on the three-point data and press “1 step”: w=1.5w=1.5, b=0.2b=0.2, MSE 1.8071.807. Press “200 steps” from the restart: w=2.446w=2.446, b=−0.876b=-0.876, MSE 0.5020.502. The pink line is almost on the blue one but not quite. Now drag a point while descent is on: the blue line jumps at once, and the pink line starts chasing a new target.

The closed form: the normal equations

A bowl is lowest where its slope is zero. The gradient of the MSE with respect to the weights (the matrix calculus of P1.C11, with P1.C5 for the three points) is

∇wL=2N X⊤(Xw−y).\nabla_{\mathbf{w}}\mathcal{L}=\frac2N\,\mathbf{X}^{\top}(\mathbf{X}\mathbf{w}-\mathbf{y}).

Setting it to zero gives the normal equations:

X⊤X w=X⊤y.\mathbf{X}^{\top}\mathbf{X}\,\mathbf{w}=\mathbf{X}^{\top}\mathbf{y}.

P1.B11 reaches the same equations by geometry: Xw\mathbf{X}\mathbf{w} is the point in the span of the columns closest to y\mathbf{y}, so the leftover y−Xw\mathbf{y}-\mathbf{X}\mathbf{w} is perpendicular to every column.

For the three points, X⊤X=(14663)\mathbf{X}^{\top}\mathbf{X}=\begin{pmatrix}14&6\\6&3\end{pmatrix} and X⊤y=(2912)\mathbf{X}^{\top}\mathbf{y}=\begin{pmatrix}29\\12\end{pmatrix}. As two equations:

14 w+6 b=29,6 w+3 b=12.14\,w+6\,b=29,\qquad 6\,w+3\,b=12 .

The second gives b=4−2wb=4-2w. Putting that into the first gives 14w+24−12w=2914w+24-12w=29, so w=2.5w=2.5 and b=−1b=-1. The prediction at x=2.5x=2.5 is 2.5⋅2.5−1=5.252.5\cdot2.5-1=5.25.

Go deeper The one-feature formulas and what the best line guarantees

One feature in plain statistics. With a single feature the solution is w=SxySxxw=\dfrac{S_{xy}}{S_{xx}} and b=yˉ−wxˉb=\bar y-w\bar x, where Sxy=∑i(xi−xˉ)(yi−yˉ)S_{xy}=\sum_i(x_i-\bar x)(y_i-\bar y) and Sxx=∑i(xi−xˉ)2S_{xx}=\sum_i(x_i-\bar x)^2. For the three points xˉ=2\bar x=2, yˉ=4\bar y=4, Sxy=5S_{xy}=5, Sxx=2S_{xx}=2, so w=2.5w=2.5 and b=4−2.5⋅2=−1b=4-2.5\cdot2=-1. The second formula says the line passes through the mean point (xˉ,yˉ)=(2,4)(\bar x,\bar y)=(2,4). In terms of the correlation rr between xx and yy, the slope is w=r sy/sxw=r\,s_y/s_x (the standard-deviation ratio), the regression line of P1.D7.

What the best line guarantees. Because the bias is a column of ones, the first and second rows of X⊤(y−Xw)=0\mathbf{X}^{\top}(\mathbf{y}-\mathbf{X}\mathbf{w})=\mathbf{0} say two things (checked in the code below): the residuals add to 00, and the residuals are perpendicular to the xx column. For the three points the residuals are 0.5, −1, 0.50.5,\ -1,\ 0.5: they add to 00, and 1⋅0.5+2⋅(−1)+3⋅0.5=01\cdot0.5+2\cdot(-1)+3\cdot0.5=0.

Solve, do not invert

Many textbooks write w=(X⊤X)−1X⊤y\mathbf{w}=(\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbf{y}. That formula is right on paper and a poor recipe on a computer (P1.B9): a solver such as np.linalg.solve is faster and more accurate than forming an inverse. Even better, a least-squares routine such as np.linalg.lstsq works from X\mathbf{X} directly (by a QR factorization or the SVD of P1.B13) and never forms X⊤X\mathbf{X}^{\top}\mathbf{X}. The reason: the sensitivity of the system, its condition number, is squared by that product. For the three points it is 6.796.79 for X\mathbf{X} and 46.146.1 for X⊤X\mathbf{X}^{\top}\mathbf{X}.

When X⊤X\mathbf{X}^{\top}\mathbf{X} is singular

Suppose the data contain the feature xx twice, so X\mathbf{X} has the columns x, x, 1x,\ x,\ 1. Then the prediction depends only on w1+w2w_1+w_2, so (2.5, 0, −1)(2.5,\,0,\,-1), (1.25, 1.25, −1)(1.25,\,1.25,\,-1) and (2, 0.5, −1)(2,\,0.5,\,-1) all give the same predictions and the same MSE. There is no single best weight vector. The matrix X⊤X\mathbf{X}^{\top}\mathbf{X} is singular (its rank is 2 out of 3), and np.linalg.solve raises an error (or, with rounded data, can return meaningless huge weights). The same happens when one feature is a sum or a multiple of others (P1.B7, P1.B8), or when there are fewer examples than weights.

What to do: drop the redundant feature; or use lstsq, which returns the solution with the smallest weights, here (1.25, 1.25, −1)(1.25,\,1.25,\,-1); or add a penalty on the weights, which is regularization (P3.A6): X⊤X+λI\mathbf{X}^{\top}\mathbf{X}+\lambda\mathbf{I} is invertible for λ>0\lambda>0.

The nearly singular case is the one you meet in practice. Two features that are almost copies give a matrix that is invertible but badly conditioned: the predictions stay good, while the individual weights swing wildly with tiny changes in the data. The code below shows it.

Gradient descent on the same loss

The loss is a bowl, so we can also walk down it, as in P0.2 and P1.F3. Start with the gradient above. At w=1, b=0w=1,\ b=0 the residual vector gives ∇L=(−10, −4)\nabla\mathcal{L}=(-10,\,-4), the slopes of P0.2. With learning rate η=0.05\eta=0.05 the update w←w−η∇L\mathbf{w}\leftarrow\mathbf{w}-\eta\nabla\mathcal{L} gives the same trace as P0.2 and P2.7:

StepwwbbMSE
01.0000.0006.000
11.5000.2001.807
21.7270.2800.970
101.9580.2320.718
502.166−0.2400.583
2002.446−0.8760.502
10002.500−1.0000.500

After 200 steps the prediction at x=2.5x=2.5 is 5.245.24 (P2.7), against 5.255.25 from the closed form. Both methods minimize the same loss, so they must agree, and they do. Descent only arrives later, and it is slow near the end. Why?

The loss is convex. Its Hessian 2NX⊤X\frac2N\mathbf{X}^{\top}\mathbf{X} is positive semidefinite for any X\mathbf{X} (P1.C8, P1.F2), so every local minimum is global, and with a small enough step descent reaches the best line from any start. Descent crawls near the end because the loss is a long thin valley, and it blows up if η\eta exceeds 2/λmax⁡=0.1802/\lambda_{\max}=0.180. Centring xx makes descent about 4 times faster (233 steps to 55) and does not change the line.

Go deeper Why descent is slow here, and what centring does

For any X\mathbf{X}, v⊤X⊤Xv=∥Xv∥2≥0\mathbf{v}^{\top}\mathbf{X}^{\top}\mathbf{X}\mathbf{v}=\lVert\mathbf{X}\mathbf{v}\rVert^2\ge0. If the columns of X\mathbf{X} are independent the minimum is unique. With a copied feature there is a whole flat valley of best weights, and descent that starts at w=0\mathbf{w}=\mathbf{0} ends at the same smallest-weights answer that lstsq returns.

For the three points the Hessian is (28/3442)\begin{pmatrix}28/3&4\\4&2\end{pmatrix} with eigenvalues 11.0911.09 and 0.240.24 (P1.C8). The step must satisfy η<2/11.09=0.180\eta<2/11.09=0.180, and then the flat direction, with eigenvalue 0.240.24, shrinks the error by only a factor of 1−η⋅0.241-\eta\cdot0.24 per step. The ratio 11.09/0.24≈4611.09/0.24\approx46 is the condition number (P1.F3).

The slow valley comes from the columns xx and 11 being correlated: both are positive, so changing ww and changing bb do almost the same thing. Subtract the mean from xx (so x=−1, 0, 1x=-1,\ 0,\ 1) and the cross term vanishes. The Hessian becomes diag(4/3, 2)\mathrm{diag}(4/3,\ 2), with condition number 1.51.5 and the stable limit η<1\eta<1. The fit is then w=2.5w=2.5, b=4b=4 (the height at the mean xˉ=2\bar x=2), the same line in new coordinates. With η=0.05\eta=0.05 the loss is within 0.0010.001 of the minimum after 55 steps, against 233 steps with the raw xx; with η=0.3\eta=0.3 it takes 8 steps. This is a main reason to centre and rescale features before gradient descent (P3.A11, and P4.19 for the same idea inside networks). It does not change the best line, only the weights’ units, because ww is measured per unit of the feature’s scale.

Go deeper One Newton step is the normal equations

Newton’s method (P1.F6) jumps to the minimum of the quadratic model of the loss. The MSE of a linear model is exactly quadratic in w\mathbf{w}, with constant Hessian 2NX⊤X\frac2N\mathbf{X}^{\top}\mathbf{X}, so the quadratic model is the loss itself and one Newton step lands on the minimum from any start. That minimum satisfies the normal equations. From (1,0)(1,0) the step is (1.5, −1)(1.5,\,-1), and it lands on (2.5, −1)(2.5,\,-1). Solving the normal equations is one Newton step; the work of forming and solving a d×dd\times d system is the price of that single step.

Closed form or gradient descent?

Both find the same weights. They differ in cost.

  • Closed form. Forming X⊤X\mathbf{X}^{\top}\mathbf{X} takes about Nd2Nd^2 multiply-adds, and solving the d×dd\times d system takes about d3d^3. The cost is O(Nd2+d3)O(Nd^2+d^3) (P1.G4), the matrix needs d2d^2 numbers of memory, and the answer is exact up to rounding. There is nothing to tune.
  • Gradient descent. One step multiplies X\mathbf{X} by a vector and X⊤\mathbf{X}^{\top} by a vector, about 2Nd2Nd multiply-adds, so O(Nd)O(Nd) per step, and it never forms a d×dd\times d matrix. The total is the step cost times the number of steps. It needs a learning rate and a stopping rule, and the number of steps depends on the conditioning.
  • Stochastic descent (P1.F4) uses a small batch of BB examples for each step, at a cost of O(Bd)O(Bd), and works even when NN is too large to hold in memory.
Go deeper A worked cost comparison

With N=106N=10^6 examples and d=1000d=1000 features, forming X⊤X\mathbf{X}^{\top}\mathbf{X} costs roughly 101210^{12} multiply-adds, and solving costs roughly 10910^9. Descent costs roughly 2×1092\times10^9 per step, so about 500 steps cost the same as forming the matrix. With d=105d=10^5, the matrix X⊤X\mathbf{X}^{\top}\mathbf{X} alone has 101010^{10} entries, about 80 GB in 64-bit numbers.

Rule of thumb: for a few thousand features at most, use the closed form (through lstsq). For very many features or examples, or for a model with no closed form, use descent. The closed form is a special case: only a squared loss with a model that is linear in its weights gives a formula this simple. Logistic regression (P3.A7) and neural networks (P4.8) have none, and the descent loop, which you practised on the line, is the tool that remains.

How good is the fit? RMSE and R²

The MSE depends on the units of yy, so 0.50.5 means little by itself. Two common ways to make it readable:

  • RMSE =MSE=\sqrt{\mathrm{MSE}}, in the units of yy: 0.5≈0.71\sqrt{0.5}\approx0.71 points.
  • R², the fraction of the variation in yy that the model accounts for. Compare the model with the dumbest rule, “always predict the mean yˉ\bar y”. That rule has squared error SST=∑i(yi−yˉ)2\mathrm{SST}=\sum_i(y_i-\bar y)^2, and the model has SSE=∑i(yi−y^i)2\mathrm{SSE}=\sum_i(y_i-\hat y_i)^2. Then
R2=1−SSESST.R^2=1-\frac{\mathrm{SSE}}{\mathrm{SST}} .

For the three points SST=(2−4)2+(3−4)2+(7−4)2=14\mathrm{SST}=(2-4)^2+(3-4)^2+(7-4)^2=14 and SSE=1.5\mathrm{SSE}=1.5, so R2=1−1.5/14=0.893R^2=1-1.5/14=0.893.

How to read it. R2=1R^2=1 means a perfect fit and R2=0R^2=0 means no better than the mean. For a least-squares line with a bias, fitted and scored on the same data, R2R^2 is between 00 and 11, and with one feature it equals the squared correlation, r2=52/(2⋅14)=0.893r^2=5^2/(2\cdot14)=0.893. But R² can be negative: nothing forces SSE below SST. It happens for a line that is not the least-squares line: w=1, b=0w=1,\ b=0 has SSE 1818 and R2=1−18/14=−0.286R^2=1-18/14=-0.286 on the three points, worse than predicting 44 every time. It also happens for a good line on new data. Score 2.5x−12.5x-1 on three new points (4,8), (5,9), (6,10)(4,8),\ (5,9),\ (6,10), with the mean of the new yy as the baseline. The predictions are 9, 11.5, 149,\ 11.5,\ 14, the test MSE is 7.757.75 (against 0.50.5 on the training data) and R2=−10.6R^2=-10.6. These points lie outside the training range 11 to 33 and their yy values vary little (SST =2=2), so R² swings hard. A negative test R² means the model does worse than the plain average there (P3.A4).

Two cautions. Adding features never lowers the training R² (and almost always raises it), so a high training R² can come from overfitting (P3.A3). And R² does not say that a line is the right shape or that the model is useful: it is one number, and the residual plot below tells you more.

Reading the weights

The weight wjw_j is the change in the prediction when feature jj goes up by one unit while the other features stay fixed. In the example, one more hour of study adds 2.52.5 points to the prediction. The bias b=−1b=-1 is the prediction at x=0x=0, which here is outside the range of the data (1 to 3 hours), so it is an extrapolation and not a fact about students who study 0 hours.

Three cautions, in order of how often they bite.

  1. Correlated features share credit unpredictably. When two features move together, the data cannot separate their effects. The prediction depends on the combination, and the split between the two weights is decided by small accidents of the sample. Running the code below with x2≈x1x_2\approx x_1 and y≈3x1y\approx3x_1 gives weights (1.78, 1.23)(1.78,\,1.23), (2.92, 0.07)(2.92,\,0.07) and (4.41, −1.50)(4.41,\,-1.50) on three random samples, while their sum stays near 33 every time. Individual weights of correlated features should not be interpreted one by one.
  2. Units and scale. A weight is “per unit”, so a feature measured in metres and the same feature in millimetres get weights 1000 times apart. To compare the importance of weights, put the features on a common scale first (P3.A11).
  3. Association, not cause. The line describes how yy co-varies with xx in this data. It says nothing about what would happen if you changed xx (P1.D13).

What the model assumes

Say precisely what you are claiming. The fit itself, minimizing the squared error, is just an optimization and needs no assumptions. The assumptions decide whether the fit is a good model and whether its error bars can be trusted. The model is y=w⋅x+b+εy=\mathbf{w}\cdot\mathbf{x}+b+\varepsilon with noise ε\varepsilon, and:

  1. Linearity. On average, yy is a linear function of the features: E[y∣x]=w⋅x+b\mathbb{E}[y\mid\mathbf{x}]=\mathbf{w}\cdot\mathbf{x}+b. The features may be transformed (x2x^2, ln⁡x\ln x), since the model only needs to be linear in the weights. If the relationship curves and you do not add such features, the model is biased everywhere in a pattern.
  2. Independent errors. The noise of one example does not depend on that of another. This fails for time series, where today’s error resembles yesterday’s, and when examples come in groups (several rows from the same person).
  3. Constant variance. The spread of the noise is the same for every x\mathbf{x}. It fails when large values are noisier than small ones.
  4. No exact redundancy among features (full column rank), so the weights are unique.

Under assumptions 1 to 4, with noise that has mean zero given x\mathbf{x}, equal variance and zero correlation between examples (independence is enough), the least-squares weights are unbiased, and among all unbiased estimators that are linear in y\mathbf{y} they have the smallest variance (the Gauss–Markov theorem: they are “BLUE”).

Normality is not required for prediction. You do not need Gaussian noise to fit the line or to predict with it. Gaussian noise gives the exact maximum-likelihood reading of the loss (P1.D10) and the textbook small-sample confidence intervals; with moderate or large samples, the central limit theorem (P1.D8) makes many of those intervals approximately right even when the noise is not Gaussian.

How to check: plot the residuals against the predictions. A patternless band around zero of even width is what you want; a curve means non-linearity, a funnel means non-constant variance. The best line always has residuals that sum to 00 and are uncorrelated with each feature, so those two checks tell you nothing: look at the pattern.

Outliers pull hard

A residual of 4 costs 16 and a residual of 1 costs 1, so a far point counts 16 times as much in the loss and pulls the line 4 times as hard. Take the three points and change the last target from 77 to 1717. The best line becomes w=7.5w=7.5, b=−7.67b=-7.67: the slope tripled because of one number. The widget’s “Last one moved” preset shows the same on six points.

Remedies: look at the data first (an outlier is sometimes a typing mistake and sometimes the most interesting row); use a loss that grows more slowly for large errors, such as the absolute error, whose best constant is the median (P1.D4), or Huber loss (P4.6); or use a robust regression method. These give up the closed form, but descent still works. The right choice depends on whether the far point is an error or real data.

Beyond a straight line: preview

A model that is linear in the weights can still be curved in xx: add a column of x2x^2 and the same normal equations fit a parabola, which passes exactly through the three points (MSE 0) because there are three weights for three points. Zero training error is not a sign of a good model; P3.A3 shows why, and P3.A6 shows how a penalty (X⊤X+λI\mathbf{X}^{\top}\mathbf{X}+\lambda\mathbf{I}) keeps it in check.

Intuition

Picture a stiff rod fastened to every point by a spring, each spring pulling straight up or down. The more a spring stretches, the harder it pulls, and the pull grows with the stretch, so far points pull much harder than near ones. The rod settles where the pulls balance: the up and down pulls cancel (residuals sum to 0), and so do the twists (residuals are perpendicular to xx). That balanced rod is the least-squares line. Say the springs have zero rest length. The analogy breaks in that real springs snap or saturate when stretched far, while the squared loss keeps pulling harder, which is the outlier problem.

Closed form and descent are two ways to find the bottom of a bowl: compute where the slope is zero, or roll down.

Math

Model y^=Xw\hat{\mathbf{y}}=\mathbf{X}\mathbf{w}, with X∈RN×(d+1)\mathbf{X}\in\mathbb{R}^{N\times(d+1)} containing a column of ones.

Loss L=1N∥y−Xw∥2\mathcal{L}=\frac1N\lVert\mathbf{y}-\mathbf{X}\mathbf{w}\rVert^2, gradient 2NX⊤(Xw−y)\frac2N\mathbf{X}^{\top}(\mathbf{X}\mathbf{w}-\mathbf{y}), Hessian 2NX⊤X⪰0\frac2N\mathbf{X}^{\top}\mathbf{X}\succeq0.

Normal equations X⊤Xw=X⊤y\mathbf{X}^{\top}\mathbf{X}\mathbf{w}=\mathbf{X}^{\top}\mathbf{y}; unique solution if and only if the columns of X\mathbf{X} are independent. Residual e=y−Xw\mathbf{e}=\mathbf{y}-\mathbf{X}\mathbf{w} satisfies X⊤e=0\mathbf{X}^{\top}\mathbf{e}=\mathbf{0}.

Descent w←w−η 2NX⊤(Xw−y)\mathbf{w}\leftarrow\mathbf{w}-\eta\,\frac2N\mathbf{X}^{\top}(\mathbf{X}\mathbf{w}-\mathbf{y}), stable for η<2/λmax⁡\eta<2/\lambda_{\max} with λmax⁡\lambda_{\max} the largest eigenvalue of 2NX⊤X\frac2N\mathbf{X}^{\top}\mathbf{X}; speed set by the condition number κ\kappa.

One feature: w=Sxy/Sxx=r sy/sxw=S_{xy}/S_{xx}=r\,s_y/s_x, b=yˉ−wxˉb=\bar y-w\bar x.

R2=1−SSE/SSTR^2=1-\mathrm{SSE}/\mathrm{SST}; for a fit with a bias on its own training data R2=r2R^2=r^2 (one feature).

Cost: closed form O(Nd2+d3)O(Nd^2+d^3); one descent step O(Nd)O(Nd).

Code

The model in scikit-learn, shown here as a static block because scikit-learn is not available in the in-browser runner. The output is from a local run (scikit-learn 1.8.0).

import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score, mean_squared_error

X = np.array([[1.0], [2.0], [3.0]])   # shape (N, d) = (3, 1)
y = np.array([2.0, 3.0, 7.0])

model = LinearRegression()            # adds the bias for you
model.fit(X, y)
print("w:", model.coef_, " b:", round(model.intercept_, 4))
print("prediction at 2.5:", model.predict([[2.5]]).round(4))
print("train R^2:", round(model.score(X, y), 4))

X_test = np.array([[4.0], [5.0], [6.0]])
y_test = np.array([8.0, 9.0, 10.0])
pred = model.predict(X_test)
print("test R^2:", round(r2_score(y_test, pred), 4))
print("test MSE:", round(mean_squared_error(y_test, pred), 4))
w: [2.5]  b: -1.0
prediction at 2.5: [5.25]
train R^2: 0.8929
test R^2: -10.625
test MSE: 7.75

LinearRegression takes the features without the column of ones, stores the weights in coef_ and the bias in intercept_, and solves the problem by a least-squares routine, not by gradient descent.

Try it

The first cell finds the line with the normal equations and with lstsq, checks the properties of the residuals and R², and runs gradient descent with the numbers of the table. The second cell makes X⊤X\mathbf{X}^{\top}\mathbf{X} singular with a copied feature, shows what ridge does, and shows weights swinging when two features are nearly copies. Both use only NumPy.

Try it: the same line, two ways

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Try it: a copied feature, ridge, and nearly copied features

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Exercises

  1. Fit the line to the points (0,1), (1,3), (2,4)(0,1),\ (1,3),\ (2,4) with the one-feature formulas, and compute the MSE and R².
    Show answerxˉ=1\bar x=1, yˉ=8/3\bar y=8/3. Sxy=(−1)(1−83)+0+(1)(4−83)=3S_{xy}=(-1)(1-\tfrac83)+0+(1)(4-\tfrac83)=3 and Sxx=2S_{xx}=2, so w=1.5w=1.5 and b=83−1.5=76≈1.167b=\tfrac83-1.5=\tfrac76\approx1.167. The predictions are 1.167, 2.667, 4.1671.167,\ 2.667,\ 4.167, the residuals −0.167, 0.333, −0.167-0.167,\ 0.333,\ -0.167, SSE =0.167=0.167 and MSE =0.0556=0.0556. SST =4.667=4.667, so R2=1−0.167/4.667=0.964R^2=1-0.167/4.667=0.964.
  2. For the three points of this lesson, compute the gradient of the MSE at w=2, b=0w=2,\ b=0 and take one step with η=0.05\eta=0.05.
    Show answerThe errors y^−y\hat y-y are 0, 1, −10,\ 1,\ -1. The slope in ww is 23(1⋅0+2⋅1+3⋅(−1))=−23\frac23(1\cdot0+2\cdot1+3\cdot(-1))=-\frac23, and the slope in bb is 23(0+1−1)=0\frac23(0+1-1)=0. The step gives w=2+0.05⋅23=2.033w=2+0.05\cdot\frac23=2.033 and b=0b=0.
  3. Subtract the mean from xx in the three-point data, so that xx becomes −1, 0, 1-1,\ 0,\ 1, and refit. What are ww and bb, and what does bb now mean?
    Show answerw=2.5w=2.5 (the slope does not change) and b=4b=4. Now bb is the prediction at the mean of xx, which is the mean of yy: with centred features X⊤X\mathbf{X}^{\top}\mathbf{X} is diagonal and the bias is simply yˉ\bar y.
  4. A data set has a second feature equal to 33 times the first. Why is X⊤X\mathbf{X}^{\top}\mathbf{X} singular, and describe all the best weights for the two features.
    Show answerThe second column is a multiple of the first, so the columns are dependent and the matrix has a null direction: Xn=0\mathbf{X}\mathbf{n}=\mathbf{0} for n=(3, −1, 0)\mathbf{n}=(3,\,-1,\,0) (with the bias column last). If (w1, w2, b)(w_1,\,w_2,\,b) is best, then so is (w1+3t, w2−t, b)(w_1+3t,\ w_2-t,\ b) for every tt, with identical predictions. The predictions depend only on w1+3w2w_1+3w_2.
  5. What is the R² of the constant prediction y^=4\hat y=4 on the three points? And of the line w=1, b=0w=1,\ b=0?
    Show answerFor y^=4\hat y=4 the SSE equals the SST, so R2=0R^2=0. For w=1, b=0w=1,\ b=0 the SSE is 1818, so R2=1−18/14=−0.286R^2=1-18/14=-0.286.
  6. With N=106N=10^6 and d=1000d=1000, about how many multiply-adds does forming X⊤X\mathbf{X}^{\top}\mathbf{X} take, and about how many descent steps cost the same?
    Show answerAbout Nd2=1012Nd^2=10^{12}. A descent step costs about 2Nd=2×1092Nd=2\times10^9, so about 500500 steps cost the same. Whether descent is cheaper then depends on how many steps it needs, which depends on the conditioning and the learning rate.
  7. Change the last target of the three points from 77 to 1717. Without computing, which way does the slope move? Then compute it.
    Show answerUp, because the far point pulls the line towards it. With X⊤y=(1⋅2+2⋅3+3⋅17, 2+3+17)=(59, 22)\mathbf{X}^{\top}\mathbf{y}=(1\cdot2+2\cdot3+3\cdot17,\ 2+3+17)=(59,\,22) the normal equations are 14w+6b=5914w+6b=59 and 6w+3b=226w+3b=22, which give w=7.5w=7.5 and b=−7.667b=-7.667.

Check your understanding

  1. For the points (1,2), (2,3), (3,7)(1,2),\ (2,3),\ (3,7), which line has the smallest mean squared error?

  2. A line with a bias term is fitted by least squares. What is true of its residuals on the training data?

  3. You want a linear model with d=100 000d=100\,000 features. Which statement about the cost is correct?

  4. A fitted model gets R2=−0.5R^2=-0.5 on a test set. What does that mean?

  5. Two features are almost exact copies of each other. What is the most accurate description of the fitted linear regression?

Next: P3.A3 adds powers of xx as columns, which makes the fit curved and shows what goes wrong when it becomes too flexible. P3.A4 gives the proper way to measure a model on data it has not seen, and P3.A6 stabilizes the weights with a penalty. P3.A7 keeps the weighted sum and swaps the loss to classify.

Key takeaways

  • The model is ŷ = w·x + b. Add a constant feature 1 to every example and the bias becomes one more weight, so ŷ = Xw. The residual of an example is y − ŷ, and the loss is the mean squared error (MSE), the average of the squared residuals.
  • Squared error is smooth, is convex for linear models (every local minimum is global), is minimized by the mean, and is the negative log-likelihood of Gaussian noise (P1.D10). The price is sensitivity to outliers: one far point can swing the line a long way.
  • The best weights satisfy the normal equations XᵀXw = Xᵀy. For the three points (1,2), (2,3), (3,7) they read 14w + 6b = 29 and 6w + 3b = 12, with solution w = 2.5, b = −1 and MSE 0.5. At the best line the residuals add to 0 and are perpendicular to every column of X.
  • Solve the normal equations with a solver, not by inverting XᵀX. If a feature is a copy (or a combination) of others, XᵀX is singular: infinitely many weight vectors give the same predictions, and nearly copied features make the weights unstable.
  • Gradient descent on the same MSE uses the gradient (2/N)Xᵀ(Xw − y). From w = 1, b = 0 with η = 0.05 it reaches (1.5, 0.2) after one step and (2.446, −0.876) after 200, approaching (2.5, −1). The closed form costs about Nd² + d³, one step of descent about Nd, so descent wins for very many features or examples.
  • R² = 1 − SSE/SST compares the fit with always predicting the mean of y. It is 0.893 for the three points, and it can be negative on new data. Coefficients describe association, not cause, and with correlated features they are not individually reliable.
Found a mistake? Tell us