Classical ML

Linear Regression

Simple on paper, brutal in interviews. Most candidates fail when asked to derive OLS or explain heteroscedasticity.

🟢 beginner4 min readsupervisedmust-know
Linear Regression models continuous targets as y = Xβ + ε. Ordinary Least Squares (OLS) minimizes squared residuals, yielding the closed-form solution β = (XᵀX)⁻¹Xᵀy. Under the Gauss-Markov assumptions, OLS is the Best Linear Unbiased Estimator (BLUE). Key interview topics include closed-form derivation, assumption validation, multicollinearity, and OLS vs Gradient Descent trade-offs.

Closed-form solution (OLS)

Linear regression assumes y = Xβ + ε, where y ∈ ℝᴺ, X ∈ ℝᴺˣᵈ, β ∈ ℝᵈ, and residual errors ε ~ N(0, σ²I).

To find optimal β, minimize Sum of Squared Errors (SSE):

L(β) = ||y - Xβ||² = (y - Xβ)ᵀ(y - Xβ) = yᵀy - 2βᵀXᵀy + βᵀXᵀXβ

Taking derivative wrt β and setting to 0:

∇_β L(β) = -2Xᵀy + 2XᵀXβ = 0  ⇒  (XᵀX)β = Xᵀy  ⇒  β = (XᵀX)⁻¹Xᵀy

This normal equation gives the exact global minimum because SSE is strictly convex.

The 5 Gauss-Markov assumptions

For OLS to be BLUE (Best Linear Unbiased Estimator):

  1. Linearity: Relationship between X and mean of y is linear in parameters.
  2. Strict Exogeneity: E[ε | X] = 0 (residuals have zero mean, independent of X).
  3. No Multicollinearity: XᵀX is full rank (invertible).
  4. Homoscedasticity: Constant error variance Var(ε_i | X) = σ².
  5. No Autocorrelation: Residual errors are uncorrelated across observations Cov(ε_i, ε_j) = 0.

If residuals have non-constant variance (heteroscedasticity), OLS estimates remain unbiased but standard errors are wrong and confidence intervals fail. Use Robust Standard Errors (White's HC) or Weighted Least Squares (WLS).

OLS vs Gradient Descent

FactorClosed-Form OLSGradient Descent
Equationβ = (XᵀX)⁻¹Xᵀyβ := β - α ∇L(β)
Time ComplexityO(d³ + Nd²)O(k · Nd) for k iterations
MemoryNeeds XᵀX in memory (O(d²))Mini-batch (O(B · d))
HyperparametersNoneLearning rate α, batch size, iterations
Scaling RequiredNoYes (critical for convergence)
Large Features (d > 100k)Fails (inversion slow/impossible)Scales easily (SGD / Adam)

Say this out loud

"Linear regression minimizes sum of squared residuals. The closed-form OLS solution is β = (XᵀX)⁻¹Xᵀy, which is BLUE under Gauss-Markov assumptions. For small to medium feature counts, OLS is instant and non-parametric. But when feature count d is very large, d³ matrix inversion becomes prohibitive, so we switch to Mini-Batch Gradient Descent with feature scaling."

Follow-ups to expect

Check yourself

Question 1 of 3

What is the computational complexity of solving OLS via the normal equation β = (XᵀX)⁻¹Xᵀy for N samples and d features?

More in Classical ML

See all →
Bias–Variance Tradeoff4 minOverfitting vs Underfitting3 minLogistic Regression4 min