Regularization Theory
Suppose you fit a polynomial to ten noisy data points using Empirical Risk Minimization. A degree-9 polynomial passes through every point exactly. It achieves zero training error. Yet it oscillates wildly between data points. It predicts nonsense for any new input. This is the central paradox of learning from finite data. The hypothesis that best explains what you have seen is often the worst at explaining what you have not. Regularization theory is the mathematical machinery that resolves this paradox. It deliberately biases the learner away from complex explanations. This trades a little fit quality for a lot of generalization. The idea matters because almost every production machine learning system would overfit catastrophically otherwise. This includes linear models, neural networks, and gradient-boosted trees. Ridge regression, LASSO, weight decay in deep networks, dropout, and early stopping share a common root. Even the implicit bias of stochastic gradient descent fits this pattern. All are instances of the same underlying principle. Constrain or penalize the hypothesis space. This makes the model prefer simple explanations unless the data strongly demands complexity. Understanding regularization as a coherent theory matters, rather than treating it as a bag of tricks. It lets you reason about which penalty to use. It helps you decide how much of it to apply. And it explains why it provably improves out-of-sample performance. The big picture connects two seemingly different formulations. In constrained risk minimization, you restrict the hypothesis to a ball of bounded norm. Then you minimize empirical risk inside that ball. In penalized (structural) risk minimization, you add a penalty term to the loss. Then you minimize the sum unconstrained. Lagrangian duality shows these are two views of the same object. For convex problems, every constraint radius corresponds to some penalty strength. That penalty strength produces the identical solution. This article builds that correspondence precisely. It derives the geometry of L1 versus L2 penalties. It shows why L1 induces sparsity while L2 shrinks smoothly. By the end you will be able to derive the ridge and LASSO solutions. You will explain the diamond-versus-circle geometry that makes L1 select features. You will state and justify the bias-variance consequences of penalization. And you will correctly tune a regularization strength using validation data rather than guesswork.
- Regularization penalizes hypothesis complexity to prevent overfitting, trading increased training bias for reduced variance.
- Constrained risk minimization (norm-ball constraint) and penalized risk minimization (Lagrangian penalty) are dual formulations of the same problem for convex losses.
- L2 (ridge) penalties shrink all coefficients smoothly toward zero and have a closed-form solution.
- L1 (LASSO) penalties induce exact sparsity because the diamond-shaped constraint region has corners on the axes.
- The regularization strength λ controls model complexity and must be chosen via validation, not fixed by theory alone.
- Elastic Net, group LASSO, and weight decay are practical descendants of the same convex-penalty framework.
Regularization trades a controlled increase in training error for a provable decrease in generalization error by penalizing hypothesis complexity.
The idea
Regularization modifies the empirical risk minimization objective
by adding a term that penalizes complex parameter vectors . The penalized (Tikhonov / structural) form is
where is a penalty function (commonly a norm of ) and is the regularization strength. The constrained form instead solves
restricting the search to a norm-ball of radius . These are not two different ideas — they are the same idea viewed through primal and dual eyes.
Lagrangian duality connects them. Introduce a Lagrange multiplier for the constraint ; the KKT stationarity condition of the constrained problem is exactly the stationarity condition of the penalized problem with that same . For convex, differentiable loss and convex penalty , strong duality holds (Slater's condition is satisfied whenever the constraint set has nonempty interior), so for every there exists a such that , and this correspondence is monotone: larger (looser constraint) corresponds to smaller (weaker penalty). This is why practitioners freely move between "constrain the norm" and "penalize the norm" language — they describe the same solution path traced by one scalar knob. The two canonical penalties are the squared L2 norm, , giving ridge regression, and the L1 norm, , giving the LASSO (Least Absolute Shrinkage and Selection Operator). Both are convex, so the penalized objective remains a convex optimization problem whenever the base loss is convex, preserving global optimality guarantees. The qualitative difference between them — L2 shrinks, L1 selects — comes entirely from the shape of their unit balls, not from any difference in convexity or smoothness of the loss term itself.
How it works
Deriving the ridge solution
Take linear regression with squared loss. The penalized objective is
Differentiating and setting the gradient to zero:
Because is symmetric positive definite for any (even if is singular, e.g. when features are collinear or ), the solution is unique:
This is the single biggest practical reason ridge regression is used even absent any belief in sparsity: it repairs the invertibility problem that breaks ordinary least squares whenever features are correlated or the design matrix is rank-deficient.
Deriving the LASSO update (coordinate descent)
The LASSO objective, , has no closed form for the full vector because is not differentiable at . But it is separable coordinate-wise given the other coordinates fixed, which makes coordinate descent exact and efficient. Fixing all for , the one-dimensional subproblem in reduces (after algebra using the partial residual ) to the soft-thresholding operator:
The soft-threshold function is the proximal operator of the L1 norm; it shrinks its argument toward zero and sets it exactly to zero once — this exact zeroing is the mechanism of sparsity. ``` Algorithm: Coordinate Descent for LASSO Input: X (n×p design matrix, columns standardized), y (n-vector), λ ≥ 0, tolerance ε, max_iters Output: θ (p-vector), the LASSO solution 1. Initialize θ ← 0 # or warm start from previous λ 2. Precompute column norms: c_j ← X_j^T X_j for all j 3. repeat 4. θ_old ← θ 5. for j = 1 to p: 6. r_j ← y − X θ + X_j θ_j # partial residual excluding feature j 7. z_j ← X_j^T r_j 8. θ_j ← soft_threshold(z_j, λ / 2) / c_j 9. until ‖θ − θ_old‖ < ε or iters ≥ max_iters 10. return θ function soft_threshold(z, γ): if z > γ: return z − γ if z < −γ: return z + γ else: return 0 ``` Each outer sweep over all coordinates costs (recomputing residuals incrementally, not from scratch each time), and coordinate descent for LASSO is known to converge because the objective is convex and each coordinate update solves its 1-D subproblem exactly — a block coordinate minimization scheme, which for convex separable-nonsmooth-plus-smooth objectives is guaranteed to converge to the global optimum.
Choosing λ
Neither ridge nor LASSO tells you what should be — that is determined empirically. The standard procedure is k-fold cross-validation over a geometric grid of values, selecting the that minimizes held-out error (or the largest within one standard error of the minimum, the "one-standard-error rule," which prefers simpler models when performance is statistically indistinguishable). ``` Algorithm: Selecting λ via k-fold Cross-Validation Input: data (X, y), candidate grid Λ = {λ_1 > λ_2 > ... > λ_m}, number of folds k Output: λ, the selected regularization strength 1. Split data into k folds F_1, ..., F_k 2. for each λ in Λ: 3. for i = 1 to k: 4. train on all folds except F_i, using penalty λ 5. evaluate validation error on F_i 6. CV_error(λ) ← average validation error over the k folds 7. λ ← argmin_λ CV_error(λ) 8. refit final model on all data using λ 9. return λ ``` The LASSO path — the sequence of solutions as decreases from (at which all coefficients are zero) to 0 (ordinary least squares) — can be computed efficiently with warm starts: initialize the coordinate descent for the next, smaller from the solution at the previous, larger , which is both a good initial guess and dramatically speeds convergence.
The figure shows why the two penalties behave so differently. The elliptical contours are level sets of the loss ; the solution to the constrained problem is the point where the smallest such ellipse touches the constraint region. The L2 ball is smooth everywhere, so the tangency point generically lands at an interior point of an edge — no coordinate is forced to zero. The L1 diamond has sharp corners lying exactly on the coordinate axes; because ellipses are far more likely to first touch a corner than a smooth edge (corners are "attractive" in a measure-theoretic sense — a positive-probability set of ellipse orientations touches each corner, while touching a specific interior edge point is a measure-zero event), the LASSO solution frequently has some coordinates exactly zero. This is the entire geometric explanation for feature selection, foreshadowing the deeper connection to Feature Selection.
Complexity & correctness
Ridge regression. Computing requires forming in time and inverting the resulting matrix in (via Cholesky decomposition, since is symmetric positive definite). Total: time, space for the matrix. This is the same asymptotic cost as ordinary least squares — regularization adds essentially no overhead here, only numerical stability, since guarantees the matrix being inverted is well-conditioned even when alone is singular.
LASSO via coordinate descent. Each full sweep over coordinates costs if residuals are updated incrementally rather than recomputed from scratch (each single-coordinate update touches only one column of , an operation, times coordinates). Convergence to a fixed tolerance typically requires a small constant number of sweeps in practice (often –), though the worst-case iteration count depends on the condition number of the problem; the overall practical cost is commonly quoted as per sweep, times sweeps needed. Because the LASSO objective is convex (sum of a convex quadratic loss and a convex, though nonsmooth, L1 penalty), coordinate descent — which exactly minimizes each coordinate's one-dimensional convex subproblem in turn — provably converges to the global minimum: this is a special case of the general theorem that block coordinate descent converges for objectives that are the sum of a smooth convex function and a separable (coordinate-wise decomposable), possibly nonsmooth, convex function.
Why regularization improves generalization — the bias-variance argument. Decompose the expected test error of an estimator at a fixed input as
Ordinary least squares is the unique unbiased linear estimator with minimum variance among unbiased estimators (the Gauss–Markov theorem), but "minimum variance among unbiased estimators" does not mean minimum variance overall. Ridge regression deliberately introduces bias — in general — in exchange for a reduction in variance that can be large enough to lower total mean squared error. Concretely, for orthogonal design (), the ridge estimate of each coefficient is , a pure shrinkage; its variance is , strictly smaller than the OLS variance for any , while its squared bias grows from zero. There exists a range of small for which the variance reduction outweighs the bias increase, so the ridge estimator has strictly lower MSE than OLS — this is a classical, provable fact, not a heuristic, and it directly foreshadows The Bias-Complexity Tradeoff.
Tradeoffs to be honest about. Ridge never produces exact zeros (its penalty is smooth away from the origin, so no soft-thresholding effect occurs), meaning it does not perform feature selection and all features remain in the model, which can hurt interpretability. LASSO's sparsity is a genuine benefit for interpretability and computational cost at prediction time, but it has known weaknesses: with strongly correlated features it tends to arbitrarily select one and zero out the rest rather than sharing weight, and it can select at most features when . Elastic Net, , is the standard fix, combining both penalties to get sparsity plus grouped shrinkage among correlated features.
Worked example
Consider a tiny regression with one feature standardized to unit variance, target , and observations, where the true relationship is but a second, spurious feature is highly noisy and uncorrelated with in the population but weakly correlated by chance in this small sample.
| Step | Quantity | OLS () | Ridge () | LASSO () |
|---|---|---|---|---|
| 1 | (informative feature) | |||
| 2 | (spurious feature) | |||
| 3 | , (standardized) | , | , | , |
| 4 | Coefficient update rule | soft-threshold at | ||
| 5 | ||||
| 6 | after scaling |
(Step 6's LASSO arithmetic is schematic to show the mechanism: with and threshold applied on the normalized scale, , so soft-thresholding sends it to exactly zero.) Reading the table: OLS assigns a nonzero, noise-inflated coefficient to the spurious feature () simply because of sampling coincidence. Ridge shrinks both coefficients toward zero proportionally, reducing but not eliminating the spurious signal — it is still present, just smaller (). LASSO's soft-thresholding step exactly zeros out the spurious coefficient because its correlation with the residual falls below the threshold , while the true signal survives (shrunk from to , but nonzero). This concretely demonstrates the sparsity mechanism: it is not that LASSO "decides" a feature is useless via some search procedure, it is the direct algebraic consequence of the soft-threshold operator's flat region around zero.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Forgetting to standardize features before penalizing | L1/L2 penalties are scale-dependent; a feature measured in millimeters gets penalized far more than the same feature in meters | Standardize (zero mean, unit variance) all features before fitting; never penalize the intercept |
| Choosing λ by training error | Training error is monotonically nondecreasing in λ, so this always selects λ = 0 | Always tune λ via cross-validation or a held-out validation set |
| Assuming LASSO always outperforms ridge | LASSO's sparsity helps only when the true model is genuinely sparse; with many weakly-informative correlated features, ridge or Elastic Net often generalizes better | Compare via cross-validation, don't assume based on the L1/L2 story alone |
| Treating a zeroed LASSO coefficient as "proof of irrelevance" | With correlated features, LASSO arbitrarily zeros one of a correlated group; the zeroed feature can still be causally or predictively relevant | Use Elastic Net or stability selection when features are collinear |
| Penalizing the bias/intercept term | Shrinking the intercept toward zero has no complexity-control justification and biases predictions | Center and features, exclude the intercept from |
| Confusing constrained-form radius and penalty strength as independently tunable | They are dual to each other for convex problems; treating them as separate hyperparameters wastes search budget | Tune one only; convert via the known monotone correspondence if the other form is needed |
Pioneers & history
Origins · 1 minAndrey Nikolayevich Tikhonov and how this was discovered
Andrey Tikhonov developed what is now called Tikhonov regularization in the 1940s–60s to solve ill-posed inverse problems — problems (arising in geophysics, imaging, and integral equations) where a unique, stable solution does not exist without additional constraints. His insight, that adding a penalty term restores well-posedness by making the solution operator continuous in the data, is mathematically identical to what became ridge regression when Arthur Hoerl and Robert Kennard introduced it independently into statistics in 1970 to fix multicollinearity in linear regression. Robert Tibshirani introduced the LASSO in 1996, explicitly motivated by the desire for a penalty that would perform variable selection automatically rather than merely shrinking coefficients — recognizing that the geometry of the L1 ball, rather than the L2 ball, was the key structural ingredient.
Origins · 1 minhow this was discovered
Where this matters
Ridge regression and its generalizations underpin production systems wherever features are correlated or numerous relative to sample size: genomics (where the number of genes vastly exceeds the number of patients), econometric forecasting, and any linear model built on engineered feature sets with redundancy. LASSO and Elastic Net are the default tools for automatic feature selection in high-dimensional settings — recommender systems selecting a sparse set of predictive signals from thousands of candidates, and biostatistics pipelines identifying a handful of biomarkers from tens of thousands of gene expression measurements. Regularized logistic regression is a staple of interpretable risk-scoring models in credit and healthcare, where sparsity is prized because a model with 12 nonzero coefficients can be audited by a human regulator in a way a model with 10,000 cannot. In deep learning, the L2 penalty reappears as weight decay, added to virtually every training recipe for large neural networks to control the effective capacity of massively overparameterized models; L1 penalties appear in structured pruning objectives that seek to zero out entire neurons or channels for model compression. Support Vector Machines are, at their core, an L2-regularized hinge-loss minimization — the "maximum margin" geometric story and the "penalized empirical risk" algebraic story are the same convex program viewed two ways, another instance of the constrained/penalized duality developed here. Any framework offering `alpha`, `C`, or `weight_decay` hyperparameters — scikit-learn, PyTorch, XGBoost's regularization terms — is exposing exactly the of this article to the user, making regularization theory one of the most universally applied ideas in applied machine learning.
Ask the tutor: How does the choice between L1 and L2 regularization change when the loss function itself is non-convex, such as in deep neural networks?
Why does adding a penalty term reduce overfitting instead of just making training error worse?
Overfitting occurs when a model captures noise-specific patterns from the training sample that do not generalize. A penalty on complexity shrinks the hypothesis toward simpler functions, reducing the model's capacity to memorize noise. This raises training error slightly (bias increases) but lowers the variance of predictions across different training samples drawn from the same distribution. Since generalization error is a sum of squared bias and variance (plus irreducible noise), a well-chosen penalty strength lowers the total generalization error even though training error alone looks worse. The penalty essentially trades a measurable, controlled cost (worse fit on data you have) for a real gain (better fit on data you have not seen).
Is L1 always better than L2 because it gives sparse, interpretable models?
No. L1's sparsity is valuable specifically when the true underlying signal is sparse — only a handful of features actually matter. If most features carry real, correlated signal, LASSO's tendency to arbitrarily zero out some members of a correlated group can discard genuinely useful information and produce unstable coefficient estimates across resamples. Ridge, by contrast, shares weight smoothly among correlated features and is often more stable when many small effects exist. Elastic Net exists precisely to hedge between these regimes. The correct choice is an empirical question, answered by cross-validation, not a theoretical default.
What happens if the regularization strength λ is set too large or too small?
If λ is too small, the penalty barely constrains the hypothesis space, so the model behaves like unregularized ERM and overfits, showing low training error but high validation error. If λ is too large, the penalty dominates the loss, and the model underfits — coefficients are driven so far toward zero (or, in ridge's case, all the way to zero as λ → ∞) that the model fails to capture even the true signal, showing high error on both training and validation sets. The optimal λ sits at the minimum of the validation error curve, balancing these two failure modes, which is exactly the shape underlying The Bias-Complexity Tradeoff.
Why is coordinate descent used for LASSO instead of standard gradient descent?
The L1 penalty is not differentiable at zero, so plain gradient descent has no well-defined gradient exactly where the interesting sparse solutions live. Coordinate descent sidesteps this by minimizing over one coordinate at a time while holding the others fixed; each one-dimensional subproblem has a simple closed-form solution via the soft-thresholding operator, which correctly handles the nondifferentiable point by explicitly checking whether the optimal coordinate value is zero. Because the objective is convex and separable across coordinates in this sense, repeated coordinate updates provably converge to the global optimum, making coordinate descent both simpler and more reliable than subgradient methods for LASSO specifically.
Does regularization change the assumptions of Empirical Risk Minimization, or is it compatible with it?
Regularization is fully compatible with Empirical Risk Minimization; it is best understood as ERM over a restricted or penalized hypothesis class rather than a departure from ERM. The constrained form literally performs ERM subject to , restricting the hypothesis space directly. The penalized form performs ERM on an augmented objective that implicitly favors the same restricted region of hypothesis space. In both views, you are still minimizing empirical risk — you have simply changed which hypotheses are eligible, or how costly complex hypotheses are, which is exactly the mechanism by which finite-sample learning theory bounds generalization error via properties of the hypothesis class.
Can regularization be applied to models other than linear regression, such as logistic regression or neural networks?
Yes — the penalized-risk framework is loss-agnostic. Regularized logistic regression adds the same or term to the cross-entropy loss, and the resulting objective remains convex because cross-entropy loss is convex in the parameters. In neural networks, L2 regularization becomes "weight decay," applied to the (nonconvex) network loss; the global-optimality guarantees from the convex case no longer strictly hold, but the same bias-variance intuition — smaller weights generalize better — still empirically drives its widespread use. Other neural-network-specific regularizers, like dropout and early stopping, achieve similar variance-reduction effects through different mechanisms rather than an explicit norm penalty.
What is the geometric intuition for why L1's "corners" are more likely to be touched by the loss contours than L2's smooth boundary?
Picture growing the elliptical loss contours outward from the unconstrained minimum until they first touch the constraint region's boundary. For the smooth L2 circle, the touching point depends continuously on the ellipse's orientation and eccentricity, and generically lands at a point where the tangent line matches the ellipse's tangent — an interior point of the boundary, not a special location. For the L1 diamond, the corners are places where the boundary's normal direction is not uniquely defined (it takes a whole cone of possible normal directions), so a much larger set of possible ellipse orientations first touches at that exact corner rather than at a smooth edge point. This asymmetry in "how much of the space of possible problems" leads to each type of tangency is the rigorous version of the sparsity intuition.