Sign in

L1 penalty

L1 norm weight penalty (lasso)

A regulariser added to the loss that charges for the absolute size of every weight, which drives many weights to exactly zero.

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

  1. Take the weights, one array or a list of arrays.
  2. In forward, sum the absolute values of all weights and multiply by λ\lambda. Add this to the data loss.
  3. In backward, return λ sign⁡(w)\lambda\,\operatorname{sign}(w) for each weight, taken as 0 at w=0w = 0. Add this to the data-loss gradient.
  4. Or use prox instead of the subgradient: first take a gradient step on the data loss alone with learning rate η\eta.
  5. Then shrink every weight toward zero by ηλ\eta\lambda 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 prox step.
  • 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

IfUse instead
Most inputs carry some signal and you only want smaller weightsL2 penalty
Features are strongly correlated in groups and you want to keep whole groupsElastic net, which combines L1 and L2
You train with Adam and want standard regularisationDecoupled weight decay as in AdamW

Math foundations

  1. The penalty

    Ω(w)=λ ∥w∥1=λ∑i∣wi∣\Omega(w) = \lambda\,\lVert w \rVert_1 = \lambda \sum_{i} |w_i|

    The sum of absolute values of all weights, scaled by the strength λ\lambda. This is what forward returns.

  2. The objective being minimised

    J(w)=Ldata(w)+λ ∥w∥1J(w) = \mathcal{L}_{\text{data}}(w) + \lambda\,\lVert w \rVert_1

    The data loss plus the penalty. A weight earns its place only if it reduces the data loss by more than λ\lambda per unit of size.

  3. The subgradient

    ∂Ω∂wi=λ sign⁡(wi)\frac{\partial \Omega}{\partial w_i} = \lambda\,\operatorname{sign}(w_i)

    A push of constant size λ\lambda toward zero, whatever the weight's size. At wi=0w_i = 0 the absolute value has a corner, and any value in [−λ,λ][-\lambda, \lambda] is valid. The template uses 0.

  4. The proximal step

    prox⁡ηλ(v)i=sign⁡(vi) max⁡ ⁣(∣vi∣−ηλ,  0)\operatorname{prox}_{\eta\lambda}(v)_i = \operatorname{sign}(v_i)\,\max\!\big(|v_i| - \eta\lambda,\; 0\big)

    Soft-thresholding: the exact minimiser of 12∥w−v∥2+ηλ∥w∥1\tfrac{1}{2}\lVert w - v \rVert^{2} + \eta\lambda\lVert w \rVert_1. Weights smaller than ηλ\eta\lambda become exactly zero and the rest move toward zero by that amount.

  5. Proximal gradient descent

    w←prox⁡ηλ ⁣(w−η ∇Ldata(w))w \leftarrow \operatorname{prox}_{\eta\lambda}\!\big(w - \eta\,\nabla \mathcal{L}_{\text{data}}(w)\big)

    A gradient step on the smooth data loss, then the shrinkage. This is how prox is meant to be used, and it is the method known as ISTA.

Symbols

w,wiw, w_i
the weights and one of them
λ\lambda
penalty strength, lam in the config, default 0.0001
Ω(w)\Omega(w)
the penalty
Ldata\mathcal{L}_{\text{data}}
the loss on the data, without the penalty
J(w)J(w)
the full objective
η\eta
the learning rate, step in the call to prox
vv
the weights after the gradient step on the data loss
sign⁡\operatorname{sign}
+1 for positive, -1 for negative, 0 at zero

Worked by hand

Weights w=(0.5,−0.02,0)w = (0.5, -0.02, 0) with λ=0.1\lambda = 0.1. Compute the penalty and its subgradient, then apply prox with step η=0.5\eta = 0.5.

Ω=0.1×(0.5+0.02+0)=0.052\Omega = 0.1 \times (0.5 + 0.02 + 0) = 0.052
∂Ω∂w=(0.1,  −0.1,  0)\frac{\partial \Omega}{\partial w} = (0.1,\; -0.1,\; 0)
ηλ=0.5×0.1=0.05\eta\lambda = 0.5 \times 0.1 = 0.05
prox⁡(w)=(0.5−0.05,    0,    0)=(0.45,  0,  0)\operatorname{prox}(w) = \big(0.5 - 0.05,\;\; 0,\;\; 0\big) = (0.45,\; 0,\; 0)

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 0
Read 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

  1. 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.

  2. 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 ηλ\eta\lambda regardless of how close the weight is to zero, so it overshoots. Soft-thresholding caps the move at the weight's own size.

  3. 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.

  4. As λ\lambda 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.