TExcelTAD
Home › Classical ML Algorithms: Supervised & Unsupervised › Ridge, Lasso and Elastic Net

Ridge, Lasso and Elastic Net

Two problems from the last lessons share one cure. When features are strongly correlated, least-squares coefficients become huge and unstable; when a model has many features (a degree-2 expansion of 10 inputs already has 65), it overfits. Regularisation adds a penalty on the size of the weights to the loss, trading a little bias for a large drop in variance. The Machine Learning course introduces Ridge and Lasso with scikit-learn; here you implement both.

Three penalties

scikit-learn's objectives (the intercept is not penalised):

ridge:min⁡w ∥y−Xw∥22+α∥w∥22lasso:min⁡w 12n∥y−Xw∥22+α∥w∥1elastic net:min⁡w 12n∥y−Xw∥22+αρ∥w∥1+α(1−ρ)2∥w∥22\begin{aligned} \text{ridge:} \quad & \min_{\mathbf{w}} \ \lVert \mathbf{y} - X\mathbf{w} \rVert_2^2 + \alpha \lVert \mathbf{w} \rVert_2^2 \\ \text{lasso:} \quad & \min_{\mathbf{w}} \ \frac{1}{2n} \lVert \mathbf{y} - X\mathbf{w} \rVert_2^2 + \alpha \lVert \mathbf{w} \rVert_1 \\ \text{elastic net:} \quad & \min_{\mathbf{w}} \ \frac{1}{2n} \lVert \mathbf{y} - X\mathbf{w} \rVert_2^2 + \alpha \rho \lVert \mathbf{w} \rVert_1 + \frac{\alpha (1 - \rho)}{2} \lVert \mathbf{w} \rVert_2^2 \end{aligned}

α≥0\alpha \ge 0 sets the strength and ρ\rho (l1_ratio) the mix. Note the different scaling: Ridge's α\alpha is not divided by nn, Lasso's is, so the same number means different strengths in the two classes.

Ridge keeps a closed form. Setting the gradient to zero gives

wridge=(X⊤X+αI)−1X⊤y,\mathbf{w}_{\text{ridge}} = (X^\top X + \alpha I)^{-1} X^\top \mathbf{y},

and adding α\alpha to every eigenvalue of X⊤XX^\top X makes the system well conditioned however correlated the features are. Ridge shrinks all coefficients towards zero but rarely makes one exactly zero. In Bayesian terms it is the MAP estimate under a Gaussian prior on the weights (MAP Estimation and Regularization).

Lasso has no closed form because ∣wj∣\lvert w_j \rvert has a corner at 0. Coordinate descent solves it one weight at a time: with the others fixed, the best wjw_j is a soft-thresholded correlation,

wj←S(ρj,α)1n∥xj∥2,ρj=1nxj⊤(y−∑k≠jxkwk),S(ρ,α)=sign⁡(ρ)max⁡(∣ρ∣−α,0)w_j \leftarrow \frac{S(\rho_j, \alpha)}{\frac{1}{n} \lVert \mathbf{x}_j \rVert^2}, \qquad \rho_j = \frac{1}{n} \mathbf{x}_j^\top \Big(\mathbf{y} - \sum_{k \ne j} \mathbf{x}_k w_k\Big), \qquad S(\rho, \alpha) = \operatorname{sign}(\rho) \max(\lvert \rho \rvert - \alpha, 0)

Whenever ∣ρj∣≤α\lvert \rho_j \rvert \le \alpha the weight is set to exactly zero, which is why the lasso selects features. The corner is explained with subgradients in Subgradients, the algorithm in Coordinate Descent and The Lasso with ISTA and FISTA.

From scratch

Eight features, only three of which matter, and feature 1 is a near-copy of feature 0:

python · try it yourself
import numpy as np
from sklearn.linear_model import Ridge, Lasso

rng = np.random.default_rng(0)
n, p = 50, 8
X = rng.normal(size=(n, p))
X[:, 1] = X[:, 0] + rng.normal(scale=0.05, size=n)   # feature 1 is almost a copy of feature 0
w_true = np.array([2.0, 0.0, 0.0, -1.5, 0.0, 0.0, 1.0, 0.0])
y = X @ w_true + rng.normal(scale=0.5, size=n)
Xc, yc = X - X.mean(axis=0), y - y.mean()            # centre, so the intercept drops out

def ridge(Xc, yc, alpha):
    return np.linalg.solve(Xc.T @ Xc + alpha * np.eye(Xc.shape[1]), Xc.T @ yc)

def lasso_cd(Xc, yc, alpha, sweeps=500):
    """Coordinate descent for (1/2n)||y - Xw||^2 + alpha ||w||_1 (scikit-learn's objective)."""
    n = len(yc)
    w = np.zeros(Xc.shape[1])
    col_sq = (Xc ** 2).sum(axis=0) / n
    for _ in range(sweeps):
        for j in range(len(w)):
            r_j = yc - Xc @ w + Xc[:, j] * w[j]       # residual without feature j
            rho = Xc[:, j] @ r_j / n
            w[j] = np.sign(rho) * max(abs(rho) - alpha, 0) / col_sq[j]   # soft-thresholding
    return w

