Overview
A model with many weights can fit noise. One remedy is to make weights cost something, so the model keeps only those that pay their way. The L1 penalty charges each weight in proportion to its absolute value. The charge per unit is the same whether the weight is large or tiny, so there is a constant pull toward zero that does not fade as the weight shrinks. Small, unhelpful weights are pulled all the way to zero and stay there. The result is a sparse model, which also acts as a form of feature selection.
A short history
Robert Tibshirani introduced the lasso in 1996: least squares regression with a limit on the sum of the absolute values of the coefficients. Unlike the older ridge penalty, it sets many coefficients to exactly zero, so it selects variables while fitting. Related ideas appeared in signal processing as basis pursuit. The same penalty is added to neural network losses to encourage sparse weights.
How it works
- Take the weights, one array or a list of arrays.
- In
forward, sum the absolute values of all weights and multiply by . Add this to the data loss. - In
backward, return for each weight, taken as 0 at . Add this to the data-loss gradient. - Or use
proxinstead of the subgradient: first take a gradient step on the data loss alone with learning rate . - Then shrink every weight toward zero by and set those smaller than that to exactly zero. This is soft-thresholding.
Watch out for
- Plain gradient descent with the subgradient makes weights hover around zero without landing on it. Exact zeros need the
proxstep. - Among correlated features, L1 tends to keep one and zero the rest, more or less arbitrarily. Do not read the survivors as the only important ones.
- The penalty shrinks the large, useful weights as well, which biases them toward zero. A common fix is to refit the selected weights without the penalty.
- Penalising biases and normalisation parameters usually hurts. Pass only the weight matrices you intend to regularise.
Use cases
When to use it
When you want a sparse model: feature selection in linear models (the lasso), pruning, or learning sparse codes, especially with many features and few of them relevant.
In industry
- Genomics
- Studies with thousands of gene measurements and few patients use L1-penalised regression to pick out a short list of predictive genes.
- Online advertising
- Large logistic regression models for click prediction use L1 regularisation so that most of the millions of feature weights are zero and the model stays small.
- Credit and insurance
- Analysts fit L1-penalised models to reduce a long list of candidate variables to a few that can be explained to a regulator.
Choosing it: what must hold
- A belief that only a fraction of the inputs or weights matter.
- Features scaled to comparable ranges, so the penalty treats them evenly.
- A penalty strength chosen by validation, and an optimiser that can produce exact zeros if you need true sparsity.
When to choose something else
| If | Use instead |
|---|---|
| Most inputs carry some signal and you only want smaller weights | L2 penalty |
| Features are strongly correlated in groups and you want to keep whole groups | Elastic net, which combines L1 and L2 |
| You train with Adam and want standard regularisation | Decoupled weight decay as in AdamW |
Math foundations
The penalty
The sum of absolute values of all weights, scaled by the strength . This is what
forwardreturns.The objective being minimised
The data loss plus the penalty. A weight earns its place only if it reduces the data loss by more than per unit of size.
The subgradient
A push of constant size toward zero, whatever the weight's size. At the absolute value has a corner, and any value in is valid. The template uses 0.
The proximal step
Soft-thresholding: the exact minimiser of . Weights smaller than become exactly zero and the rest move toward zero by that amount.
Proximal gradient descent
A gradient step on the smooth data loss, then the shrinkage. This is how
proxis meant to be used, and it is the method known as ISTA.
Symbols
- the weights and one of them
- penalty strength,
lamin the config, default 0.0001 - the penalty
- the loss on the data, without the penalty
- the full objective
- the learning rate,
stepin the call toprox - the weights after the gradient step on the data loss
- +1 for positive, -1 for negative, 0 at zero
Worked by hand
Weights with . Compute the penalty and its subgradient, then apply prox with step .
The large weight shrinks by 0.05. The small weight, at 0.02, is below the threshold and becomes exactly zero.
Visual example
Loading the example.
Try this
- Move across the curve: the height is what the model is charged.
- Move each control and watch which part of the curve it changes.
Code sample
import numpy as np
from impl import L1Penalty
from config import L1PenaltyConfig
pen = L1Penalty(L1PenaltyConfig(lam=0.01))
w = np.array([0.5, -0.003, 0.0, -2.0])
data_loss, data_grad = 1.0, np.zeros(4) # stand-ins for your model's loss and gradient
loss = data_loss + pen.forward(w) # 1.0 + 0.01 * 2.503
grad = data_grad + pen.backward(w) # adds 0.01 * sign(w)
w_sparse = pen.prox(w - 0.1 * data_grad, step=0.5) # shrink by 0.005: the -0.003 becomes exactly 0Read the implementation (54 lines)
"""L1 weight penalty: lam * sum(|w|), with its subgradient and its proximal (soft-threshold) step.
NumPy only. `forward` returns the penalty to add to the loss, `backward` its gradient with respect to the weights,
`prox` the exact shrinkage step that produces zeros.
"""
from __future__ import annotations
import numpy as np
try:
from .config import L1PenaltyConfig
except ImportError: # run from the template's own folder
from config import L1PenaltyConfig
def _as_list(weights) -> tuple[list, bool]:
"""Weights as a list of float arrays, plus whether a list (or tuple) was given rather than one array."""
if isinstance(weights, (list, tuple)):
return [np.asarray(w, dtype=float) for w in weights], True
return [np.asarray(weights, dtype=float)], False
class L1Penalty:
"""lam * sum(|w|) over one weight array or a list of them."""
def __init__(self, config: L1PenaltyConfig | None = None) -> None:
self.config = config or L1PenaltyConfig()
def forward(self, weights) -> float:
"""weights: one array of any shape, or a list of arrays. Returns the penalty as a float."""
arrays, _ = _as_list(weights)
return float(self.config.lam * sum(np.abs(w).sum() for w in arrays))
def backward(self, weights):
"""Subgradient of the penalty with respect to the weights: lam * sign(w), taken as 0 at w = 0.
Returns one array, or a list of arrays, matching what was given.
"""
arrays, was_list = _as_list(weights)
grads = [self.config.lam * np.sign(w) for w in arrays]
return grads if was_list else grads[0]
def prox(self, weights, step: float):
"""Proximal step for the penalty (soft-thresholding): shrink every weight towards zero by step * lam
and set those smaller than that to exactly zero.
weights: one array or a list of arrays, normally the result of a gradient step on the data loss alone.
step: the learning rate of that gradient step. Returns the same form as given.
"""
arrays, was_list = _as_list(weights)
threshold = step * self.config.lam
out = [np.sign(w) * np.maximum(np.abs(w) - threshold, 0.0) for w in arrays]
return out if was_list else out[0]
__call__ = forward- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 7, run with
python3 -m unittest -v
Practice
Build L1Penalty(L1PenaltyConfig(lam=0.1)). Starting from 20 random weights, repeat two procedures 200 times each: subtract 0.05 * backward(w), or apply prox(w, 0.05). Count how many weights are exactly zero at the end of each.
Check on learning
- The L1 pull has the same size for a weight of 5 and a weight of 0.001. The L2 pull is proportional to the weight. How does that difference explain which one gives exact zeros?
A way to think about it
Follow a small weight under each. A pull that shrinks with the weight never quite finishes. A constant pull reaches zero in finitely many steps.
- With the subgradient and a fixed step, a weight near zero jumps from positive to negative and back. Why, and how does the proximal step avoid it?
A way to think about it
The step size is regardless of how close the weight is to zero, so it overshoots. Soft-thresholding caps the move at the weight's own size.
- Two features are nearly identical copies. L1 gives one a weight and zeros the other. Should you conclude the second feature is irrelevant?
A way to think about it
Any split of the weight between the two gives the same fit and the same penalty. The choice among them is close to arbitrary, so selection is unstable.
- As rises from zero, more weights become zero. How would you choose where to stop?
A way to think about it
Track validation loss against the number of nonzero weights. Decide whether you want the best fit or the simplest model within a tolerance of it.