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:
Here is the weight (the slope) and is the bias (the height at ), as in P0.2. With input features the model is a weighted sum plus a bias:
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 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 in the first column and the constant 1 in the second:
From here on, contains the column of ones, and contains the bias. With examples and features, has rows and columns. (To keep the formulas short, the costs later on write for the number of columns.)
Residuals and the loss
The residual of an example is the gap between the true value and the prediction, . (P0.2 wrote the error the other way round, . 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 residuals into one number, square each one and average:
This is the mean squared error (MSE). The sum without the is the sum of squared errors (SSE). Its square root, the RMSE, is in the units of , so it is easier to read.
The line of P0.2 has residuals , SSE and MSE . The best line (found below) has , , predictions , residuals , SSE , MSE and RMSE .
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 from is the conditional mean (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 , , the MSE and R² (explained below). Everything you see recomputes after each move.
Things to try (each checked against the widget):
- The defaults. The readouts show , , MSE and R² , the numbers of P0.2. Tick “Show the squares”: the three squares have areas , and , and their average is the MSE.
- Pull the top point down. Move the point at from down to . 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”: , , MSE , R² . Press “Last one moved”: one point is now far below the others, and the line flattens to , , with MSE and R² . 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”: , , MSE . Press “200 steps” from the restart: , , MSE . 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
Setting it to zero gives the normal equations:
P1.B11 reaches the same equations by geometry: is the point in the span of the columns closest to , so the leftover is perpendicular to every column.
For the three points, and . As two equations:
The second gives . Putting that into the first gives , so and . The prediction at is .
Go deeper The one-feature formulas and what the best line guarantees
One feature in plain statistics. With a single feature the solution is and , where and . For the three points , , , , so and . The second formula says the line passes through the mean point . In terms of the correlation between and , the slope is (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 say two things (checked in the code below): the residuals add to , and the residuals are perpendicular to the column. For the three points the residuals are : they add to , and .
Solve, do not invert
Many textbooks write . 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 directly (by a QR factorization or the SVD of P1.B13) and never forms . The reason: the sensitivity of the system, its condition number, is squared by that product. For the three points it is for and for .
When is singular
Suppose the data contain the feature twice, so has the columns . Then the prediction depends only on , so , and all give the same predictions and the same MSE. There is no single best weight vector. The matrix 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 ; or add a penalty on the weights, which is regularization (P3.A6): is invertible for .
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 the residual vector gives , the slopes of P0.2. With learning rate the update gives the same trace as P0.2 and P2.7:
| Step | MSE | ||
|---|---|---|---|
| 0 | 1.000 | 0.000 | 6.000 |
| 1 | 1.500 | 0.200 | 1.807 |
| 2 | 1.727 | 0.280 | 0.970 |
| 10 | 1.958 | 0.232 | 0.718 |
| 50 | 2.166 | −0.240 | 0.583 |
| 200 | 2.446 | −0.876 | 0.502 |
| 1000 | 2.500 | −1.000 | 0.500 |
After 200 steps the prediction at is (P2.7), against 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 is positive semidefinite for any (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 exceeds . Centring 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 , . If the columns of are independent the minimum is unique. With a copied feature there is a whole flat valley of best weights, and descent that starts at ends at the same smallest-weights answer that lstsq returns.
For the three points the Hessian is with eigenvalues and (P1.C8). The step must satisfy , and then the flat direction, with eigenvalue , shrinks the error by only a factor of per step. The ratio is the condition number (P1.F3).
The slow valley comes from the columns and being correlated: both are positive, so changing and changing do almost the same thing. Subtract the mean from (so ) and the cross term vanishes. The Hessian becomes , with condition number and the stable limit . The fit is then , (the height at the mean ), the same line in new coordinates. With the loss is within of the minimum after 55 steps, against 233 steps with the raw ; with 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 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 , with constant Hessian , 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 the step is , and it lands on . Solving the normal equations is one Newton step; the work of forming and solving a 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 takes about multiply-adds, and solving the system takes about . The cost is (P1.G4), the matrix needs numbers of memory, and the answer is exact up to rounding. There is nothing to tune.
- Gradient descent. One step multiplies by a vector and by a vector, about multiply-adds, so per step, and it never forms a 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 examples for each step, at a cost of , and works even when is too large to hold in memory.
Go deeper A worked cost comparison
With examples and features, forming costs roughly multiply-adds, and solving costs roughly . Descent costs roughly per step, so about 500 steps cost the same as forming the matrix. With , the matrix alone has 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 , so means little by itself. Two common ways to make it readable:
- RMSE , in the units of : points.
- R², the fraction of the variation in that the model accounts for. Compare the model with the dumbest rule, “always predict the mean ”. That rule has squared error , and the model has . Then
For the three points and , so .
How to read it. means a perfect fit and means no better than the mean. For a least-squares line with a bias, fitted and scored on the same data, is between and , and with one feature it equals the squared correlation, . But R² can be negative: nothing forces SSE below SST. It happens for a line that is not the least-squares line: has SSE and on the three points, worse than predicting every time. It also happens for a good line on new data. Score on three new points , with the mean of the new as the baseline. The predictions are , the test MSE is (against on the training data) and . These points lie outside the training range to and their values vary little (SST ), 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 is the change in the prediction when feature goes up by one unit while the other features stay fixed. In the example, one more hour of study adds points to the prediction. The bias is the prediction at , 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.
- 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 and gives weights , and on three random samples, while their sum stays near every time. Individual weights of correlated features should not be interpreted one by one.
- 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).
- Association, not cause. The line describes how co-varies with in this data. It says nothing about what would happen if you changed (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 with noise , and:
- Linearity. On average, is a linear function of the features: . The features may be transformed (, ), 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.
- 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).
- Constant variance. The spread of the noise is the same for every . It fails when large values are noisier than small ones.
- 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 , 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 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 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 to . The best line becomes , : 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 : add a column of 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 () 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 ). 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 , with containing a column of ones.
Loss , gradient , Hessian .
Normal equations ; unique solution if and only if the columns of are independent. Residual satisfies .
Descent , stable for with the largest eigenvalue of ; speed set by the condition number .
One feature: , .
; for a fit with a bias on its own training data (one feature).
Cost: closed form ; one descent step .
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.75LinearRegression 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 singular with a copied feature, shows what ridge does, and shows weights swinging when two features are nearly copies. Both use only NumPy.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Exercises
- Fit the line to the points with the one-feature formulas, and compute the MSE and R².
Show answer
, . and , so and . The predictions are , the residuals , SSE and MSE . SST , so . - For the three points of this lesson, compute the gradient of the MSE at and take one step with .
Show answer
The errors are . The slope in is , and the slope in is . The step gives and . - Subtract the mean from in the three-point data, so that becomes , and refit. What are and , and what does now mean?
Show answer
(the slope does not change) and . Now is the prediction at the mean of , which is the mean of : with centred features is diagonal and the bias is simply . - A data set has a second feature equal to times the first. Why is singular, and describe all the best weights for the two features.
Show answer
The second column is a multiple of the first, so the columns are dependent and the matrix has a null direction: for (with the bias column last). If is best, then so is for every , with identical predictions. The predictions depend only on . - What is the R² of the constant prediction on the three points? And of the line ?
Show answer
For the SSE equals the SST, so . For the SSE is , so . - With and , about how many multiply-adds does forming take, and about how many descent steps cost the same?
Show answer
About . A descent step costs about , so about 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. - Change the last target of the three points from to . Without computing, which way does the slope move? Then compute it.
Show answer
Up, because the far point pulls the line towards it. With the normal equations are and , which give and .
Check your understanding
For the points , which line has the smallest mean squared error?
The normal equations , give , , and the residuals give MSE . The line has residuals and MSE , which is larger. The constant has MSE , and has residuals and MSE : all larger than , and no line can beat the least-squares line.
A line with a bias term is fitted by least squares. What is true of its residuals on the training data?
The bias is a column of ones, and the normal equations say the residual vector is perpendicular to every column, including that one, so the residuals sum to . Their size depends on the data, they usually differ from each other, and since they sum to they cannot all be positive .
You want a linear model with features. Which statement about the cost is correct?
The closed form scales like in time and in memory, and with that is far too much. One step of gradient descent scales like and stores only vectors. The claim that the normal equations are cheaper than one step of descent is false for every : they cost about times as much as one step. They can still beat a whole descent run when is small, but that is a different claim. Descent needs no closed form at all, and matters for both methods.
A fitted model gets on a test set. What does that mean?
, and it is negative exactly when the model’s squared error exceeds that of the mean-only baseline. That can happen on new data (or for a bad line on any data). The bounds and apply to a least-squares line scored on the data it was fitted to. Explaining half the variation would be , and a perfect fit gives .
Two features are almost exact copies of each other. What is the most accurate description of the fitted linear regression?
When the features are nearly copies, the data fix only their combined effect, so the split of the weight between them changes with tiny changes in the sample (the lesson’s example gave , and with a sum near ). An exact copy leaves infinitely many solutions rather than none. The weights can have any signs, and the predictions on similar data are usually fine.
Next: P3.A3 adds powers of 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.