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
iter 0 · Σr² = 70.47iter 1 · Σr² = 31.50iter 2 · Σr² = 17.99iter 3 · Σr² = 13.15iter 5 · Σr² = 10.56iter 8 · Σr² = 9.94iter 13 · Σr² = 9.81iter 21 · Σr² = 9.80iter 34 · Σr² = 9.79QR · Σr² = 9.79min Σ rᵢ²
Preparing the lab…

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.

Gradient descent, η = 0.05Preparing…
Three outliers, bottom rightPreparing…
The data are curvedPreparing…

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 R2≈0.86R^2 \approx 0.86: the line explains 86% of the variation in yy; the rest is noise. The data were generated from y=1.2x−0.6y = 1.2x - 0.6, and least squares finds w∗≈1.13w^* \approx 1.13, b∗≈−0.59b^* \approx -0.59 — 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 R2R^2 to 0.38. Squaring lets far-away points shout.

The third follows a parabola. No straight line fits, and R2R^2 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

nn samples, each with dd features xi∈Rdx_i\in\mathbb R^d and a target yiy_i. The model and the mean squared error are:

y^i=w⋅xi+b,L(w,b)=1n∑i=1n(y^i−yi)2\hat y_i = w\cdot x_i + b, \qquad L(w,b) = \frac1n\sum_{i=1}^{n}\big(\hat y_i - y_i\big)^2

Gradient

With residuals ri=y^i−yir_i = \hat y_i - y_i, the partial derivatives are:

∂L∂wj=2n∑iri xij,∂L∂b=2n∑iri\frac{\partial L}{\partial w_j} = \frac2n\sum_i r_i\,x_{ij}, \qquad \frac{\partial L}{\partial b} = \frac2n\sum_i r_i

Gradient descent steps against the gradient, with step size (learning rate) η\eta:

w←w−η ∂L∂w,b←b−η ∂L∂bw \leftarrow w - \eta\,\frac{\partial L}{\partial w}, \qquad b \leftarrow b - \eta\,\frac{\partial L}{\partial b}

Why step against the gradient? A first-order Taylor expansion: a small step Δθ\Delta\theta changes the loss by about ∇L⋅Δθ\nabla L\cdot\Delta\theta. For a fixed step length, the loss falls fastest when Δθ\Delta\theta points opposite to ∇L\nabla L. Taking Δθ=−η∇L\Delta\theta = -\eta\nabla L predicts a drop of η ∥∇L∥2\eta\,\|\nabla L\|^2 — 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 10−1210^{-12}) and against this site's automatic-differentiation engine.

Closed form: one step

Fold the bias into the design matrix A=[X    1]A = [X \;\; \mathbf 1] with parameters θ=(w,b)\theta = (w, b). Setting the gradient to zero gives the normal equations A⊤A θ=A⊤yA^\top A\,\theta = A^\top y. Solving them directly squares the condition number and loses half the significant digits when the data sit far from the origin; this page factors A=QRA = QR with Householder QR and solves the triangular system R θ=Q⊤yR\,\theta = Q^\top y, which is far more stable.

Learning rate, curvature and speed

LL is quadratic in θ\theta, so its Hessian (curvature matrix) is constant:

H=2nA⊤AH = \frac2n A^\top A

Decompose the error θt−θ∗\theta_t - \theta^* along the eigenvectors of HH: each step multiplies the component along direction kk by 1−ηλk1 - \eta\lambda_k:

  • ηλk<1\eta\lambda_k < 1: it approaches steadily;
  • 1<ηλk<21 < \eta\lambda_k < 2: every step overshoots to the other side, but by less each time — a zig-zag;
  • ηλk>2\eta\lambda_k > 2: it overshoots further and further and diverges.

So it converges only if even the steepest direction satisfies ∣1−ηλmax⁡∣<1|1 - \eta\lambda_{\max}| < 1, while the overall speed is set by the slower of the two directions; making the two factors equal in size gives the fastest step:

η<2λmax⁡,η∗=2λmax⁡+λmin⁡ (fastest)\eta < \frac{2}{\lambda_{\max}}, \qquad \eta^* = \frac{2}{\lambda_{\max} + \lambda_{\min}}\ \text{(fastest)}

For the default data λmax⁡≈6.72\lambda_{\max}\approx 6.72 and λmin⁡≈1.98\lambda_{\min}\approx 1.98: the limit is about 0.297 and the fastest rate about 0.23. Their ratio is the condition number κ=λmax⁡/λmin⁡≈3.39\kappa = \lambda_{\max}/\lambda_{\min} \approx 3.39 — how flat the loss "bowl" is; the larger κ\kappa, the more the steepest direction caps the learning rate, and the more slowly the gentle direction moves. Measured steps until the loss is within 10−610^{-6} of the optimum:

Learning rate η\etaSteps
0.01404
0.05 (default)78
0.217
0.2215
0.29164 (oscillating near the limit)
0.3diverges

The same data, 60 steps each:

η = 0.01: too slowPreparing…
η = 0.22: near the fastestPreparing…
η = 0.3: over the limitPreparing…

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 1−0.05×1.98≈0.9011 - 0.05 \times 1.98 \approx 0.901 per step; the loss is proportional to the squared error, so the "excess loss over the optimum" is multiplied by about 0.9012≈0.8120.901^2 \approx 0.812 per step — measured, exactly 0.812, halving roughly every 3 steps.

Coefficient of determination R2R^2

R2=1−∑i(yi−y^i)2∑i(yi−yˉ)2=1−n L∑i(yi−yˉ)2R^2 = 1 - \frac{\sum_i (y_i-\hat y_i)^2}{\sum_i (y_i-\bar y)^2} = 1 - \frac{n\,L}{\sum_i (y_i-\bar y)^2}

The denominator is the error of guessing the mean every time. R2=1R^2 = 1 is a perfect fit; the least-squares solution has R2R^2 between 0 and 1; a bad enough line makes it negative — the η = 0.3 run above has R2≈−30.7R^2 \approx -30.7 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. 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.

    After 60 steps the line barely moves. Why?
  2. 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.

    Why does the loss keep growing?
  3. 3. The fastest learning rate

    Try 0.22, then 0.29.

    0.29 is larger than 0.22, so why is it so much slower (164 steps against 15)?
  4. 4. The closed form

    Switch the method to "QR closed form" and press step once.

    Why does QR reach the optimum in one step?
  5. 5. Outliers

    Switch to the "Outliers" data and turn on "Squared residuals".

    How can three points flatten the line?

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 10−610^{-6} 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: R2R^2 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 y=1.2x−0.6y = 1.2x - 0.6): all three give R2≈0.89R^2 \approx 0.89, only two give 0.64.

  • R² ≥ 0.850

Exercise 3: drown the signal in noise

Change only the noise σ. Goal: the least-squares R2R^2 is at most 0.5.

Hint

σ = 1.8 gives R2≈0.52R^2 \approx 0.52 and σ = 2 about 0.46. The line itself varies with variance about 4.3; when the noise variance σ² is about as large, R2R^2 is near 0.5.

  • R² ≤ 0.500

Quiz

What happens if the learning rate exceeds 2/λmax?
What does R² = 0.86 mean?
Which model can NOT be fitted by linear regression?

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.