←Back to 03 / Published Articles
03 / Resources/Regression · Linear Regression
Interactive Diagnostic Essay · Topic 01

Linear Regression: Ordinary Least Squares

The first model everyone learns — and the one everything else is built on. Watch a line hunt for the best fit, drag your own residuals, and race gradient descent against the closed-form solution.

01 / The Line That Hunts

What Does “Fitting a Line” Actually Mean?

You have data: hours studied vs exam score. Linear regression draws the straight line y^=mx+c\hat{y} = mx + c that comes closest to all points at once — mm is the slope (how much the score rises per extra hour) and cc is the intercept (the baseline score).

But “closest” needs a definition. For every point we measure the residual ei=yi−y^ie_i = y_i - \hat{y}_i — the vertical gap between truth and prediction. We square each gap (so negatives don't cancel positives) and add them up:

SSE=∑i=1N(yi−(mxi+c))2\text{SSE} = \sum_{i=1}^N (y_i - (mx_i + c))^2

In the animation, the orange line is a candidate fit sweeping through angles — too steep, too flat, too steep again. The red dashed segments are the residuals it leaves behind. The best line is the one minimizing the total squared length of those red segments — Ordinary Least Squares (OLS).

CANDIDATE LINE SWEEPING ↔minimize Σ e²
hours studied →exam score →best fit (OLS)

The dashed ink line never moves — OLS already found it.

02 / Residual Geometry

Sandbox: Steal the Line Yourself

Drag the slope and intercept and watch the squared error react. Can you beat the computer's answer before you press the snap button?

SLOPE (m)0.80
INTERCEPT (c)15.0
MEAN SQUARED ERROR39.00
COEFFICIENT R²0.925

Notice that R2R^2 reads as “the fraction of variance the line explains” — 0 means the line is no better than predicting the mean, 1.01.0 means a perfect fit through every point.

RESIDUALS (VERTICAL DISTANCES)ŷ = 0.80x + 15.0

Red dashed hairlines are the errors eie_i. OLS minimizes the sum of their squares.

03 / Two Ways Down the Bowl

Normal Equations vs Gradient Descent

The error is a bowl over the parameter space — every pair (m,c)(m, c) is a point on its surface, and the height is the MSE. There are two classic ways to reach the bottom:

Closed-Form Normal Equationβ∗=(XTX)−1XTy\mathbf{\beta}^* = (\mathbf{X}^T \mathbf{X})^{-1} \mathbf{X}^T \mathbf{y}

One matrix inversion teleports you straight to the bottom. Exact — but O(D3)\mathcal{O}(D^3) cost makes it impractical for huge feature counts.

Gradient Descent Updateβt+1=βt−η∇β MSE\beta_{t+1} = \beta_t - \eta \nabla_\beta \, \text{MSE}

Take small steps η\eta downhill, opposite the gradient. Cheap per step, iterative — and the learning rate is everything: too small crawls, too large overshoots and zigzags (watch the ink ball).

η = 0.3 (smooth)η = 1.6 (overshooting)
MSE SURFACE · m
slope m → (c fixed) · minimum at m*m* (global min)

Both balls want the same minimum — only the journey differs.

04 / Judging a Regression

Metrics & the Fine Print

MSE / RMSERMSE=1N∑(yi−y^i)2\text{RMSE} = \sqrt{\tfrac{1}{N}\sum (y_i - \hat{y}_i)^2}

Squaring makes outliers scream — a single point 10× off hurts 100× more. RMSE returns to the target's units.

MAEMAE=1N∑∣yi−y^i∣\text{MAE} = \tfrac{1}{N}\sum |y_i - \hat{y}_i|

Every error counts linearly — robust to outliers. Pick MAE when a few wild points shouldn't dominate the score.

R² (Coefficient of Determination)R2=1−SSE∑(yi−yˉ)2R^2 = 1 - \frac{\text{SSE}}{\sum (y_i - \bar{y})^2}

Variance explained vs a mean-only baseline. Comparable across datasets — but a high R² never implies causation.

Assumptions (The Fine Print)
  • Linearity — the relationship really is straight.
  • Independence — errors don't correlate (no time leakage).
  • Homoscedasticity — error spread is constant, not funnel-shaped.
  • Normal residuals — needed for valid confidence intervals.
OPTIMAL SOLUTION FOR THE SANDBOX DATASET:m* = 0.858, c* = 15.08
05 / The Fine Print

Six Assumptions Holding the Line Up

OLS will hand you coefficients no matter how badly the data misbehaves. These six assumptions are the conditions under which those coefficients mean what the textbook says they mean. Read each one as a question you can ask of a residual plot.

Validityy=f(x1,…,xp)+εy = f(x_1, \dots, x_p) + \varepsilonTest

Do the features and the target still mean what the decision needs?

Representativenessβ^→β as n→Npop\hat{\beta} \to \beta \text{ as } n \to N_{\text{pop}}Test

Would a fresh case from deployment look at home in your training rows?

Additivity & Linearityy=β0+β1x1+⋯+βpxp+εy = \beta_0 + \beta_1 x_1 + \cdots + \beta_p x_p + \varepsilonTest

Plot residuals against fitted values — a curve hiding there breaks the straight-line claim.

Independence of ErrorsCov(ei,ej)=0i≠j\text{Cov}(e_i, e_j) = 0 \quad i \neq jTest

Do residuals drift with collection order, time, or group?

HomoscedasticityVar(ei)=σ2for all i\text{Var}(e_i) = \sigma^2 \quad \text{for all } iTest

Does the residual cloud fan out as predictions grow?

Normality of Errorsei∼N(0,σ2)e_i \sim \mathcal{N}(0, \sigma^2)Test

Read a QQ plot — this one buys valid confidence intervals, not better predictions.

RESIDUALS vs FITTED · HETEROSCEDASTICspread grows with ŷ
fitted value ŷ →residual e →growing envelope

The cloud fans open and snaps shut — variance is not constant.

RESIDUALS vs FITTED · HOMOSCEDASTICassumed · spread = σ²
fitted value ŷ →residual e →constant envelope

The ideal the assumption asks for — same width everywhere.

When Assumptions Fail

A violated assumption is not an automatic failure. In machine learning the test is narrower: does the model generalize to unseen data? A predictor that scores well on a held-out set is still useful even when its errors are lumpy or its residuals are not Gaussian. Statistical purity matters most when you are making inferences — confidence intervals, p-values, causal claims — and far less when you are shipping predictions. So start by asking whether the assumption even applies to your question.

Transform the data

Logs or square roots tame a fanning residual cloud and straighten a multiplicative relationship.

Extend the model

Add interaction or polynomial terms, or move to something that bends — splines, GAMs, trees.

Gather more data

Widen the sample until it represents the population you actually deploy to.

Restrict the question

Narrow the claim or the input range until the data can honestly support it.

06 / Scoring The Fit

MSE, RMSE, MAE & R² — Four Lenses on One Error

All four scores are computed from the same residuals. They differ only in how they weigh a miss — and that choice is a statement about what you care about.

MSEMean Squared Error
MSE=1N∑i=1N(yi−y^i)2\text{MSE} = \frac{1}{N}\sum_{i=1}^N (y_i - \hat{y}_i)^2

Units: squared target units — score², ₹², whatever yy is measured in.

Failure mode: punishes outliers quadratically — an error twice as large contributes four times as much.

RMSERoot Mean Squared Error
RMSE=1N∑i=1N(yi−y^i)2\text{RMSE} = \sqrt{\frac{1}{N}\sum_{i=1}^N (y_i - \hat{y}_i)^2}

Units: the target's own units — MSE\sqrt{\text{MSE}} is why RMSE is the score you report out loud.

Failure mode: the square is still inside the root, so one wild point can set your headline number.

MAEMean Absolute Error
MAE=1N∑i=1N∣yi−y^i∣\text{MAE} = \frac{1}{N}\sum_{i=1}^N |y_i - \hat{y}_i|

Units: target units — directly readable as “the average miss”.

Failure mode: robust to outliers, but ∣⋅∣|\cdot| is non-differentiable at 00, and a fat tail of medium errors hides inside the same average.

R²Coefficient of Determination
R2=1−∑i(yi−y^i)2∑i(yi−yˉ)2R^2 = 1 - \frac{\sum_i (y_i - \hat{y}_i)^2}{\sum_i (y_i - \bar{y})^2}

Units: dimensionless — 11 is perfect, 00 is no better than the mean, negative is worse than the mean.

Failure mode: always rises as you add features, even pure noise — never compare R² across models with different feature counts. Use adjusted R² or a held-out set.

Worked · Study-Hours Dataset at the OLS Optimum (N = 9)
MSE27.73SSE / N = 249.58 / 9
RMSE5.27√27.73
MAE4.31Σ|e| / N = 38.83 / 9
R²0.9471 − 249.58 / 4670

RMSE (5.27) sits above MAE (4.31) — that gap is the outlier signature. When the two converge, errors are evenly sized; when RMSE runs away, a handful of points are carrying the score.