Technopedia

The technologist’s encyclopedia

Regression

Regression fits a parametric function fθ(x)f_\theta(x) to observed data (xi,yi)(x_i, y_i) by minimizing a loss (typically mean squared error). It is the simplest optimization problem: the objective is a sum of squared residuals, and the parameters are the coefficients of the model. It is relevant whenever a continuous quantity must be predicted from features, or a parametric model must be calibrated to measurements.

Authoritative sources

Linear regression

Definition: Given design matrix X∈Rn×dX \in \mathbb{R}^{n \times d} and target vector y∈Rny \in \mathbb{R}^n, the least-squares estimator minimizes ∥Xθ−y∥2\|X\theta - y\|^2 and has the closed-form solution:

θ∗=(XTX)−1XTy\theta^* = (X^T X)^{-1} X^T y

This is the normal equation. It requires O(nd2)O(nd^2) to form XTXX^T X and O(d3)O(d^3) to invert (or O(nd2)O(nd^2) via QR decomposition) and is exact: no iteration needed.

Details

Derivation: the objective is L(θ)=(Xθ−y)T(Xθ−y)\mathcal{L}(\theta) = (X\theta - y)^T(X\theta - y). Taking the gradient and setting it to zero:

∇θL=2XT(Xθ−y)=0  ⟹  XTX θ=XTy\nabla_\theta \mathcal{L} = 2X^T(X\theta - y) = 0 \implies X^T X \, \theta = X^T y

If XTXX^T X is invertible (i.e., XX has full column rank dd), the solution is unique.

When to use the closed form: for small dd (say d<104d < 10^4), the normal equation or QR decomposition is faster than any iterative method. For large dd (deep learning: d>106d > 10^6), the O(d3)O(d^3) cost is infeasible, and the loss must be minimized iteratively with gradient descent, which defines the epoch, the learning rate, and the convergence rate.

What the fit looks like: the figure below shows 15 samples of y=2+1.5x+noisey = 2 + 1.5x + \text{noise} with the least-squares line y^=0.90+1.66x\hat{y} = 0.90 + 1.66x and the residuals (the vertical segments between each point and the line). The normal equation is the unique line that makes the sum of the squared residual lengths minimal.

024681005101520f̂(x) = 0.90 + 1.66x

Try it yourself: drag the line through the points and watch the MSE change; the dashed line is the least-squares optimum.

Example problem:

Problem

You have n=1000n = 1000 samples with d=3d = 3 features. The design matrix XX is full rank. Compare the cost of solving linear regression via the normal equation vs. 100 steps of gradient descent with η=0.01\eta = 0.01.

Solution
  • Normal equation: O(nd2+d3)=1000×9+27≈9,027O(nd^2 + d^3) = 1000 \times 9 + 27 \approx 9{,}027 FLOPs. One shot.
  • Gradient descent (100 steps): each step computes ∇L=2XT(Xθ−y)\nabla \mathcal{L} = 2X^T(X\theta - y) at cost O(nd)=3,000O(nd) = 3{,}000 FLOPs. Total: 100×3,000=300,000100 \times 3{,}000 = 300{,}000 FLOPs.

For small dd and moderate nn, the closed form wins. For d=106d = 10^6 (deep learning), the normal equation is infeasible (d3=1018d^3 = 10^{18}), and iterative methods are the only option.

When d>nd > n the normal equation has infinitely many solutions; when dd is large the closed form is infeasible; in both cases the model can memorize noise, which is the overfitting problem.

Overfitting and the hat matrix

Definition: the fitted values of least squares are y^=Hy\hat{y} = H y where H=XX+H = X X^+ is the hat matrix (X+X^+ is the Moore–Penrose pseudoinverse; when XX has full column rank, H=X(XTX)−1XTH = X(X^T X)^{-1} X^T). HH is symmetric and idempotent (H2=HH^2 = H), so its trace tr(H)=rank(X)=min⁡(n,d)\text{tr}(H) = \text{rank}(X) = \min(n, d) is the effective number of parameters of the fit. When d≥nd \geq n the model can interpolate the training data exactly (zero training loss) — it has enough degrees of freedom to fit the noise.

