Foundations to Frontier
Tests
D. Classical Machine Learning › D1 Linear Models for Regression

Simple Linear Regression

Simple linear regression fits a straight line y = b₀ + b₁x to pairs of numbers by least squares: it chooses the intercept and slope that minimise the sum of squared vertical distances to the points. The answer has a closed form (slope = covariance over variance), comes with standard errors, confidence and prediction intervals under classical assumptions, and is the foundation of nearly every model that follows. This page covers the method from a hand-worked example to its derivation, its assumptions and what happens when they fail. In the exercises you implement the fit, its inference (including the t distribution), prediction intervals and a gradient-descent version; then you simulate thousands of datasets to measure when the textbook 95% interval for the slope can be trusted.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

The best straight line through dots

Put some dots on paper and lay a ruler across them so it passes as close as possible to all of them. Some dots sit above the ruler and some below. Linear regression finds the one ruler position where the misses, each squared so that big misses count extra, add up to the smallest total. Then you can use the line to guess new values: “if the battery is 20 °C warmer, the range drops by about this much.”

Drag the dots, find the best line
■ least squares: ŷ = 2.16 + 0.64x, sum of squares 1.14 · ■ your line: 1.84
However you set the sliders, your sum of squares can only match the orange line's, never beat it. Drag one dot far away and watch the line swing: squaring makes far points pull hard (see robust losses, D0.6).
Why engineers care

Sensor calibration curves, thrust against throttle, battery capacity against cycles, and drag against speed in a narrow range are all fitted with straight lines first. The slope and its uncertainty are often the engineering answer.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Linear regression finds…
  2. 2. Why square the misses?
  3. 3. In the demo, can your line ever beat the orange line's total?

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

A worked example by hand

x y x − x̄ y − ȳ (x − x̄)(y − ȳ) (x − x̄)²
1 2 −2 −2 4 4
2 4 −1 0 0 1
3 5 0 1 0 0
4 4 1 0 0 1
5 5 2 1 2 4
mean 3 mean 4 sum 6 sum 10

The fit, step by step:

  • slope b₁ = 6/10 = 0.6;
  • intercept b₀ = ȳ − b₁x̄ = 4 − 0.6·3 = 2.2, so ŷ = 2.2 + 0.6x;
  • predictions 2.8, 3.4, 4.0, 4.6, 5.2;
  • residuals −0.8, 0.6, 1.0, −0.6, −0.2 (they sum to 0);
  • SSE = 2.4 and total SS = 6, so R² = 1 − 2.4/6 = 0.6.

The steps in plain English:

  1. Find the average x and the average y.
  2. For every point, multiply how far x is from its average by how far y is from its average, and add these up.
  3. Divide by the sum of squared x-distances: that is the slope.
  4. Put the line through the point (x̄, ȳ).
📝 Quick check (Level 1)
0/3 answered
  1. 1. The least-squares line always passes through…
  2. 2. Slope with Sxy = 12 and Sxx = 4?
  3. 3. The residuals of a least-squares line with an intercept sum to…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

Model, estimates and inference

Model: yᵢ = β₀ + β₁xᵢ + εᵢ, with E[εᵢ] = 0.

Least squares minimises S(b₀, b₁) = Σ(yᵢ − b₀ − b₁xᵢ)². Setting both partial derivatives to zero gives the normal equations, with solution:

  • b₁ = Sxy/Sxx;
  • b₀ = ȳ − b₁x̄.

Classical assumptions: linear mean, independent errors, constant variance σ², and (for exact small-sample intervals) normal errors. Under them:

  • s² = SSE/(n − 2) estimates σ²;
  • SE(b₁) = s/√Sxx;
  • the 95% CI for β₁ is b₁ ± t₀.₉₇₅,ₙ₋₂ · SE(b₁);
  • a prediction interval for a new y at x₀ adds the noise itself: ŷ₀ ± t·s·√(1 + 1/n + (x₀ − x̄)²/Sxx).
function FIT(x, y):
    x̄, ȳ ← mean(x), mean(y)
    b1 ← Σ (x − x̄)(y − ȳ) / Σ (x − x̄)²
    b0 ← ȳ − b1·x̄
    return b0, b1
from sklearn.linear_model import LinearRegression
m = LinearRegression().fit(x.reshape(-1, 1), y); print(m.intercept_, m.coef_)
import statsmodels.api as sm
print(sm.OLS(y, sm.add_constant(x)).fit(cov_type="HC3").summary())      # inference, robust SEs

Hyperparameters: none (that is part of its appeal). Use it when the relationship is roughly linear over the range of interest and you want interpretable effects with uncertainty. Avoid it when the relationship is curved (D1.4, D1.20), outliers are present (D1.11–D1.13), or x is measured with substantial error.

🐍 Exercise 1: simple regression with its inference
Fit the line in closed form; compute R²; implement the Student t 97.5% quantile by numerical integration and bisection; compute residual standard error, standard errors and a 95% confidence interval for the slope; compute a 95% prediction interval; reproduce the fit by gradient descent; check everything against the hand-worked example.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Degrees of freedom for s² in simple regression?
  2. 2. A prediction interval is wider than a confidence interval for the mean because…
  3. 3. Intervals are narrowest at…

