Skip to content
AI.info

Classical machine learning

Ridge, Lasso, and Elastic Net

Understand L2, L1, and mixed regularization through coefficient geometry, scaling, correlation, tuning, and stability.

By the end you can

Regularization changes the question asked of the data

Unregularized least squares asks which coefficients fit the training outcomes best. Regularized regression asks for a fit that also keeps the coefficient vector within a preferred shape or size.

This preference can reduce variance, stabilize correlated features, or produce sparse solutions. It also introduces bias deliberately. The penalty must therefore be evaluated rather than treated as free protection.

Both penalties have a date and a stated purpose. Ridge regression arrived in Technometrics in February 1970, under a title that announced the bias: Ridge Regression: Biased Estimation for Nonorthogonal Problems. Hoerl and Kennard accepted that bias in exchange for stability when the predictor matrix is close to singular. The lasso came twenty-six years later, in 1996. Tibshirani returned to it in 2011 and gave the reason for the exponent. Penalties can be indexed by an exponent q. Ridge regression is q = 2, and subset selection is the limit as q → 0. “The lasso uses the smallest value of q (i.e. closest to subset selection) that yields a convex problem. Convexity is very attractive for computational purposes.” The shape of the constraint was chosen for tractability, and for a preference over coefficient vectors. It was not chosen as a remedy for the data.

Regularization is a modeling assumption about plausible coefficient patterns, not a repair button for invalid data.

Comparison

Ridge, lasso, and elastic net make different compromises

All three use the same features and the same prediction form. Their coefficient geometry differs. Ridge penalizes the squared magnitude of the coefficients: it shrinks correlated effects together and rarely produces exact zeros. Lasso penalizes absolute magnitude, can set coefficients exactly to zero, and therefore performs selection as a side effect of fitting. Elastic net combines the two penalties and adds a mixing hyperparameter. Sparsity survives, and so do correlated blocks.

FigureComparison · 3 columns

Ridge

Penalizes the squared magnitude of coefficients.

  • Shrinks correlated effects together
  • Rarely produces exact zeros
  • Often stable in wide or collinear data
  • Requires feature-scale awareness

Lasso

Penalizes the absolute magnitude of coefficients.

  • Can set coefficients exactly to zero
  • Performs embedded feature selection
  • May choose unpredictably among correlated columns
  • Produces biased nonzero estimates

Elastic net

Combines L1 and L2 penalties.

  • Supports sparsity with group stability
  • Adds a mixing hyperparameter
  • Useful with correlated feature blocks
  • Still needs cross-validated strength

Visual

Penalty geometry changes where the optimum lands

The loss contours meet different constraint shapes, and that creates distinct coefficient behavior. The data-fit contours collect coefficient vectors with similar training error. The L2 constraint is a smooth round region, so it encourages shared shrinkage. The L1 constraint is a diamond, and its corners sit on the coordinate axes. That is why solutions land on axes and coefficients become exactly zero. The elastic-net constraint blends corners with curvature.

FigureLayers · 4 layers
  1. 01

    Data-fit contours

    Sets of coefficient vectors with similar training error.

  2. 02

    L2 constraint

    A smooth round region that encourages shared shrinkage.

  3. 03

    L1 constraint

    A diamond-shaped region with corners on coordinate axes.

  4. 04

    Elastic-net constraint

    A blended geometry that combines corners with curvature.

Feature scale is part of the penalty

A penalty acts on coefficient magnitude. That magnitude depends on feature units. A one-unit change in euros is not comparable with a one-unit change in millions of euros.

That is not a piece of advice floating free of any tool. It is a fork in the tooling, and the two reference implementations take opposite branches. glmnet does the standardising for you. Its reference manual for version 5.0, dated 8 May 2026, documents the `standardize` argument of glmnet() as “Logical flag for x variable standardization, prior to fitting the model sequence. The coefficients are always returned on the original scale. Default is standardize=TRUE.” Centring is not even offered there as a choice. The 2010 coordinate-descent paper behind the package says why in one line: “Irrespective of whether the variables are standardized to have variance 1, we always center each predictor variable.”

scikit-learn 1.9.0 hands the job back to the analyst. Ridge, Lasso and ElasticNet expose no standardize argument at all. The user guide states the requirement as an instruction rather than a default: “The feature matrix X should be standardized before fitting. This ensures that the penalty treats features equally.” The consequence is concrete. The same model, fitted to the same table, returns different coefficients under glmnet and under scikit-learn. That holds unless the person fitting it knows which library standardised and which did not.

Standardize numeric features inside the training pipeline when equal penalty treatment is intended. Binary indicators, ordered variables, and engineered features may require more deliberate scaling choices.