Details

Why tr(H) counts parameters: HH is the orthogonal projection onto the column space of XX. An idempotent matrix has only eigenvalues 00 and 11, so tr(H)\text{tr}(H) — the sum of the eigenvalues — counts the 11s, i.e. the dimension of the column space. Each of those dimensions can absorb one independent direction of noise: the more of them, the more noise the fit can memorize.

Bias-variance tradeoff: the expected prediction error decomposes as:

E[(fθ(x)−y)2]=(E[fθ(x)]−f∗(x))2⏟bias2+Var[fθ(x)]⏟variance+σ2⏟irreducible noise\mathbb{E}[(f_\theta(x) - y)^2] = \underbrace{(\mathbb{E}[f_\theta(x)] - f^*(x))^2}_{\text{bias}^2} + \underbrace{\text{Var}[f_\theta(x)]}_{\text{variance}} + \underbrace{\sigma^2}_{\text{irreducible noise}}

The learning curve: the standard diagnostic is to plot the training and validation loss against training progress. The figure below shows the typical shape: the training loss keeps falling (the model keeps memorizing), while the validation loss bottoms out and then rises — the point where the two diverge is where the model starts fitting noise.

0204060801001200.00.20.40.60.81.0training iterationsMSEbest generalization (stop here)overfittingtraining MSEvalidation MSE

The train/validation split and these diagnostics are general machine-learning concepts; see Learning Paradigms and Models for their treatment in the context of neural networks.

Example problem:

Problem

A linear model with d=500d = 500 features is fit to n=100n = 100 samples whose rows are linearly independent. (a) What are rank(X)\text{rank}(X) and tr(H)\text{tr}(H)? (b) Can the model achieve zero training loss? (c) Give two remedies for the resulting poor generalization.

Solution

(a) rank(X)=min⁡(n,d)=100\text{rank}(X) = \min(n, d) = 100 (the rows are independent), and tr(H)=rank(X)=100\text{tr}(H) = \text{rank}(X) = 100: the fit has 100 effective parameters.

(b) Yes. Since d=500≥n=100d = 500 \geq n = 100, the system Xθ=yX\theta = y has a solution (infinitely many), so the model interpolates the training data exactly — zero training loss is guaranteed, and says nothing about generalization.

(c) 1. Regularization: ridge regression replaces XTXX^T X with XTX+λIX^T X + \lambda I, which is always invertible and shrinks the coefficients (see Regularization). 2. More data: collect additional samples so that n>dn > d, making the problem well-posed.

Regularization

Definition: regularization adds a penalty on θ\theta to the loss, trading bias for variance and reducing the effective number of parameters:

Details

Ridge: with orthonormal features, each coefficient shrinks smoothly: βj(λ)=βjOLS/(1+λ/σj2)\beta_j(\lambda) = \beta_j^{OLS} / (1 + \lambda / \sigma_j^2). The effective number of parameters becomes tr(Hλ)=∑jσj2/(σj2+λ)<d\text{tr}(H_\lambda) = \sum_j \sigma_j^2 / (\sigma_j^2 + \lambda) < d — regularization literally reduces the degrees of freedom the model can use to fit noise. Ridge is the same L2 penalty used as weight decay in neural network training.

Lasso: with orthonormal features, each coefficient is soft-thresholded: βj(λ)=sign(βjOLS)max⁡(∣βjOLS∣−λ,0)\beta_j(\lambda) = \text{sign}(\beta_j^{OLS}) \max(|\beta_j^{OLS}| - \lambda, 0). Coefficients smaller than the threshold become exactly zero — the lasso performs feature selection, keeping at most min⁡(n,d)\min(n, d) features. With correlated features it tends to pick one from each group; the elastic net fixes this by adding the ridge term, which keeps correlated groups together.

