Notes
All notes

Deriving Regularization (ML #2)

Chapter 1 ended with a warning: least squares will happily use every column you give it, because adding features can only shrink \(\|y - \tilde{X}\theta\|\). Your 400-feature model on 300 rows now memorizes the noise. You need a way to say “use these coefficients unless they’re not worth their cost”.

The standard answer is to add a penalty to the objective. But the interesting part is not that L1 zeroes coefficients — it’s why, and the answer is entirely about the shape of the penalty’s contour lines. Two penalties that look almost identical produce qualitatively different models, and the difference falls out of one corner of a diagram.

By the end you will have derived both solutions, seen exactly where sparse solutions come from, and learned why the penalty strength is not comparable between L1 and L2.

Deriving ridge: add a quadratic penalty

Take the objective from Chapter 1 and add \(\lambda \|w\|_2^2\). Note we penalize weights only, not the intercept — the intercept is not a model parameter that encodes signal, so shrinking it toward zero would just bias predictions toward the origin:

\[ L(\theta) = \frac{1}{n} \| y - \tilde{X}\theta \|_2^2 + \lambda \| w \|_2^2 \]

The \(\nabla_\theta\) of the first term we already know. The new term contributes \(2\lambda w\) (and zero for the intercept, which lives outside the penalty). Setting the total gradient to zero:

\[ \frac{2}{n}\tilde{X}^\top(\tilde{X}\theta - y) + 2\lambda \tilde{w} = 0 \;\Longrightarrow\; \left( \tilde{X}^\top \tilde{X} + n\lambda I \right) w = \tilde{X}^\top y \]

So ridge regression has the same closed form as OLS with one addition:

\[ w_{\text{ridge}} = \left( \tilde{X}^\top \tilde{X} + n\lambda I \right)^{-1} \tilde{X}^\top y \]

This one extra term explains everything ridge does. \(\tilde{X}^\top\tilde{X}\) has eigenvalues from 0 to \(\lambda_{\max}\); adding \(n\lambda I\) shifts every eigenvalue up by \(n\lambda\), so:

That last point is a theorem, not an intuition, and it’s worth proving. Decompose \(w\) along the eigenvectors of \(\tilde{X}^\top\tilde{X}\): each component \(w_i\) must independently minimize its own 1-D problem, giving

\[ w_i = \frac{\lambda_i\, \theta_i}{\lambda_i + n\lambda} \quad\text{where}\quad \theta = \tilde{X}^+ y \]

Every component is multiplied by a factor \(\frac{\lambda_i}{\lambda_i + n\lambda} \in (0, 1)\). Ridge shrinks, never kills.

Deriving lasso: swap the norm, change everything

Now swap the penalty for \(\lambda\|w\|_1\):

\[ L(w) = \frac{1}{n}\| y - \tilde{X}w \|_2^2 + \lambda \| w \|_1 \]

\(\|w\|_1\) is not differentiable at any \(w_j = 0\) — the subgradient is \([-1, +1]\) there. This is the entire story. In one dimension, differentiate the objective directly and set the subgradient condition to zero:

\[ \frac{2}{n}\sum_i x_{ij}(y_i - w_j x_{ij}) - \lambda\,\text{sign}(w_j) = 0 \;\Longrightarrow\; \sum_i x_{ij}^2 w_j = \sum_i x_{ij}y_i - \tfrac{n\lambda}{2}\text{sign}(w_j) \]

The solution is the soft-thresholding operator:

\[ w_j = \text{sign}\!\left(\hat w_j^{\text{OLS}}\right) \max\!\left(\left|\hat w_j^{\text{OLS}}\right| - \frac{\lambda}{2}, \; 0\right) \]

Read that formula carefully: if \(\left|\hat w_j^{\text{OLS}}\right| \le \frac{\lambda}{2}\), the result is exactly zero — not small, zero. L1’s entire model-selection behavior is one max(·, 0).

import numpy as np

def lasso_coordinate_descent(X, y, lam, iters=5000):
    """Exact 1-D lasso updates; each coordinate solved in closed form."""
    n, d = X.shape
    Xb = np.c_[X, np.ones(n)]              # intercept unpenalized, handled separately
    w = np.zeros(d + 1)
    XtX = Xb.T @ Xb
    for _ in range(iters):
        for j in range(d + 1):
            resid = y - Xb @ w + Xb[:, j] * w[j]
            rho = Xb[:, j] @ resid
            # subgradient condition; intercept not shrunk
            thr = lam * n / 2 if j < d else 0.0
            w[j] = np.sign(rho) * max(abs(rho) - thr, 0) / XtX[j, j]
    return w

rng = np.random.default_rng(0)
n, p = 200, 6
X = rng.normal(size=(n, p))
y = X @ np.array([3.0, 0, 0, -2.5, 0, 0]) + rng.normal(scale=1.0, size=n)   # only 2 real signals

def ridge(lam):
    Xb = np.c_[X, np.ones(n)]
    return np.linalg.solve(Xb.T @ Xb + n * lam * np.eye(p + 1), Xb.T @ y)

wl, wr = lasso_coordinate_descent(X, y, 1.0), ridge(1.0)
print("lasso:", np.round(wl[:-1], 6))    # [ 2.444229  0.  0. -1.948671  0. -0.]
print("ridge:", np.round(wr[:-1], 6))    # [ 1.421507 0.133554 0.087833 -1.253851 0.047789 -0.034717]

At the same \(\lambda\), lasso drives four of the six coefficients to exactly 0.0, while ridge’s smallest surviving coefficient is still 0.035. Lasso also fits the training data better (MSE 1.63 vs 4.76) — it discarded the four noise directions entirely, whereas ridge shrank the two real signals (3.0 → 1.42) along with everything else. That is the empirical form of the subgradient argument, and it is the honest version of “L1 is better at feature selection”.

One honest caveat, because the textbook version oversells this: L1 does not always zero coefficients. Sparsity only appears once \(\lambda\) exceeds half the largest correlation — sweep \(\lambda\) and watch the path:

\(\lambda\) lasso nonzero ridge nonzero train MSE (lasso / ridge)
0.01 6 6 1.073 / 1.074
0.05 6 6 1.077 / 1.108
0.30 3 6 1.161 / 1.879
1.00 2 6 1.631 / 4.758

Below \(\lambda \approx 0.1\) both penalties use every feature, and note how nearly identical they are — the “L1 selects features” claim is a statement about the large-\(\lambda\) regime, not a general property.

Why the shape matters: the geometry

Both penalties do the same thing — they intersect the elliptical least-squares contours with a constraint region — but the region differs. The derivation makes this precise. Rewrite each as “minimize error subject to a budget”:

\[ \min_w \| y - \tilde{X}w \|_2^2 \quad \text{s.t.} \quad \|w\|_2 \le t \;\; (L_2) \qquad\text{or}\qquad \|w\|_1 \le t \;\; (L_1) \]

The optimum sits where an ellipse first touches the constraint boundary — a point of tangency, since at the optimum the ellipse’s gradient and the constraint’s gradient are parallel (Lagrange multipliers, which Chapter 9 develops fully for SVMs).

\begin{tikzpicture}[font=\rmfamily, scale=0.92]
  % L2 ball
  \begin{scope}
    \draw[->, thick] (-3.4,0) -- (3.4,0) node[right, font=\rmfamily\scriptsize] {$w_1$};
    \draw[->, thick] (0,-2.4) -- (0,2.4) node[above, font=\rmfamily\scriptsize] {$w_2$};
    \foreach \s in {0.7,1.4,2.1}
      \draw[gray!70] (-3.2,{0.55*\s}) .. controls (-1.2,{0.9*\s}) and (1.2,{0.9*\s}) .. (3.2,{0.55*\s});
    \draw[blue, very thick] (0,0) circle (1.05);
    \fill[blue!70] (1.05,0) circle (2pt);
    \node[font=\rmfamily\scriptsize, text=blue!70!black] at (0,-1.55) {$L_2$ ball: corner $\to$ no exact zeros};
  \end{scope}
  % L1 diamond
  \begin{scope}[xshift=7.4cm]
    \draw[->, thick] (-3.2,0) -- (3.2,0) node[right, font=\rmfamily\scriptsize] {$w_1$};
    \draw[->, thick] (0,-2.4) -- (0,2.4) node[above, font=\rmfamily\scriptsize] {$w_2$};
    \foreach \s in {0.7,1.4,2.1}
      \draw[gray!70] (-3.2,{0.55*\s}) .. controls (-1.2,{0.9*\s}) and (1.2,{0.9*\s}) .. (3.2,{0.55*\s});
    \draw[orange!80!black, very thick] (0,1.5) -- (1.5,0) -- (0,-1.5) -- (-1.5,0) -- cycle;
    \fill[orange!85!black] (1.5,0) circle (2.2pt);
    \node[font=\rmfamily\scriptsize, text=orange!70!black] at (0,-1.9) {$L_1$ diamond: vertex on an axis $\to$ exact zero};
  \end{scope}
\end{tikzpicture}

This is the picture to keep. The \(L_2\) ball is round: tangency almost never lands on a coordinate axis, so no coefficient is exactly zero. The \(L_1\) diamond is pointed, with its vertices lying precisely on the axes — and tangency prefers vertices, because a vertex touches a smooth ellipse at exactly one point while a curved edge generally touches it at a worse point. Whenever the ellipse reaches a diamond corner, the solution is exactly on an axis: one coefficient is zero. Sparsity isn’t an effect added to the model; it’s the geometry of a polytope whose corners lie on the axes.

What each penalty is for

Ridge (L2) Lasso (L1) Elastic net
Penalty \(\lambda\|w\|_2^2\) \(\lambda\|w\|_1\) \(\lambda(\alpha\|w\|_1 + \tfrac{1-\alpha}{2}\|w\|_2^2)\)
Sparsity never exactly zero yes, large \(\lambda\) yes
Singularity fix yes yes yes
Grouped features no no yes (the \(\alpha\) term couples them)
Collinear pair splits weight, keeps both picks one, drops other tends to keep both

Elastic net deserves the last note: plain lasso on two identical features picks one arbitrarily and drops the other; ridge splits the weight between them. Elastic net’s L1 term still allows zeros while the L2 term stabilizes which of a correlated group survives.

Choosing λ, and a warning about the parameter

There is no closed form for \(\lambda\) — it is chosen by cross-validation (Chapter 13). One trap catches nearly everyone: \(\lambda\) is not comparable between L1 and L2, because the objectives are scaled differently. Ridge’s gradient scales with \(n\lambda\) while lasso’s threshold is \(\frac{n\lambda}{2}\) on a different quantity. The same numeric \(\lambda\) on both penalizes very differently, and the “correct” ranges depend on your feature count and \(n\).

from sklearn.linear_model import Ridge, Lasso
from sklearn.model_selection import cross_val_score

for model in (Ridge(alpha=1.0), Lasso(alpha=0.1)):
    scores = cross_val_score(model, X, y, cv=5, scoring="neg_mean_squared_error")
    print(type(model).__name__, -scores.mean().round(4))

Pitfalls

QQuestionSelf-check

Show that ridge’s closed form is \(\left(\tilde{X}^\top\tilde{X} + n\lambda I\right)^{-1}\tilde{X}^\top y\) and explain why \(\lambda_i + n\lambda\) guarantees no singular directions. Why does L1 produce exact zeros while L2 does not, in terms of the subgradient at zero? Your lasso has no zeros even though 4 of 6 features are pure noise — what should you try?

ASolution

Differentiating \(\frac{1}{n}\|y - \tilde{X}w\|^2 + \lambda\|w\|_2^2\) gives \(\frac{2}{n}\tilde{X}^\top(\tilde{X}w - y) + 2\lambda w = 0\) (weights only, intercept excluded from the penalty), which rearranges to the stated form. In the eigenbasis of \(\tilde{X}^\top\tilde{X}\) each component is multiplied by \(\frac{\lambda_i}{\lambda_i + n\lambda}\), strictly positive, so no component can be zero and no eigenvalue of the shifted matrix is zero — ridge is always invertible, which is exactly how it fixes duplicate columns. For L1, the penalty \(\|w\|_1\) is non-differentiable at \(w_j = 0\) with subgradient \([-1,1]\); the optimality condition becomes \(\left|\sum_i x_{ij}(y_i - \hat w_j x_{ij})\right| \le \frac{\lambda}{2}\), and that inequality is satisfied with equality only when \(\hat w_j = 0\). Geometrically, the \(L_1\) budget region’s vertices sit exactly on the axes, so tangency with an ellipse prefers a corner. On the non-sparse lasso: \(\lambda\) was simply below the threshold — \(\left|\hat w_j^{\text{OLS}}\right| \le \lambda/2\) held for every \(j\), so nothing was zeroed. The sweep shows the transition: 6 nonzeros at \(\lambda = 0.05\), 3 at \(0.30\), 2 at \(1.00\), while ridge stays at 6 throughout. Cross-validate over that path rather than picking one \(\lambda\) by hand.

Next: Deriving Logistic Regression (ML #3) — swapping squared error for a likelihood, and watching cross-entropy appear on its own.