Example

What correlated features do to coefficient stories

This has been measured on real correlated data, twice, in the same year. In 2005 Ein-Dor and colleagues re-ran van 't Veer's own gene-selection method on van 't Veer's own breast-cancer data. Their report in Bioinformatics is blunt: “We showed that, in fact, the resulting set of genes is not unique; it is strongly influenced by the subset of patients used for gene selection. Many equally predictive lists could have been produced from the same analysis.” Which genes came out was decided by which patients went in.

A second reanalysis went wider. In The Lancet, in the same year, Michiels and colleagues reanalysed the seven largest studies of this kind, using repeated random training sets. They found that “The list of genes identified as predictors of prognosis was highly unstable; molecular signatures strongly depended on the selection of patients in the training sets.” Their second finding is the harder one: “Five of the seven studies did not classify patients better than chance.” Correlated predictors carrying nearly the same signal do not produce one true short list. The estimator will not tell you so.

  • Ordinary least squares: coefficients may become large, opposite-signed, and sensitive to small sample changes, while predictions remain stable.
  • Ridge: the shared signal is often distributed across the correlated measurements, with smaller coefficient magnitudes.
  • Lasso: one measurement may enter while the others become zero, and a nearby resample can select a different member — the instability Ein-Dor and colleagues produced deliberately, by changing which patients were used.
  • Elastic net: several members can remain while the overall solution is still sparse.
  • Interpretation: a zero coefficient does not prove a feature is irrelevant when substitutes carry similar information, because many equally predictive lists could have come out of the same analysis.

Steps

Tune a regularized model without leaking the validation signal

Regularization strength belongs inside the model-selection process. Each step has a published number or a published default behind it, not only a recommendation.

Step 1, the fold-aware pipeline. Selection performed once, on all the data, produces cross-validated errors near zero on data that carries no signal. Ambroise and McLachlan showed this on real published data in PNAS on 30 April 2002: “Using two published data sets, we demonstrate that when correction is made for the selection bias, the cross-validated error is no longer zero for a subset of only a few genes.” scikit-learn 1.9.0 ships the same demonstration on data built to contain nothing: 200 samples, 10,000 randomly generated features, labels assigned at random. Selection that sees the test data scores an accuracy of 0.76. The same selection done inside the folds scores 0.5. “Using all the data to perform feature selection results in an accuracy score much higher than chance, even though our targets are completely random.”

Step 2, the penalty path. “Search over orders of magnitude” has an actual shape, and two independent libraries ship it as their default. The coordinate-descent paper states the recipe: “Our strategy is to select a minimum value λmin = ϵλmax, and construct a sequence of K values of λ decreasing from λmax to λmin on the log scale. Typical values are ϵ = 0.001 and K = 100.” The glmnet manual for v5.0 gives nlambda = 100, with lambda.min.ratio 0.0001 when nobs > nvars and 0.01 when nobs < nvars. scikit-learn's LassoCV defaults to eps = 0.001 with 100 alphas: “Length of the path. eps=1e-3 means that alpha_min / alpha_max = 1e-3.” A hundred values on a log scale, not a narrow linear grid.

Step 4, inspecting coefficient paths, is affordable, because the whole path costs about what one fit costs. The Least Angle Regression paper made the claim in its own abstract in 2004: “LARS and its variants are computationally efficient: the paper describes a publicly available algorithm that requires only the same order of magnitude of computational effort as ordinary least squares applied to the full set of covariates.” scikit-learn documents both halves for its own implementation — “It is computationally just as fast as forward selection and has the same order of complexity as ordinary least squares.” and “It produces a full piecewise linear solution path, which is useful in cross-validation or similar attempts to tune the model.” On the leukaemia data the full 100-value path “took under a second in total”. The path, not a single fit, is the object to look at.

Steps 3 and 5, the deployment metric and refitting only after selection. The score at the chosen penalty cannot double as the reported performance. Varma and Simon generated data sets with no difference between the classes at all. They reported in BMC Bioinformatics in 2006: “Even though there is no real difference between the two classes for the "null" datasets, the CV error estimate for the Shrunken Centroid with the optimal parameters was less than 30% on 18.5% of simulated training data-sets.” For SVMs the same thing happened on 38% of them. Nested cross-validation gave an almost unbiased estimate. Cawley and Talbot report the same over-fitting of the selection criterion independently, in 2010: “we demonstrate that a low variance is at least as important, as a non-negligible variance introduces the potential for over-fitting in model selection as well as in training the model”.

Step 6 remains what it always was: compare coefficients and predictions across folds, seeds, or bootstrap samples, and report the spread.