Coefficient paths: the figure below shows the four coefficients of a fit as λ\lambda grows from 0 (plain least squares) to 2.5. Ridge shrinks everything smoothly toward zero; the lasso drives the small coefficients exactly to zero at λ=∣βjOLS∣\lambda = |\beta_j^{OLS}|.

Ridge (L2)βₚ(λ) = βₚ / (1 + λ)0.00.51.01.52.02.50.00.61.11.72.2λβ₁ = 2.0β₂ = 1.2β₃ = 0.6β₄ = 0.3Lasso (L1)βₚ(λ) = sign(βₚ) · max(|βₚ| − λ, 0)0.00.51.01.52.02.50.00.61.11.72.2λβ₁ = 2.0β₂ = 1.2β₃ = 0.6β₄ = 0.3

Choosing λ: the penalty strength λ\lambda is a hyperparameter, chosen by validation loss or cross-validation (next section).

Example problem:

Problem

A model has 500 features. The true signal depends on only 12 of them; the remaining 488 are pure noise. The unregularized least-squares fit shows 12 large coefficients and about 488 small nonzero ones. Which regularizer — ridge or lasso — better matches this structure, and why?

Solution

Lasso. Its soft-thresholding drives the 488 noise coefficients exactly to zero, recovering the sparse 12-feature model. Ridge would shrink them toward zero but never to zero, leaving all 500 features active and retaining capacity to fit noise.

Model selection and goodness of fit

Definition:

Details

Why R² lies: R2R^2 is computed on the training data. When d≥nd \geq n, interpolation gives SSres=0\text{SS}_{res} = 0 and R2=1R^2 = 1 no matter how much of the fit is noise — a training R2R^2 of 1 is a red flag, not an achievement. Adjusted R2R^2 corrects for pp: it can be negative (the model is worse than predicting the mean) and saturates at 1 under interpolation, so neither metric can judge an over-parameterized model — only a held-out estimate can.

k-fold cross-validation: k=5k = 5 or 1010 in practice. Each fold is used for validation exactly once, so the estimate uses all the data. It is the standard way to choose λ\lambda (regularization strength), the polynomial degree, and other capacity knobs.

The split protocol:

  1. Train: fit the model.
  2. Validate: choose hyperparameters (λ\lambda, degree, early-stopping point).
  3. Test: a single final evaluation on data never used for any decision.

Example problem:

Problem

A model with p=10p = 10 parameters is fit to n=100n = 100 samples and achieves training R2=0.85R^2 = 0.85. (a) Compute the adjusted R2R^2. (b) A colleague fits a model with d=200d = 200 features to the same data and reports training R2=1.0R^2 = 1.0. What does that tell you about its generalization?

Solution

(a) Radj2=1−(1−0.85)×100−1100−10−1=1−0.15×9989≈1−0.167=0.833R^2_{adj} = 1 - (1 - 0.85) \times \frac{100 - 1}{100 - 10 - 1} = 1 - 0.15 \times \frac{99}{89} \approx 1 - 0.167 = 0.833.

(b) Nothing good. d=200>n=100d = 200 > n = 100, so the model interpolates the training data (tr(H)=rank(X)=100=n\text{tr}(H) = \text{rank}(X) = 100 = n), and R2=1R^2 = 1 is guaranteed regardless of how much of the fit is noise. Adjusted R2R^2 is also 1 (saturated). Only a held-out estimate — cross-validation or a test set — can judge this model.

Polynomial and nonlinear regression

Definition: replace each feature by a feature map ϕ(x)=(x,x2,…,xk)\phi(x) = (x, x^2, \ldots, x^k); the model f(x)=θ0+θ1x+⋯+θkxkf(x) = \theta_0 + \theta_1 x + \cdots + \theta_k x^k is still linear in the parameters, so the normal equation, ridge, lasso, R2R^2 and cross-validation all apply unchanged to the expanded design matrix. The degree kk is a capacity knob.

