Skip to content
mlmentorship

Linear regression

Fit an affine prediction by squared residuals, verify its projection, and separate solver, sampling, penalty, and variance assumptions.

Published · 6 min read ·Core ·Foundation

Visual quick review

See ordinary least squares as projecting the observed target vector onto the column space of the design matrix, leaving a residual perpendicular to every feature direction.

Learning objective

The residual is perpendicular to the fitted column space

The residual is perpendicular to the fitted subspaceThe model can place its prediction only on the feasible rail. Dropping the observation straight onto that rail gives the shortest remaining gap. Moving along the rail makes that gap longer. Different coefficients may describe the same point, but cannot create a closer prediction off the rail.Allowed fits lie on the green railObserved (3,2)Other tethers are longerShortest gap: perpendicularto the rail
Read it this way: The model can place its prediction only on the feasible rail. Dropping the observation straight onto that rail gives the shortest remaining gap. Moving along the rail makes that gap longer. Different coefficients may describe the same point, but cannot create a closer prediction off the rail. Can another coefficient representation change the same projected prediction?
Full explanation 6 min read
Reading depth

Summary

Ordinary least squares chooses linear predictions that minimize squared residuals. Its fitted vector is the orthogonal projection of observed responses onto the design matrix’s column space. This deterministic optimization problem does not require Gaussian noise; sampling assumptions justify additional statistical claims.

Ordinary least squares (OLS)

Put observations in rows of and include a ones column if fitting an intercept. With coefficient vector , minimize . Differentiating gives , so stationarity means .

For full column rank, the unique coefficient vector is

The fitted vector remains unique without full column rank, but coefficients need not be. An SVD pseudoinverse selects the minimum-Euclidean-norm coefficient solution.

Take and , with design rows . Then and . Solving gives intercept , slope , and predictions . Residuals sum to zero, as does their dot product with ; SSE is .

Reference drawing

Learning objective

The residual is perpendicular to the fitted column space

The residual is perpendicular to the fitted subspaceThe model can place its prediction only on the feasible rail. Dropping the observation straight onto that rail gives the shortest remaining gap. Moving along the rail makes that gap longer. Different coefficients may describe the same point, but cannot create a closer prediction off the rail.Allowed fits lie on the green railObserved (3,2)Other tethers are longerShortest gap: perpendicularto the rail
Derivation
Ordinary least squares as an orthogonal projection A slanted plane represents the column space of the design matrix X. From the origin, the fitted vector y-hat ends on that plane. The observed target vector y ends above it. A dashed residual vector connects y-hat to y and meets the plane at a marked right angle. This perpendicular residual satisfies X transpose r equals zero. Col(X) all possible fitted vectors Xw origin fitted y_hat = Xw_hat observed y residual r y - y_hat r is perpendicular to Col(X) X^T r = 0
Read it this way: fitted responses lie in Col(X), an observation-space subspace. The closest fit leaves a perpendicular residual, giving XTr = 0. The picture is not a feature-scatter plot or advice to form an inverse. Use QR or SVD numerically. Original schematic follows MIT's projection notes and the NIST least-squares handbook.
Check: Why is the residual orthogonal to X even when the coefficient vector is not unique?
Read it this way: The model can place its prediction only on the feasible rail. Dropping the observation straight onto that rail gives the shortest remaining gap. Moving along the rail makes that gap longer. Different coefficients may describe the same point, but cannot create a closer prediction off the rail. Can another coefficient representation change the same projected prediction?

The inverse expression identifies a solution; it is not the preferred numerical algorithm.

  • QR: for full column rank, solve triangular without forming an inverse.
  • SVD: handles rank deficiency with a declared numerical rank threshold.
  • Gradient methods: useful when factorization costs exceed the available resources; stopping accuracy remains part of the contract.

Probabilistic interpretation

Independent conditional Gaussian errors with a common variance make OLS a maximum-likelihood coefficient estimate. Other error models can change efficiency, robustness, or interval calculations without changing the definition of least squares.

Ridge and lasso

Regularization changes the objective rather than merely stabilizing an otherwise identical estimator.

MethodPenaltyEffect
Ridge (L2)Shrinks singular-direction coefficients; solve the modified linear system
Lasso (L1)Can produce exact zeros; use an appropriate convex solver
Elastic netBothCombines quadratic and absolute-value penalties

Penalize Only the Slope

New task: Add slope penalty with , leaving the intercept unpenalized.

Picture and change: Add to the fixture’s normal-equation matrix.

Check: Coefficients become ; the penalized slope no longer requires ordinary residual orthogonality.

Use when: A justified bias-variance trade-off favors shrinkage; coefficient sparsity alone does not establish causal importance.

Weight by Precision

New task: Give the middle observation one-quarter the noise variance of the others.

Picture and change: Set and solve .

Check: Coefficients become , satisfying rather than ordinary orthogonality.

Use when: Positive observation variances are known or defensibly estimated; the weighted inner product changes the projection.

Assumptions and diagnostics

Separate conditional mean specification, error covariance, and distributional assumptions. Residual plots against predictions/features can suggest misspecification or unequal variance; time plots can reveal dependence. QQ plots assess distributional shape but do not prove exogeneity or independence.

Gauss–Markov theorem

For full-column-rank fixed , require and with finite variance. Then OLS has minimum conditional covariance among linear unbiased coefficient estimators: BLUE. Normality is unnecessary for this theorem; it supports additional exact Gaussian-model inference. Biased estimators can have smaller mean squared error.

When to use vs. alternatives

  • Nonlinear mean: justify basis functions, kernels, trees, or neural networks against held-out objectives.
  • Heavy tails/outliers: compare robust losses; quantile regression targets a conditional quantile, not automatically the conditional mean.
  • Dependent observations: consider covariance-aware estimation or hierarchical models and suitable inference.
  • Variable selection: evaluate lasso or elastic net without treating selected features as automatically causal.

Common pitfalls

  • Unidentified coefficients. Duplicate columns permit offsetting coefficient changes without changing any fitted response.
  • Training-score claims. Evaluate generalization with a split matching the sampling and deployment process.
  • Interval confusion. Mean confidence intervals and individual prediction intervals target different quantities; the latter include observation noise.

Reconstruct

If the observed vector is already in Col(X), what does the projection prove?

The fit has zero residual and zero training SSE. This does not prove zero future error, correct sampling assumptions, or a causal coefficient interpretation.