FigureProcess · 6 steps
  1. 1. Build a fold-aware pipeline

    Fit imputation, encoding, transformations, and scaling within each training fold.

  2. 2. Choose a penalty path

    Search strengths over orders of magnitude rather than a narrow linear grid.

  3. 3. Use the deployment metric

    Evaluate errors, thresholds, and slices that matter operationally.

  4. 4. Inspect coefficient paths

    Look for sign changes, unstable selection, and correlated groups.

  5. 5. Refit only after selection

    Train the chosen pipeline on the allowed development data.

  6. 6. Report stability

    Compare coefficients and predictions across folds, seeds, or bootstrap samples.

Analogy

Packing a suitcase under different rules

Items for a trip are chosen under a weight surcharge. Ridge makes every heavy item increasingly expensive. Lasso also rewards leaving some items out entirely. Elastic net encourages a light suitcase without forcing every useful group down to one representative.

Luggage has weight and little else, while coefficients can be negative, correlated, and rescaled. The penalty acts in mathematical coordinates, not on independent physical objects.

The penalty expresses which coefficient configurations the model should prefer when several fits explain the data similarly.

Key idea

Sparse is not the same as scientifically selected

Lasso selection depends on sampling noise, scaling, regularization strength, and the set of correlated alternatives. A selected column is not automatically a causal driver. An excluded column may be redundant rather than useless.

The experiment that makes this measurable is Stability Selection, published by Meinshausen and Bühlmann in 2010 after a 2009 preprint. They took a riboflavin-production dataset from DSM Nutritional Products: n = 115 samples, p = 4,088 gene-expression covariates. Then they randomly permuted all but 6 of the 4,088 genes. Which variables carried signal was therefore known in advance. On the plain lasso path only three of the six stood out; the other three “are hidden within the paths of noise (permuted) genes”, so that “selecting a model with all 6 unpermuted genes invariably means selecting a large number of irrelevant noise variables”. They refitted the lasso on subsamples of size ⌊n/2⌋ and recorded how often each variable was selected. That lifted at least four clear of the noise. With the randomised lasso, at weakness α = 0.2, all six were chosen before any noise variable entered. Same data, same estimator, a different question asked of it.

What is at stake when that check is skipped is not a footnote. Sparse genomic signatures selected from high-dimensional data were used to assign real patients to chemotherapy regimens before anyone had reproduced them. Baggerly and Coombes reverse-engineered those analyses and reported in 2009: “However, we show in five case studies that the results incorporate several simple errors that may be putting patients at risk.” The Institute of Medicine's 2012 report Evolution of Translational Omics records the sequel. Between October 2007 and April 2008, three cancer clinical trials were launched at Duke University on the basis of those tests. Then: “Before the IOM committee convened for its first meeting, investigators at Duke concluded that the omics-based tests used in the three clinical trials were invalid.” The trials were terminated and the papers began to be retracted.

Use stability analysis and domain reasoning before turning sparsity into a scientific claim.

Exact zeros are properties of an optimization solution, not certificates of truth.

Regularization can improve predictions without improving coefficient interpretation

A ridge model may generalize better while making individual coefficients harder to translate. That happens when features are transformed or correlated. Conversely, a sparse lasso can look interpretable and still change its selected set across folds. The seven studies reanalysed in The Lancet in 2005 produced highly unstable gene lists, and five of the seven did not classify patients better than chance.

Evaluate predictive performance and interpretive stability as separate objectives.

A model can be stable in its predictions and unstable in its coefficient story.

Case

Better test error and a longer coefficient list came out of the same two data sets

Two data sets show both halves of that at once, in the 2005 paper that introduced the elastic net. On the prostate cancer data — 67 training and 30 test observations, eight clinical predictors — test mean-squared error was 0.586 for ordinary least squares, 0.566 for ridge, 0.499 for the lasso and 0.381 for the elastic net. Zou and Hastie put the gap at “about 24% lower than that of the lasso”. Each of the two sparse methods kept five predictors, and they were not the same five. On Golub's leukaemia data — 7,129 genes, 38 training and 34 test samples — the elastic net reached a tenfold cross-validation error of 3/38 and a test error of 0/34 while selecting 45 genes. That is more genes than the lasso can return at all: “the size of the training set is 38, so the lasso can at most select 38 genes”. Better predictions, and a longer, differently shaped coefficient story, from the same two data sets.

Figure

The method with the lowest error is also the one returning more coefficients than the training set can support: 45 genes where the lasso can select at most 38. Zou and Hastie, Journal of the Royal Statistical Society Series B 67(2), 2005; the two percentage falls and the 1.18 ratio are derived from the paper’s own errors.

Key takeaways