Details

Feature engineering: the only difference from linear regression is the columns of XX: instead of xx, the model sees (x,x2,…,xk)(x, x^2, \ldots, x^k). Everything else — the closed form, the hat matrix, regularization — carries over.

The degree as a capacity knob: the figure below fits polynomials of degree 1, 3 and 10 to 12 noisy samples of y=sin⁡xy = \sin x. Degree 1 underfits (the line cannot bend); degree 3 tracks the curve; degree 10 has 11 parameters for 12 points, so it interpolates the samples — and diverges wildly outside the data range.

0123456-1.5-1.0-0.50.00.51.01.5true: sin(x)degree 1degree 3degree 10underfitoverfit: diverges outside data

Ill-conditioning: as kk grows, the columns x,x2,…,xkx, x^2, \ldots, x^k become nearly collinear and the normal equation becomes numerically unstable. In practice, scale xx to [−1,1][-1, 1] or use orthogonal polynomials.

Connection to kernel methods: the ridge solution can be written in dual form as f(x)=∑iαiK(xi,x)f(x) = \sum_i \alpha_i K(x_i, x) with K(x,x′)=xTx′K(x, x') = x^T x': the prediction depends on the data only through inner products. Replacing the inner product with a kernel (e.g. the RBF K(x,x′)=e−∥x−x′∥2/2σ2K(x, x') = e^{-\|x - x'\|^2 / 2\sigma^2}) gives a nonlinear model without writing the features explicitly; a polynomial kernel of degree kk is exactly polynomial regression of degree kk.

When to prefer a nonlinear model: when a linear model leaves systematic structure in the residuals (the fit bends in a consistent direction). But choose the smallest kk that the validation loss supports (see Model selection) — the degree-10 fit above is the failure mode of turning the knob too far.

Example problem:

Problem

You fit polynomial models of degree k=1,2,3,4,5k = 1, 2, 3, 4, 5 to n=30n = 30 samples. The 5-fold cross-validation MSE is: 0.42, 0.18, 0.17, 0.17, 0.19. Which degree do you choose, and why not k=5k = 5?

Solution

Choose k=3k = 3 (or 2): the CV error bottoms out at k=3k = 3, and k=5k = 5 has a higher CV error — the extra capacity fits noise rather than signal. The rule is to pick the smallest kk within the noise floor of the minimum (parsimony): k=2k = 2 and k=3k = 3 are statistically indistinguishable here, and the simpler model wins ties.

Quiz

Problem: A linear model with d=300d = 300 features is trained on n=100n = 100 samples (the rows of XX are linearly independent) by gradient descent. The learning curve shows: the training MSE decreases monotonically toward 0; the validation MSE decreases until iteration 50, then increases.

(a) What are rank(X)\text{rank}(X) and tr(H)\text{tr}(H)? (b) Diagnose what is happening after iteration 50. (c) If only about 10 of the 300 features carry signal, choose between ridge and lasso and justify.

Solution

(a) rank(X)≤n=100\text{rank}(X) \leq n = 100, and since the rows are independent, rank(X)=100\text{rank}(X) = 100. Hence tr(H)=rank(X)=100\text{tr}(H) = \text{rank}(X) = 100: the model has 100 effective degrees of freedom — exactly enough to interpolate the 100 training points (zero training loss).

(b) Overfitting: after iteration 50 the model starts fitting the noise in the training data; the validation loss rises while the training loss keeps falling. Remedies: regularization (ridge or lasso), more data, or early stopping at iteration 50.

(c) Lasso: it drives the ~290 irrelevant coefficients exactly to zero (sparsity), keeping only the ~10 informative ones. Ridge would shrink them toward zero but never to zero, leaving all 300 features active.