Linear regression
Linear regression computed live in your browser: least-squares lines and planes, QR closed form vs gradient descent, the loss surface and descent path. Drag any point and it recomputes, in 2D and 3D.
Updated
- Least squares
- Mean squared error
- QR closed-form solution
- Gradient descent and learning rate
- Effect of outliers
Intuition
Make the squared residuals small
Given a cloud of points, draw the line that "fits best". Best in what sense? Each point sits some vertical distance from the line — its residual, prediction minus truth. Square every residual and add them up; smaller is better. Squaring stops positive and negative residuals from cancelling, and punishes large errors more.
The three small labs below run for real in your browser. The orange line is the current fit, thin vertical strokes are residuals, and the grey dashed line is the least-squares optimum.
The first starts from a line sloping the wrong way, turns towards the data step by step and lands on the grey line after 100 steps with : the line explains 86% of the variation in ; the rest is noise. The data were generated from , and least squares finds , — with a finite, noisy sample the estimate never lands exactly on the truth.
The second adds just three outliers and the best line is dragged flat: the slope falls from 1.13 to 0.80 and to 0.38. Squaring lets far-away points shout.
The third follows a parabola. No straight line fits, and is only 0.16. Nothing went wrong in the computation — the model has the wrong shape. Linear regression represents linear relationships only (though "linear" refers to the parameters; see the FAQ below).
Math
Model and loss
samples, each with features and a target . The model and the mean squared error are:
Gradient
With residuals , the partial derivatives are:
Gradient descent steps against the gradient, with step size (learning rate) :
Why step against the gradient? A first-order Taylor expansion: a small step changes the loss by about . For a fixed step length, the loss falls fastest when points opposite to . Taking predicts a drop of — and for small learning rates the actual drop is very close to it. The lab computes the gradient with the formulas above, and the tests check it against NumPy (to within ) and against this site's automatic-differentiation engine.
Closed form: one step
Fold the bias into the design matrix with parameters . Setting the gradient to zero gives the normal equations . Solving them directly squares the condition number and loses half the significant digits when the data sit far from the origin; this page factors with Householder QR and solves the triangular system , which is far more stable.
Learning rate, curvature and speed
is quadratic in , so its Hessian (curvature matrix) is constant:
Decompose the error along the eigenvectors of : each step multiplies the component along direction by :
- : it approaches steadily;
- : every step overshoots to the other side, but by less each time — a zig-zag;
- : it overshoots further and further and diverges.
So it converges only if even the steepest direction satisfies , while the overall speed is set by the slower of the two directions; making the two factors equal in size gives the fastest step:
For the default data and : the limit is about 0.297 and the fastest rate about 0.23. Their ratio is the condition number — how flat the loss "bowl" is; the larger , the more the steepest direction caps the learning rate, and the more slowly the gentle direction moves. Measured steps until the loss is within of the optimum:
| Learning rate | Steps |
|---|---|
| 0.01 | 404 |
| 0.05 (default) | 78 |
| 0.2 | 17 |
| 0.22 | 15 |
| 0.29 | 164 (oscillating near the limit) |
| 0.3 | diverges |
The same data, 60 steps each:
With η = 0.01 the MSE is still 1.62 after 60 steps; with η = 0.22 the gradient reaches machine precision at step 52 and the run stops; with η = 0.3 every step overshoots further, and after 60 steps the MSE is about 157.
With a fixed step on a quadratic loss like this, the error shrinks by a constant factor every step (linear convergence). At the default η = 0.05 the slow direction is multiplied by per step; the loss is proportional to the squared error, so the "excess loss over the optimum" is multiplied by about per step — measured, exactly 0.812, halving roughly every 3 steps.
Coefficient of determination
The denominator is the error of guessing the mean every time. is a perfect fit; the least-squares solution has between 0 and 1; a bad enough line makes it negative — the η = 0.3 run above has at step 60.
How it is computed, with real numbers
The numbers below come from the lab at the top of the page — its data and parameters right now. Train, drag a point or change the learning rate and this recomputes.
Once the lab above has loaded, this panel works through the same formulas with its current numbers.
Experiment
Follow the lesson
Course
Lesson 1: from gradient descent to the closed form
5 steps · each one: set up and run → look → answer
1. Gradient descent finds the line
Default data, default learning rate 0.05. Watch the fit on the left and the loss curve on the right.
2. Too large a learning rate
Set the learning rate to 0.3 and watch the loss curve and the path in the "Loss contours" tab.
3. The fastest learning rate
Try 0.22, then 0.29.
4. The closed form
Switch the method to "QR closed form" and press step once.
5. Outliers
Switch to the "Outliers" data and turn on "Squared residuals".
Try these settings
The plane is worth rotating in 3D: the vertical strokes from each point to the plane are the residuals, and least squares minimises the sum of their squares. With two features gradient descent needs 83 steps; the curvature matrix becomes 3 × 3, and everything else is the same.
Exercises
Exercises
The lab above checks these live and ticks them off.
Exercise 1: converge within 20 steps
Change only the learning rate. Goal: at step 20 the loss is within of the optimum. After a run you can drag the timeline back to step 20.
Hint
η = 0.2 takes 17 steps and 0.22 only 15. Do not go past 0.297 — the limit for these data.
- Excess loss L − L* ≤ 1.0e-6
- at most 20 epochs
Exercise 2: drag the outliers back
Drag points in the fit view. Goal: of at least 0.85. After dragging, press step once so QR solves for the new data.
Hint
All three points at the bottom right must go back near the line (about ): all three give , only two give 0.64.
- R² ≥ 0.850
Exercise 3: drown the signal in noise
Change only the noise σ. Goal: the least-squares is at most 0.5.
Hint
σ = 1.8 gives and σ = 2 about 0.46. The line itself varies with variance about 4.3; when the noise variance σ² is about as large, is near 0.5.
- R² ≤ 0.500
Quiz
Further reading
Frequently asked questions
How are linear regression and least squares related?
Linear regression is the model (ŷ = w·x + b); least squares is the criterion for choosing its parameters — minimise the sum of squared residuals. The usual "linear regression" is a linear model fitted by least squares; minimising absolute errors instead gives least-absolute-deviation regression, which is more robust to outliers.
When should I use the closed form, and when gradient descent?
With a modest number of features (up to a few thousand) and data that fit in memory, use QR or SVD: one step, an exact answer. Use gradient descent for huge data, very many features, or models that are not linear (neural networks). Never invert AᵀA directly: it squares the condition number.
Can R² be negative?
Yes. The least-squares solution always has R² between 0 and 1, but an arbitrary line can score below 0, meaning it does worse than always guessing the mean. In this page's learning-rate-0.3 example, R² is about −30.7 at step 60.
How do I choose the learning rate for gradient descent?
The limit is 2/λmax, where λmax is the largest eigenvalue of the curvature matrix (2/n)AᵀA; the fastest is 2/(λmax + λmin). For this page's default data they are 0.297 and 0.23. In practice, standardise the features first (zero mean, unit variance) so the curvature is similar in every direction and a good rate is easy to find.
Can linear regression fit curves?
Yes, as long as the model is linear in its parameters: add x², x³, sin x and so on as new features (polynomial or basis-function regression) and use the same least squares. With x alone, this page's parabola data reach an R² of only 0.16.
Why is least squares sensitive to outliers, and what can I do?
Errors are squared, so a point three times further away counts nine times as much. Here three outliers drag the slope from 1.13 to 0.80. Use a Huber or absolute-value loss (robust regression), or find the outliers first with RANSAC.
Further reading
- Legendre, Nouvelles méthodes pour la détermination des orbites des comètes, 1805: the first published account of least squares.
- Gauss, Theoria motus corporum coelestium, 1809: least squares and normally distributed errors.
- Hastie, Tibshirani, Friedman, The Elements of Statistical Learning, chapter 3: linear regression, subset selection and shrinkage.
- Boyd, Vandenberghe, Introduction to Applied Linear Algebra, chapters 12–13: least squares and QR, beginner-friendly.
- Trefethen, Bau, Numerical Linear Algebra, lectures 10–11: Householder triangularisation and the stability of least squares.
- NumPy, numpy.linalg.lstsq: this page's reference implementation.