Ordinary Least Squares Regression Fundamentals
Easy · Machine Learning · Software Engineer · Onsite
Prompt
Walk an interviewer through ordinary least squares (OLS) for linear regression from first principles to production implementation:
- Objective function: Formulate the mathematical quantity that OLS minimizes for a feature matrix
Xand target vectory, and explain why squared residuals are chosen. - Matrix derivation: Work out the vector-calculus derivation of the normal equations and state when a unique closed-form weight vector exists.
- Modeling assumptions: Distinguish the purely algebraic conditions needed to compute a solution from the statistical assumptions (on linearity, error distribution, variance, and independence) required for unbiasedness, minimum variance, and hypothesis testing.
- Conditioning and L2 penalties: Explain why naive matrix inversion breaks down numerically on collinear data, which matrix factorizations fix it, and how adding a ridge (
L2) penalty alters both the estimator and preprocessing pipeline.
Scope & Expectations
- Pin down the problem setup first: Confirm sample count
n, feature countp, intercept handling, and whether squared-error metrics match the downstream goal. - Layer assumptions cleanly: State explicitly what each assumption buys you rather than bundling normality, full rank, and constant noise variance into one vague requirement.
- Bridge math to engineering: Connect condition numbers, feature scaling, residual checks, and out-of-distribution inputs to real training and serving decisions.
Step-by-step walkthrough
Clarify the setup and state the optimization problem
Before writing equations in an interview, pin down the data shape and goal so every notation choice is concrete:
- Inputs and labels: We have
ntraining examples andpparameters. Stack the examples into ann × pdesign matrixX(a table with one row per example and one column per feature, including an initial column of1s for the interceptb0) and collect the real-valued targets into a length-nvectory. - Sample-to-feature ratio: Ask whether
nis much larger thanp(classic regression) or whetherpis close to or larger thann. Whenp > n, infinitely many parameter vectors fit the training points equally well, so plain ordinary least squares (OLS) has no unique solution without regularization. - Evaluation metric: OLS minimizes squared error, which naturally aligns with root mean squared error (RMSE) or R² on held-out data. If the business cares about median performance or has heavy outliers, flag early that absolute error (MAE) or Huber loss may be a better fit.
For any candidate weight vector
βof lengthp, rowipredictsŷ_i = x_iᵀβ. The vertical prediction error on exampleiis called its residual,r_i = y_i - x_iᵀβ. Ordinary least squares choosesβto minimize the residual sum of squares (RSS):RSS(β) = Σ_{i=1..n} (y_i - x_iᵀβ)² = ||y - Xβ||²Why square the residuals? Simply adding raw residuals
Σ r_ifails because+10and-10cancel to0on a terrible fit. Taking absolute valuesΣ |r_i|avoids cancellation, but the absolute-value V-shape has sharp corners with no single closed-form formula. Squaring makes the objective smooth and bowl-shaped (convex), estimates the conditional meanE[y | x], and matches maximum likelihood when noise is Gaussian—at the price that one outlier with residual10adds100to the loss.- Inputs and labels: We have
Derive the closed-form solution and its geometry
To minimize
||y - Xβ||²without skipping any algebra, rewrite the squared Euclidean length of vectorr = y - Xβas the dot productrᵀrand expand the four terms:RSS(β) = (y - Xβ)ᵀ (y - Xβ) = yᵀy - yᵀXβ - βᵀXᵀy + βᵀXᵀXβNotice that
yᵀXβis a(1 × n)(n × p)(p × 1) = 1 × 1single number (a scalar). Because the transpose of any single number equals itself,(yᵀXβ)ᵀ = βᵀXᵀy, so the two middle terms are identical and combine cleanly:RSS(β) = yᵀy - 2βᵀ(Xᵀy) + βᵀ(XᵀX)βNow take the gradient (the vector of partial derivatives with respect to each entry of
β) using two standard multivariable derivative rules that mirror single-variable calculus:∇_β (aᵀβ) = a(liked/db (ab) = a) and∇_β (βᵀCβ) = 2Cβfor any symmetric matrixCsuch asC = XᵀX(liked/db (cb²) = 2cb):∇RSS(β) = 0 - 2Xᵀy + 2XᵀXβ = -2Xᵀ(y - Xβ)Setting
∇RSS(β̂) = 0yields the normal equations:XᵀX β̂ = Xᵀy β̂ = (XᵀX)⁻¹ Xᵀy (whenever XᵀX is invertible)Why is
β̂guaranteed to be a global minimum rather than a saddle point or maximum? The second-derivative matrix (the Hessian) is2XᵀX. For any vectorv,vᵀ(XᵀX)v = (Xv)ᵀ(Xv) = ||Xv||² ≥ 0, soRSS(β)curves upward everywhere (it is convex). WhenXhas full column rank—meaning no feature column can be written as a weighted sum of the others, which requiresn ≥ p—Xv = 0only whenv = 0, soXᵀXis strictly positive definite and invertible, makingβ̂unique.Geometrically,
Xᵀ(y - Xβ̂) = 0says the optimal residual vectorr = y - ŷis perpendicular (orthogonal) to every column ofX:y (actual target vector in R^n) /| / | r = y - Xβ̂ (residual drops straight down at 90°, so Xᵀr = 0) / | / _v_ -------+--|_|----------> Column space of X: all possible predictions Xβ ŷ = Xβ̂ = H y (closest point in Col(X) to y)Here
H = X(XᵀX)⁻¹Xᵀis the hat matrix (symmetric and idempotent,H² = H), which projectsyonto the column space ofX. WhenXincludes a column of all1s,1ᵀr = 0means the residuals are guaranteed to sum to zero.Work through a 3-point numeric example by hand
Fit
y ≈ b0 + b1·xto three points(0, 1), (1, 3), (2, 4):X = [[1, 0], y = [1, 3, 4] [1, 1], [1, 2]] XᵀX = [[1+1+1, 0+1+2], = [[3, 3], Xᵀy = [1+3+4, = [ 8, [0+1+2, 0+1+4]] [3, 5]] 0·1+1·3+2·4] 11] det(XᵀX) = (3)(5) - (3)(3) = 6 (XᵀX)⁻¹ = (1/6) · [[ 5, -3], [-3, 3]] β̂ = (1/6) · [5·8 + (-3)·11, (-3)·8 + 3·11] = (1/6) · [7, 9] = [7/6, 3/2] ≈ [1.1667, 1.5]So the fitted line is
ŷ = 7/6 + 1.5x. Checking all three points:- At
x = 0, 1, 2, predictions are7/6, 8/3, 25/6(1.1667, 2.6667, 4.1667) and residuals are-1/6, +2/6, -1/6. - Orthogonality holds: residuals sum to
-1/6 + 2/6 - 1/6 = 0, andΣ x_i·r_i = 0(-1/6) + 1(2/6) + 2(-1/6) = 0. RSS = (-1/6)² + (2/6)² + (-1/6)² = 6/36 = 1/6. Around the meanȳ = 8/3, total sum of squares is(-5/3)² + (1/3)² + (4/3)² = 14/3, givingR² = 1 - (1/6)/(14/3) = 27/28 ≈ 0.964.
import numpy as np X = np.array([[1.0, 0.0], [1.0, 1.0], [1.0, 2.0]]) # column of 1s for intercept, plus x y = np.array([1.0, 3.0, 4.0]) beta_solve = np.linalg.solve(X.T @ X, X.T @ y) # solves normal equations on this tiny example beta_lstsq, *_ = np.linalg.lstsq(X, y, rcond=None) # SVD-based solver: safe production default print(beta_solve, beta_lstsq) # both [1.16666667, 1.5] residual = y - X @ beta_lstsq print(X.T @ residual) # ~[0.0, 0.0]: residual is perpendicular to X- At
Separate the algebraic assumptions from the statistical ones
Computing
β̂as a geometric best fit only needs linearly independent columns. Claiming statistical properties about a true data-generating modely = Xβ + εadds assumptions one layer at a time:Assumption What it unlocks -------------------------------------------- ----------------------------------------------------- 1. Linear in parameters: y = Xβ + ε Model can represent the true signal without bias 2. Full column rank: rank(X) = p (n >= p) XᵀX is invertible, so β̂ is unique 3. Zero conditional mean: E[ε | X] = 0 β̂ is unbiased: E[β̂ | X] = β (no omitted confounders) 4. Spherical noise: Var(ε | X) = σ² I Gauss-Markov theorem: β̂ is BLUE (lowest variance (constant variance + uncorrelated errors) among all linear unbiased estimators); Var(β̂ | X) = σ² (XᵀX)⁻¹ 5. Gaussian noise: ε | X ~ Normal(0, σ² I) β̂ equals the maximum-likelihood estimator (MLE) and gives exact finite-sample t-tests and F-testsWhy does Gaussian noise lead directly to least squares? Under
ε_i ~ Normal(0, σ²)independently, the log-likelihood of seeingyis:log L(β, σ²) = -(n / 2) log(2πσ²) - ||y - Xβ||² / (2σ²)For any positive
σ², maximizinglog Lwith respect toβis identical to minimizing||y - Xβ||². To estimateσ²without bias after fittingpparameters, divideRSSby the remainingn - pdegrees of freedom:σ̂² = RSS / (n - p). In our 3-point example (n = 3, p = 2),σ̂² = (1/6) / 1 = 1/6, soVar(b1) ≈ (1/6) · (3/6) = 1/12and the slope's standard error issqrt(1/12) ≈ 0.29.Numerical stability: never invert XᵀX in code
Although
β̂ = (XᵀX)⁻¹Xᵀyis great on a whiteboard, computingnp.linalg.inv(X.T @ X)in production is a classic numerical bug:- Forming
XᵀXsquares the condition number. A matrix's condition numberκ(X) = σ_max / σ_min(largest singular value divided by smallest) measures how close its columns are to collinearity and how strongly rounding errors get amplified. MultiplyingXᵀXsquares every singular value, soκ(XᵀX) = κ(X)². Standard 64-bit floats hold roughly 16 decimal digits (ε_mach ≈ 2.2e-16). If nearly redundant features giveκ(X) = 10⁸, working directly withXkeeps ~8 accurate digits, whereasXᵀXhitsκ ≈ 10¹⁶and loses virtually all accuracy. - QR decomposition (
O(np²)): FactorX = QR, whereQ(n × p) has orthonormal columns (QᵀQ = I) andR(p × p) is upper triangular. ThenXᵀXβ̂ = Xᵀysimplifies toRβ̂ = Qᵀy, solved cleanly by back-substitution with condition numberκ(X)instead ofκ(X)². - Singular Value Decomposition (
X = UΣVᵀ): Computesβ̂ = V Σ⁺ Uᵀ y, whereΣ⁺inverts non-zero singular values (1 / σ_i) and zeros out tiny ones. WhenXis rank-deficient, SVD smoothly returns the unique minimum-norm least-squares solution (np.linalg.lstsquses this). - Large-scale iterative solvers: When
nandpare too huge to factor in RAM, conjugate gradient on the implicit operator (LSQR) or mini-batch gradient descent avoids formingXᵀXand costsO(np)per pass.
import numpy as np x = np.linspace(0.0, 1.0, 50) A = np.vander(x, 12, increasing=True) # columns 1, x, ..., x^11 are nearly collinear on [0, 1] true_beta = np.ones(12) y = A @ true_beta # noiseless target: any error is pure float rounding print(np.linalg.cond(A), np.linalg.cond(A.T @ A)) # ~1e8 vs ~1e16 beta_normal = np.linalg.solve(A.T @ A, A.T @ y) beta_lstsq, *_ = np.linalg.lstsq(A, y, rcond=None) print(np.max(np.abs(beta_normal - true_beta))) # ~6e-2 (most digits lost) print(np.max(np.abs(beta_lstsq - true_beta))) # ~2e-9 (seven orders of magnitude cleaner)- Forming
Regularization: how ridge regression tames collinearity and variance
When features are collinear or
papproaches/exceedsn, OLS weights explode with opposite signs to chase training noise. Ridge regression adds an L2 penalty proportional to the squared length ofβ(controlled by hyperparameterλ > 0):minimize ||y - Xβ||² + λ ||β||² gradient: -2Xᵀ(y - Xβ) + 2λβ = 0 solution: (XᵀX + λI) β̂_ridge = Xᵀy => β̂_ridge = (XᵀX + λI)⁻¹ XᵀyAdding
λIchanges four critical things:- Always invertible and better conditioned: Every eigenvalue of
XᵀX + λIisσ_i² + λ ≥ λ > 0, even whenp > nor two columns are identical. The condition number drops to(σ_max² + λ) / (σ_min² + λ). - Targeted shrinkage: Along SVD directions, OLS multiplies
u_iᵀyby1 / σ_i(huge whenσ_iis tiny), while ridge multiplies byσ_i / (σ_i² + λ), shrinking unstable, low-variance feature directions the hardest. - Bias-variance trade-off & Bayesian view: For
λ > 0,β̂_ridgeintroduces a small pull toward zero (bias) in exchange for a big drop in variance; tuneλvia cross-validation. Equivalently,β̂_ridgeis the Bayesian maximum a posteriori (MAP) estimate under a Gaussian priorβ ~ Normal(0, τ²I)withλ = σ² / τ². - Implementation rules: Always standardize features (zero mean, unit variance) first so
λdoes not penalize a feature differently in millimetres vs metres, and never penalize the intercept—centerXandy, solve the augmented least-squares system[Xc; √λ I] w ≈ [yc; 0]vialstsq/QR, and recoverb0 = mean(y) - mean(X) @ w.
On our 3-point example (
x_c = [-1, 0, 1],y_c = [-5/3, 1/3, 4/3],Σ x_c² = 2,Σ x_c·y_c = 3), the centered ridge slope isw = 3 / (2 + λ)andb0 = 8/3 - w(givingw = 1.5, 1.0, 0.25atλ = 0, 1, 10):import numpy as np def fit_ridge_centered(X, y, lam): """Fit ridge regression without penalizing the intercept via augmented lstsq.""" x_mean = X.mean(axis=0) y_mean = y.mean() Xc = X - x_mean yc = y - y_mean p = X.shape[1] # Solving ||[Xc; sqrt(lam)*I] w - [yc; 0]||^2 equals ||yc - Xc w||^2 + lam ||w||^2 A = np.vstack([Xc, np.sqrt(lam) * np.eye(p)]) b = np.concatenate([yc, np.zeros(p)]) w, *_ = np.linalg.lstsq(A, b, rcond=None) intercept = float(y_mean - x_mean @ w) return intercept, w # With multi-unit features, divide Xc by X.std(axis=0) before fitting and rescale w afterward. print(fit_ridge_centered(np.array([[0.0], [1.0], [2.0]]), np.array([1.0, 3.0, 4.0]), 1.0))By contrast, Lasso (
λ ||β||₁) uses an L1 penalty that has sharp corners at zero; it lacks a general closed form (solved via coordinate descent), but drives unimportant weights to exact0for feature selection.- Always invertible and better conditioned: Every eigenvalue of
Apply these principles to diagnostics, validation, and serving
- Before training: Inspect missing rates, extreme outliers, feature scales, and
np.linalg.condon standardizedX. Huge condition numbers warn of duplicate or derived columns (total = price + tax). - Residual diagnostics: Plot
r_iagainstŷ_i. A curved U-shape signals missing nonlinear features; a megaphone/funnel shape signals heteroscedasticity (non-constant noise variance, addressed with weighted least squares or Huber-White standard errors); points with large diagonal entriesH_{ii}have high leverage and can pull the line single-handedly. - Validation: Compare train and validation RMSE rather than training
R²(which never drops when you add junk columns), and pickλinside a cross-validation pipeline that computes means and standard deviations on each training fold only. - Deployment: Bundle the exact training feature means and standard deviations alongside
(b0, w)so serving preprocessing cannot drift, and alert on out-of-range feature values because linear models extrapolate toward±∞without bound.
- Before training: Inspect missing rates, extreme outliers, feature scales, and
Intuition & how it works
Imagine hammering a few pins onto a wooden board to represent noisy (x, y) data points and holding a stiff straight ruler across them, attaching a vertical rubber band from each pin straight up or down to the ruler. Because the potential energy of a stretched rubber band grows with the square of how far it is stretched, a single pin 4 cm away pulls 16 times harder than a pin 1 cm away, and the ruler naturally settles at the exact tilt and height where the total squared stretch across all pins is as small as possible. That resting line is ordinary least squares (OLS).
Simpler shortcuts break down quickly. Drawing a line through just two points ignores the rest of the dataset and chases random noise, while minimizing raw signed errors Σ (y_i - ŷ_i) lets a +10 error and a -10 error cancel to 0 on a completely wrong line. Minimizing absolute errors Σ |y_i - ŷ_i| avoids cancellation, but its V-shaped kinks prevent a single closed-form formula and can leave multiple tied lines. Squaring each error gives a smooth, bowl-shaped objective whose minimum can be solved directly with linear algebra.
Concretely, on the three points (0, 1), (1, 3), (2, 4) with model ŷ = b0 + b1·x, building the design matrix X = [[1, 0], [1, 1], [1, 2]] (a table with a column of 1s for the intercept b0 and a column for x) gives XᵀX = [[3, 3], [3, 5]] and Xᵀy = [8, 11]. Solving (XᵀX)β̂ = Xᵀy yields b0 = 7/6 ≈ 1.17 and b1 = 1.5: the predicted values are 7/6, 8/3, 25/6, the vertical errors (residuals, r_i = y_i - ŷ_i) are -1/6, +2/6, -1/6 (which sum to 0), and the minimized sum of squared residuals is (-1/6)² + (2/6)² + (-1/6)² = 1/6.
Key points
- Optimization objective: OLS chooses weights
βto minimize||y - Xβ||² = Σ (y_i - x_iᵀβ)². Because squared loss is minimized by the conditional expectation (the average value ofyat a givenx), OLS finds the best linear approximation toE[y | x]. - Closed form & geometry: Setting the gradient
-2Xᵀ(y - Xβ)to zero produces the normal equationsXᵀXβ̂ = Xᵀy(the linear system where the residual vector is perpendicular to every feature column). WhenXhas full column rank (no column is a linear combination of others, requiringn ≥ p),β̂ = (XᵀX)⁻¹Xᵀyis the unique global minimum andŷ = Xβ̂is the orthogonal projection ofyonto the column space ofX. - Layered statistical assumptions: Under
y = Xβ + ε, full rank gives uniqueness;E[ε | X] = 0gives unbiasedness (E[β̂ | X] = β, meaning the estimator hits the trueβon average across repeated samples); homoscedastic (constant-variance) uncorrelated errorsVar(ε | X) = σ²Imakeβ̂BLUE (Best Linear Unbiased Estimator—lowest variance among all linear unbiased estimators, by the Gauss-Markov theorem); and Gaussian errors makeβ̂the maximum-likelihood estimator (MLE) (the parameter choice under which the observed data is most probable) with exactt- andF-tests. - Numerical stability: A matrix's condition number
κ(X) = σ_max / σ_minmeasures how strongly tiny rounding errors get amplified when solving a linear system. Explicitly formingXᵀXsquares it (κ(XᵀX) = κ(X)²), which can wipe out floating-point precision on nearly redundant (collinear) features; solve directly onXusing QR decomposition (factoringXinto orthogonalQtimes upper-triangularR) or singular value decomposition (SVD) vianp.linalg.lstsq. - Ridge regularization: Adding an L2 penalty
λ||β||²(λ > 0) shifts the system to(XᵀX + λI)β̂_ridge = Xᵀy, guaranteeing invertibility even whenp > n, shrinking noisy directions with small singular values, and matching the Bayesian MAP (maximum a posteriori) estimate (the mode of the posterior distribution under a zero-mean Gaussian prior onβ). Always standardize features first and leave the intercept unpenalized.
Common mistakes
- Inverting
XᵀXexplicitly (np.linalg.inv(X.T @ X) @ X.T @ y): Both slower and far less accurate thannp.linalg.lstsq(X, y)or QR factorization because multiplyingXᵀXsquares the condition number. - Claiming OLS "requires features or labels to be normally distributed": Neither
Xnoryneeds to be bell-shaped, and OLS doesn't even need normal noise to be unbiased or BLUE; normality of the errorsεonly matters for exact small-samplep-values and confidence intervals. - Omitting the column of ones, which forces the regression hyperplane through
(0, 0)and breaks the zero-sum residual property. - Applying ridge without standardizing features or while penalizing
b0: Penalizingb0pulls predictions toward0even whenyis centered around1,000, and unscaled features makeλdepend arbitrarily on measurement units (kilometres vs millimetres). - Over-interpreting individual weights under collinearity: When two features move together, OLS can assign
+1000to one and-998to the other with huge standard errors even though overall predictions look fine. - Judging model quality by training
R²: Adding random noise columns never lowers trainingR²; always evaluate RMSE orR²on held-out validation data.
Follow-up questions
- How does your approach change when targets contain heavy outliers, binary outcomes are heavily skewed, or live inputs drift from the training distribution? Independent zero-mean label noise keeps
β̂unbiased while inflating its variance (σ²rises), whereas heavy-tailed label outliers distort squared loss badly (switch to Huber loss, which acts quadratic near zero and linear on large errors) and input-dependent noise variance calls for weighted least squares (1 / σ_i²weights). By contrast, random measurement noise inside the featuresXcauses attenuation bias, systematically shrinking slopes toward zero byVar(x) / (Var(x) + Var(noise)). If OLS is used on skewed0/1binary outcomes, predictions can fall outside[0, 1]and hug the rare base rate (use logistic regression or class-weighted cross-entropy), and under covariate shift (where the input distributionp(x)drifts between training and live traffic), an approximate linear fit optimizes accuracy on the old region unless you reweight training samples byp_live(x) / p_train(x)or retrain. - Once a linear regression model is serving live traffic, which input, prediction, and residual signals should you track? Before ground-truth labels arrive, track input feature drift (means, standard deviations, missing-value rates, and the fraction of requests outside training min/max bounds where linear models extrapolate wildly) alongside the distribution of predicted
ŷvalues. Once delayed labels arrive, monitor rolling RMSE, MAE, and mean signed residual (mean(y - ŷ)) overall and across key user slices to catch calibration bias early. Across scheduled retrains, log weight shifts andκ(X)so sudden pipeline bugs or newly collinear columns trigger alerts before going live. - What simple benchmark models would you evaluate before adopting or expanding a regression pipeline? Start with the constant-mean baseline that predicts
ȳ_trainfor every example: its MSE equals the sample variance ofyand definesR² = 0(on our 3-point example,MSE = 14/9 ≈ 1.56vs1/18 ≈ 0.056for the fitted line). Next compare against single-feature or domain-heuristic OLS, then standardized ridge regression with cross-validatedλbefore reaching for gradient-boosted trees or neural networks. For sequential or time-series targets, also compare against predicting the most recent observed value (ŷ_t = y_{t-1}), which often beats naive regression when targets drift slowly.
Follow-up questions
- How does your approach change when targets contain heavy outliers, binary outcomes are heavily skewed, or live inputs drift from the training distribution?
- Once a linear regression model is serving live traffic, which input, prediction, and residual signals should you track?
- What simple benchmark models would you evaluate before adopting or expanding a regression pipeline?
Similar questions
- Low-Latency Tree Ensemble Inference
- Select Score Cutoff for Target Precision
- Payment Fraud Detection Under Class Imbalance and Drift
- Diagnosing and Fixing Overfitting in Supervised Learning
- Correlation Bounds, Equicorrelated Variables, and Box-Muller Sampling
- Feed Click-Through Rate Feature Engineering and Modeling