Gradient LabStart the lesson

Lessons › Chapter 5: Generalization

L1 and L2 regularization

regularization adds a penalty to the loss: the bigger the weights, the bigger the fee. Now the model only keeps a weight large if it truly earns its keep by reducing the error.

Watch it move. This lesson is interactive on Gradient Lab: every step is an animated scene you can replay.

Start the interactive lesson

Step by step

Story

Too many columns

The loan table has grown to 60 columns, and many of them are useless.

Problem

Big weights, nervous model

An overfit model often leans very hard on many features at once: its weights get large. Large weights make it jumpy, so tiny changes in the input swing the prediction a lot.

Key idea

Charge a fee for big weights

regularization adds a penalty to the loss: the bigger the weights, the bigger the fee. Now the model only keeps a weight large if it truly earns its keep by reducing the error.

Build

L2 shrinks everything a bit

With the L2 penalty (sum of squared weights), every weight shrinks toward zero, the biggest ones most. The model becomes calmer and smoother.

Build

L1 switches features off

With the L1 penalty (sum of absolute weights), many weights drop to exactly zero. Those features are switched off, so L1 doubles as automatic feature selection.

Real life

In real life: ignoring useless clues

A house-price model might be given dozens of columns, including junk like the house number or the listing ID. L1 regularization lets the model switch those off by itself and keep the clues that matter, like size and location.

Quick check: Which penalty can set some weights to exactly zero?

L1’s absolute-value penalty pushes small weights all the way to zero; L2 only shrinks them.

Pseudocode

loss = prediction error
     + λ × size of the weights        # the penalty

L2 (ridge): penalty = sum of weights²    → shrinks all weights
L1 (lasso): penalty = sum of |weights|   → pushes some to exactly 0

bigger λ = stronger penalty = simpler model

Key terms

regularization
A penalty that keeps a model’s weights small so it stays simple and doesn’t memorize.