Sub topic 13
L1 regularisation (lasso) and sparse models
This chapter assumes you know how ridge regression penalises squared weights, why penalised models need scaled features, and how cross-validation chooses a hyperparameter. The goal is to see how a different penalty, the sum of absolute weights, changes which models you get.
The L1 penalty
Lasso stands for least absolute shrinkage and selection operator. It adds the L1 norm of the weights to the loss. The L1 norm is the sum of the absolute values of the coefficients. In scikit-learn's convention, the objective is:
(1 / (2 * n_samples)) * sum((y - X @ w - b) ** 2) + alpha * sum(abs(w))Ridge uses alpha * sum(w ** 2) instead. The intercept b is not penalised in either model. As with ridge, a larger alpha means a stronger penalty and a simpler model.
Replacing the square with the absolute value changes the behaviour a great deal. The ridge penalty has a gradient that shrinks as a weight approaches zero. Near zero, ridge applies almost no force, so weights get small but rarely reach exactly zero. The L1 penalty pulls with constant force, alpha, no matter how small the weight is. If a feature's usefulness for reducing the squared error is smaller than that force, the weight stops at exactly zero.
A model with many exactly-zero weights is called sparse. A sparse linear model ignores most features, so it is easier to inspect, cheaper to store, and cheaper to compute.
Why weights land on zero
Consider the simplest case, where features are uncorrelated and have equal scale. Let b_j be the unpenalised least-squares coefficient for feature j. Lasso then applies soft thresholding:
w_j = sign(b_j) * max(abs(b_j) - alpha, 0)Every coefficient moves toward zero by the same amount, alpha. Any coefficient whose size is below alpha becomes zero. Ridge instead scales each coefficient by a factor such as 1 / (1 + alpha). That factor never produces an exact zero.
The geometric view says the same thing. Picture the constraint region sum(abs(w)) <= t. In two dimensions it is a diamond with corners on the axes. The loss contours are ellipses around the unpenalised solution. The first point where an expanding ellipse touches the diamond is often a corner, and at a corner one coordinate is zero. The ridge constraint is a circle with no corners, so contact points rarely lie on an axis.
A worked example
The data below has ten features, but only the first two affect y. We scale the features first, because the penalty treats all weights equally and would otherwise punish features that happen to be measured in large units.
import numpy as np
from sklearn.linear_model import Lasso
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
X = rng.normal(size=(100, 10))
y = 3 * X[:, 0] - 2 * X[:, 1] + rng.normal(0, 0.5, size=100)
X_scaled = StandardScaler().fit_transform(X)
lasso = Lasso(alpha=0.1).fit(X_scaled, y)
print(np.round(lasso.coef_, 2))Expect the first two coefficients to be close to 3 and -2, and slightly smaller in magnitude than the true values. Most or all of the other eight should print as 0. or -0.. The exact numbers depend on the random draw. A weak feature can occasionally keep a tiny non-zero weight at this alpha, so the zeros are typical, not guaranteed.
The shrinkage of the two real coefficients is a cost of lasso. The penalty pulls every non-zero weight toward zero, so even correct features get biased estimates. That bias is the price paid for lower variance and for removing noise features.
Choosing alpha and keeping the pipeline leak-free
The same rules apply as for ridge. Pick alpha by cross-validation on the training data, and keep the test set untouched. LassoCV fits a sequence of alpha values and cross-validates each. Putting the scaler in a pipeline means it is refit on each training fold only. This avoids data leakage, where information from validation data influences preprocessing.
import numpy as np
from sklearn.linear_model import LassoCV
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 10))
y = 3 * X[:, 0] - 2 * X[:, 1] + rng.normal(0, 0.5, size=200)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
model = make_pipeline(StandardScaler(), LassoCV(cv=5))
model.fit(X_train, y_train)
lasso = model[-1]
print("chosen alpha:", round(lasso.alpha_, 4))
print("non-zero features:", np.flatnonzero(lasso.coef_))
print("test R^2:", round(model.score(X_test, y_test), 3))LassoCV picks the alpha with the lowest average validation error. A common alternative is the largest alpha within one standard error of that minimum, which gives a sparser model at nearly the same accuracy. LassoCV does not implement this rule directly. You would compute it from lasso.mse_path_ and lasso.alphas_.
Comparing L1 and L2
| Property | Ridge (L2) | Lasso (L1) |
|---|---|---|
| Penalty | `alpha * sum(w ** 2)` | `alpha * sum(abs(w))` |
| Exact zero weights | Almost never | Often |
| Correlated features | Spreads weight across them | Tends to keep one and drop the rest |
| Many small true effects | Works well | Tends to drop some of them |
| Closed-form solution | Yes | No, solved iteratively |
| Feature selection | No | Yes, built in |
Failure modes and limits
- Correlated features. If two features carry nearly the same signal, lasso often keeps one and zeroes the other. Which one it keeps can change with a different sample or a different cross-validation fold. Do not read the selected set as a stable statement about which features are "the" important ones.
- More features than samples. With
p > n, lasso can select at mostnfeatures. If more thannfeatures truly matter, it will miss some. - Dense signals. If the real relationship involves many small effects, forcing sparsity hurts accuracy. Ridge or elastic net, covered in a later chapter, usually does better.
- Selection is not inference. Choosing features with lasso and then reporting ordinary p-values on those same features is invalid. The selection step used the data.
- Scaling. Without scaling, the features with large numeric ranges get small coefficients and escape the penalty. Features with small ranges are penalised heavily and are dropped first. Unscaled lasso selects based on units.
- Convergence. Scikit-learn uses coordinate descent, which updates one weight at a time. Very small
alphavalues or unscaled data can trigger aConvergenceWarning. Scaling the features, raisingmax_iter, or raisingalphausually fixes it.
When to choose lasso
Use lasso when you suspect that only a few of many features matter, when you need a small interpretable model, or when you want to cut the cost of collecting features in production. Prefer ridge when most features contribute a little, or when features are strongly correlated and you care about prediction more than selection.
Exercise
You fit lasso with alpha=0.5 on unscaled features. Feature A is measured in millimetres with values around 5000. Feature B is measured in metres with values around 5, and both carry the same signal. Which feature is more likely to be zeroed, and what is the fix?
Show answer
Feature B is more likely to be zeroed. To carry the same effect, its coefficient must be about 1000 times larger than A's, and the L1 penalty charges for that larger coefficient. Feature A can achieve the same effect with a tiny coefficient that costs almost nothing. The fix is to standardise both features, with the scaler inside a pipeline so it is fit only on training data. Then tune alpha by cross-validation.