ols = np.linalg.lstsq(Xc, yc, rcond=None)[0]
print("true      ", w_true.round(2))
print("OLS       ", ols.round(2))
w_r = ridge(Xc, yc, 10.0)
print("ridge  10 ", w_r.round(2), " sklearn match:", np.allclose(w_r, Ridge(alpha=10.0).fit(X, y).coef_))
w_l = lasso_cd(Xc, yc, 0.1)
print("lasso 0.1 ", w_l.round(2), " sklearn match:", np.allclose(w_l, Lasso(alpha=0.1).fit(X, y).coef_, atol=1e-4))
true       [ 2.   0.   0.  -1.5  0.   0.   1.   0. ]
OLS        [ 4.17 -2.05 -0.03 -1.49  0.01 -0.04  1.03  0.06]
ridge  10  [ 0.92  0.89  0.04 -1.27  0.01  0.08  0.82  0.08]  sklearn match: True
lasso 0.1  [ 1.96  0.    0.   -1.4   0.    0.    0.92  0.01]  sklearn match: True

Three different answers to the twin features:

  • OLS gives them 4.174.17 and −2.05-2.05. Their sum, about 2.1, is right (only the sum is identified when two columns are nearly equal), but each one alone is meaningless and would flip with a little more noise.
  • Ridge splits the effect evenly (0.92 and 0.89) and shrinks every weight a little.
  • Lasso keeps one twin (1.96), sets the other to exactly 0, and zeroes four of the five useless features. The price is some shrinkage of the true effects (−1.4-1.4 instead of −1.5-1.5).

Both from-scratch versions match scikit-learn. Centring XX and y\mathbf{y} first is what makes the unpenalised intercept drop out.

Choosing alpha by cross-validation

RidgeCV and LassoCV try a grid of strengths and keep the best by cross-validation. On the diabetes data, a degree-2 expansion overfits plain least squares; regularisation recovers it:

python · try it yourself
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.linear_model import RidgeCV, LassoCV, LinearRegression
from sklearn.model_selection import cross_val_score, KFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler, PolynomialFeatures

X, y = load_diabetes(return_X_y=True)
cv = KFold(5, shuffle=True, random_state=0)
models = {
    "OLS, 10 features":          make_pipeline(StandardScaler(), LinearRegression()),
    "OLS, 65 features (deg 2)":  make_pipeline(PolynomialFeatures(2, include_bias=False), StandardScaler(), LinearRegression()),
    "RidgeCV, 65 features":      make_pipeline(PolynomialFeatures(2, include_bias=False), StandardScaler(), RidgeCV(alphas=np.logspace(-2, 3, 30))),
    "LassoCV, 65 features":      make_pipeline(PolynomialFeatures(2, include_bias=False), StandardScaler(), LassoCV(cv=5, random_state=0, max_iter=5000)),
}
for name, m in models.items():
    print(f"{name:26s} CV R^2 {cross_val_score(m, X, y, cv=cv).mean():.3f}")
lasso = models["LassoCV, 65 features"].fit(X, y)[-1]
print("lasso alpha:", round(lasso.alpha_, 3), " non-zero coefficients:", int((lasso.coef_ != 0).sum()), "of 65")
OLS, 10 features           CV R^2 0.489
OLS, 65 features (deg 2)   CV R^2 0.412
RidgeCV, 65 features       CV R^2 0.475
LassoCV, 65 features       CV R^2 0.489
lasso alpha: 2.971  non-zero coefficients: 16 of 65

The 65 squared and product features drop plain least squares from 0.489 to 0.412 (5-fold CV R2R^2). Ridge recovers most of that and the lasso all of it, keeping 16 of the 65 features. The inner RidgeCV/LassoCV search runs inside each outer fold, so the outer score is honest; the alpha printed at the end is from a final fit on all the data. On this data the interactions add little: the plain 10-feature model is just as good, a useful reminder that more features is not automatically better.

Strengths, weaknesses, when to use

Ridge Lasso Elastic net
effect shrinks all weights sets some weights to exactly 0 both
correlated features shares the weight picks one, arbitrarily groups them
solution closed form iterative (coordinate descent) iterative
use when many small effects, collinearity you expect few relevant features, want selection correlated groups of relevant features

Always standardise before regularising: the penalty treats all weights alike, so a feature measured in grams would be penalised differently from the same feature in kilograms.

Pitfalls

  • Forgetting to scale. The penalty's effect then depends on arbitrary units.
  • Reading lasso's choice among twins as importance. Which of two correlated features survives can flip with a small change in data.
  • Comparing alphas across classes. Ridge's and Lasso's α\alpha are on different scales.

Practice

  1. Show that ridge's matrix X⊤X+αIX^\top X + \alpha I is invertible for every α>0\alpha > 0.
Answer

X⊤XX^\top X is positive semidefinite, so its eigenvalues are λi≥0\lambda_i \ge 0. Adding αI\alpha I shifts each to λi+α>0\lambda_i + \alpha > 0, so all eigenvalues are positive and the matrix is invertible (Positive Definite Matrices).

  1. In lasso_cd, what happens to every weight when α\alpha is larger than max⁡j∣xj⊤y∣/n\max_j \lvert \mathbf{x}_j^\top \mathbf{y} \rvert / n?
Answer

Starting from w=0\mathbf{w} = \mathbf{0}, each ρj=xj⊤y/n\rho_j = \mathbf{x}_j^\top \mathbf{y}/n has ∣ρj∣≤α\lvert \rho_j \rvert \le \alpha, so every update gives 0 and the solution stays at zero. This αmax⁡\alpha_{\max} is where LassoCV starts its grid.

Test yourself

Which penalty can set coefficients exactly to zero?

  1. L2 (ridge)
  2. L1 (lasso)
  3. neither
  4. only an L2 penalty with a huge α\alpha

Two features are almost identical. What does ridge regression do with them?

  1. Drops one
  2. Gives them roughly equal weights that sum to the shared effect
  3. Gives them huge opposite weights
  4. Raises an error

Why standardise features before ridge or lasso?

  1. The solvers need it to converge
  2. The penalty treats all weights equally, so their scale must be comparable
  3. It removes outliers
  4. It makes the model nonlinear