Machine Learning · medium
Asked in ML Engineer interviews, in the Machine Learning round.
L1 (Lasso) drives weights to zero (sparsity/selection); L2 (Ridge) shrinks weights smoothly.
Both add a penalty on the weights to the loss, so the model prefers small coefficients unless the data insists. They differ in the shape of the penalty, and that shape decides what happens to weights near zero.
The geometric picture, if they want it: the L1 constraint region is a diamond with corners on the axes, and the loss contours tend to touch it at a corner, where some coordinates are zero; the L2 region is a circle with no corners.
from sklearn.linear_model import Lasso, Ridge
Lasso(alpha=0.01).fit(X, y).coef_ # many exact zeros
Ridge(alpha=1.0).fit(X, y).coef_ # all small, none zero
When to use which: L1 when you have many features and expect few to matter, or need an interpretable model; L2 when features are correlated (L1 picks one of a correlated pair arbitrarily, L2 shares the weight) or when you just want stability. Elastic net mixes both. Scale the features first; a penalty on raw weights punishes whichever feature happens to be measured in small units.