Level 3: Advanced

★★★★☆ Advanced⏱ 35 minGraduate level, with full derivations and proofs.

Derivation and properties

Derivation. ∂S/∂b₀ = −2Σ(yᵢ − b₀ − b₁xᵢ) = 0 gives b₀ = ȳ − b₁x̄. Substituting into ∂S/∂b₁ = −2Σxᵢ(yᵢ − b₀ − b₁xᵢ) = 0 gives b₁ = Σ(xᵢ − x̄)(yᵢ − ȳ)/Σ(xᵢ − x̄)². S is a convex quadratic, so this is the unique minimum when the xᵢ are not all equal.

Properties.

  • b₁ = r·s_y/s_x, so R² = r².
  • The estimates are unbiased with Var(b₁) = σ²/Sxx.
  • By the Gauss–Markov theorem, OLS is the best linear unbiased estimator under uncorrelated, constant-variance errors. With normal errors it is also the maximum-likelihood estimator.
  • Cost: O(n) time, O(1) memory (one pass with running sums).

When the assumptions fail:

Violation Effect Remedy
non-constant variance estimates fine, SEs wrong robust (HC3) SEs, weighted LS
correlated errors (time series) SEs far too small HAC (Newey–West) SEs, model the correlation
heavy tails / outliers estimates pulled robust regression (D1.11–D1.13)
error in x slope biased toward 0 (attenuation) errors-in-variables (Deming, total least squares)
non-linearity biased predictions transforms, polynomials, splines

Interview questions.

  • Why does regressing y on x give a different line from regressing x on y? Each minimises vertical distances in its own direction; the slopes are r·s_y/s_x and r·s_x/s_y.
  • What is regression to the mean? With |r| < 1, predictions are fewer standard deviations from the mean than the inputs.
📝 Quick check (Level 3)
0/3 answered
  1. 1. Measurement noise in x makes the OLS slope…
  2. 2. Gauss–Markov says OLS is…
  3. 3. With autocorrelated errors, classical SEs are usually…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

When can you trust the slope’s interval?

History. Legendre published least squares in 1805 to fit comet orbits. Gauss claimed to have used it since 1795 and in 1809 justified it with normal errors, which helped him recover the dwarf planet Ceres. Galton named “regression” in 1886 after observing that children of tall parents are on average less tall: regression to the mean.

Exercise 1. The hand example is reproduced exactly: ŷ = 2.2 + 0.6x, R² = 0.6. With only five points, the slope’s 95% interval (−0.30, 1.50) includes zero. The prediction interval at x = 3 spans (0.88, 7.12). Gradient descent converges to the same line.

Exercise 2 (reproduction). Setup: 4 000 simulated datasets of n = 30 per situation, true slope 0.5. The table reports the mean OLS slope and the coverage of the classical and HC3-robust 95% intervals:

Situation Mean slope Classical coverage HC3 coverage
ideal: normal errors, constant σ 0.501 0.953 0.956
heteroscedastic, σ ∝ x 0.497 0.931 0.948
heavy-tailed errors, t with 3 df 0.500 0.955 0.960
time trend with AR(1) errors, ρ = 0.8 0.499 0.497 0.511
x measured with noise, reliability 0.7 0.353 0.454 0.460
  • The interval is robust to heavy tails. It is slightly too narrow under heteroscedasticity, which HC3 repairs.
  • Correlated errors are the real danger. The slope estimate stays unbiased, but its true spread is three times the reported standard error, so the “95%” interval covers only half the time.
  • Noise in x biases the slope itself by the reliability factor 0.7, so no standard-error fix helps. You need an errors-in-variables model.

Open questions. Valid inference after model selection. Regression with dependent, heavy-tailed engineering data at small n. Errors-in-variables with unknown noise levels.

🐍 Exercise 2 (research): coverage of the slope interval
Simulate 4 000 datasets of 30 points under five conditions (ideal, heteroscedastic, heavy-tailed, autocorrelated errors with trending x, and noisy x); fit OLS to all of them at once; measure the slope's bias and how often the classical and HC3 95% intervals contain the true slope.

Simple regression in AI, robotics and aerospace

  • Sensor calibration: linear fits of raw counts to physical units, with prediction intervals as calibration uncertainty.
  • Degradation trends: capacity fade per cycle. Telemetry errors are autocorrelated, so use HAC standard errors.
  • System identification: first-order gain estimates from step tests.
  • Scientific fitting: Hubble’s law (velocity against distance) was a simple regression.

References

  1. A.-M. Legendre (1805). Nouvelles méthodes pour la détermination des orbites des comètes. Paris.
  2. C. F. Gauss (1809). Theoria motus corporum coelestium. Hamburg.
  3. F. Galton (1886). “Regression towards mediocrity in hereditary stature.” Journal of the Anthropological Institute 15.
  4. H. White (1980). “A heteroskedasticity-consistent covariance matrix estimator and a direct test for heteroskedasticity.” Econometrica 48(4).
  5. W. K. Newey, K. D. West (1987). “A simple, positive semi-definite, heteroskedasticity and autocorrelation consistent covariance matrix.” Econometrica 55(3).