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:

  1. Objective function: Formulate the mathematical quantity that OLS minimizes for a feature matrix X and target vector y, and explain why squared residuals are chosen.
  2. Matrix derivation: Work out the vector-calculus derivation of the normal equations and state when a unique closed-form weight vector exists.
  3. 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.
  4. 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 count p, 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

  1. 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 n training examples and p parameters. Stack the examples into an n × p design matrix X (a table with one row per example and one column per feature, including an initial column of 1s for the intercept b0) and collect the real-valued targets into a length-n vector y.
    • Sample-to-feature ratio: Ask whether n is much larger than p (classic regression) or whether p is close to or larger than n. When p > 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 length p, row i predicts ŷ_i = x_iᵀβ. The vertical prediction error on example i is 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_i fails because +10 and -10 cancel to 0 on 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 mean E[y | x], and matches maximum likelihood when noise is Gaussian—at the price that one outlier with residual 10 adds 100 to the loss.

  2. Derive the closed-form solution and its geometry

    To minimize ||y - Xβ||² without skipping any algebra, rewrite the squared Euclidean length of vector r = y - Xβ as the dot product rᵀr and 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 × 1 single 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 (like d/db (ab) = a) and ∇_β (βᵀCβ) = 2Cβ for any symmetric matrix C such as C = XᵀX (like d/db (cb²) = 2cb):

    ∇RSS(β) = 0 - 2Xᵀy + 2XᵀXβ  =  -2Xᵀ(y - Xβ)
    

    Setting ∇RSS(β̂) = 0 yields 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) is 2XᵀX. For any vector v, vᵀ(XᵀX)v = (Xv)ᵀ(Xv) = ||Xv||² ≥ 0, so RSS(β) curves upward everywhere (it is convex). When X has full column rank—meaning no feature column can be written as a weighted sum of the others, which requires n ≥ p—Xv = 0 only when v = 0, so XᵀX is strictly positive definite and invertible, making β̂ unique.

    Geometrically, Xᵀ(y - Xβ̂) = 0 says the optimal residual vector r = y - ŷ is perpendicular (orthogonal) to every column of X:

                  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 projects y onto the column space of X. When X includes a column of all 1s, 1ᵀr = 0 means the residuals are guaranteed to sum to zero.

  3. Work through a 3-point numeric example by hand

    Fit y ≈ b0 + b1·x to 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 are 7/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, giving R² = 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
    
  4. 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 model y = 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-tests
    

    Why does Gaussian noise lead directly to least squares? Under ε_i ~ Normal(0, σ²) independently, the log-likelihood of seeing y is:

    log L(β, σ²) = -(n / 2) log(2πσ²) - ||y - Xβ||² / (2σ²)
    

    For any positive σ², maximizing log L with respect to β is identical to minimizing ||y - Xβ||². To estimate σ² without bias after fitting p parameters, divide RSS by the remaining n - p degrees of freedom: σ̂² = RSS / (n - p). In our 3-point example (n = 3, p = 2), σ̂² = (1/6) / 1 = 1/6, so Var(b1) ≈ (1/6) · (3/6) = 1/12 and the slope's standard error is sqrt(1/12) ≈ 0.29.

  5. Numerical stability: never invert XᵀX in code

    Although β̂ = (XᵀX)⁻¹Xᵀy is great on a whiteboard, computing np.linalg.inv(X.T @ X) in production is a classic numerical bug:

    • Forming XᵀX squares 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. Multiplying XᵀX squares 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 with X keeps ~8 accurate digits, whereas XᵀX hits κ ≈ 10¹⁶ and loses virtually all accuracy.
    • QR decomposition (O(np²)): Factor X = QR, where Q (n × p) has orthonormal columns (QᵀQ = I) and R (p × p) is upper triangular. Then XᵀXβ̂ = Xᵀy simplifies to Rβ̂ = 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. When X is rank-deficient, SVD smoothly returns the unique minimum-norm least-squares solution (np.linalg.lstsq uses this).
    • Large-scale iterative solvers: When n and p are too huge to factor in RAM, conjugate gradient on the implicit operator (LSQR) or mini-batch gradient descent avoids forming XᵀX and costs O(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)
    
  6. Regularization: how ridge regression tames collinearity and variance

    When features are collinear or p approaches/exceeds n, 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ᵀy
    

    Adding λI changes four critical things:

    • Always invertible and better conditioned: Every eigenvalue of XᵀX + λI is σ_i² + λ ≥ λ > 0, even when p > n or two columns are identical. The condition number drops to (σ_max² + λ) / (σ_min² + λ).
    • Targeted shrinkage: Along SVD directions, OLS multiplies u_iᵀy by 1 / σ_i (huge when σ_i is tiny), while ridge multiplies by σ_i / (σ_i² + λ), shrinking unstable, low-variance feature directions the hardest.
    • Bias-variance trade-off & Bayesian view: For λ > 0, β̂_ridge introduces a small pull toward zero (bias) in exchange for a big drop in variance; tune λ via cross-validation. Equivalently, β̂_ridge is 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—center X and y, solve the augmented least-squares system [Xc; √λ I] w ≈ [yc; 0] via lstsq/QR, and recover b0 = 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 is w = 3 / (2 + λ) and b0 = 8/3 - w (giving w = 1.5, 1.0, 0.25 at λ = 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 exact 0 for feature selection.

  7. Apply these principles to diagnostics, validation, and serving

    • Before training: Inspect missing rates, extreme outliers, feature scales, and np.linalg.cond on standardized X. Huge condition numbers warn of duplicate or derived columns (total = price + tax).
    • Residual diagnostics: Plot r_i against ŷ_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 entries H_{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.

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 of y at a given x), OLS finds the best linear approximation to E[y | x].
  • Closed form & geometry: Setting the gradient -2Xᵀ(y - Xβ) to zero produces the normal equations XᵀXβ̂ = Xᵀy (the linear system where the residual vector is perpendicular to every feature column). When X has full column rank (no column is a linear combination of others, requiring n ≥ p), β̂ = (XᵀX)⁻¹Xᵀy is the unique global minimum and ŷ = Xβ̂ is the orthogonal projection of y onto the column space of X.
  • Layered statistical assumptions: Under y = Xβ + ε, full rank gives uniqueness; E[ε | X] = 0 gives unbiasedness (E[β̂ | X] = β, meaning the estimator hits the true β on average across repeated samples); homoscedastic (constant-variance) uncorrelated errors Var(ε | X) = σ²I make β̂ 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 exact t- and F-tests.
  • Numerical stability: A matrix's condition number κ(X) = σ_max / σ_min measures how strongly tiny rounding errors get amplified when solving a linear system. Explicitly forming XᵀX squares it (κ(XᵀX) = κ(X)²), which can wipe out floating-point precision on nearly redundant (collinear) features; solve directly on X using QR decomposition (factoring X into orthogonal Q times upper-triangular R) or singular value decomposition (SVD) via np.linalg.lstsq.
  • Ridge regularization: Adding an L2 penalty λ||β||² (λ > 0) shifts the system to (XᵀX + λI)β̂_ridge = Xᵀy, guaranteeing invertibility even when p > 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ᵀX explicitly (np.linalg.inv(X.T @ X) @ X.T @ y): Both slower and far less accurate than np.linalg.lstsq(X, y) or QR factorization because multiplying XᵀX squares the condition number.
  • Claiming OLS "requires features or labels to be normally distributed": Neither X nor y needs 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-sample p-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: Penalizing b0 pulls predictions toward 0 even when y is centered around 1,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 +1000 to one and -998 to the other with huge standard errors even though overall predictions look fine.
  • Judging model quality by training R²: Adding random noise columns never lowers training R²; always evaluate RMSE or R² 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 features X causes attenuation bias, systematically shrinking slopes toward zero by Var(x) / (Var(x) + Var(noise)). If OLS is used on skewed 0/1 binary 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 distribution p(x) drifts between training and live traffic), an approximate linear fit optimizes accuracy on the old region unless you reweight training samples by p_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 ȳ_train for every example: its MSE equals the sample variance of y and defines R² = 0 (on our 3-point example, MSE = 14/9 ≈ 1.56 vs 1/18 ≈ 0.056 for 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

Similar questions

More Sunrise interview questions

All 1 Sunrise questions →