Sub topic 11
Controlling overfitting with L2 and L1 penalties
This chapter assumes you can fit a logistic regression with log loss and gradient descent, as in the earlier chapters. You should also be comfortable with train/test splits and with standardizing features. Here you will add a penalty to the loss, see how it changes the gradient, and compare L2 and L1 in scikit-learn.
Why an unpenalized fit can go wrong
Log loss rewards confident, correct predictions. With many features, few examples, or classes that a line can separate perfectly, the model can keep lowering the loss by making the weights larger. Large weights push the sigmoid toward 0 and 1. The model then fits noise in the training set and reports extreme probabilities on new data.
In the worst case, the data are perfectly separable. Some weight vector then classifies every training example correctly, and scaling it up always lowers the loss. No finite minimum exists, so gradient descent never converges. The weights grow for as long as you let it run.
A penalty fixes this by adding a cost for large weights:
- Regularization is the practice of adding a term to the loss that discourages complex models.
- The penalized objective is the mean log loss plus a penalty on the weights.
- The bias (intercept) is usually left out of the penalty, because shifting the overall probability level is not a sign of overfitting.
L2 penalty
The L2 penalty is the sum of squared weights. With strength λ (lambda), the objective is:
J(w, b) = mean log loss + (λ / 2) · ‖w‖²
The factor ½ makes the derivative tidy. The gradient with respect to the weights gains one term:
∇w J = Xᵀ(p − y) / n + λ · w
Each update therefore shrinks every weight a little toward zero, in proportion to its size. This is why L2 is also called weight decay. Weights shrink smoothly, and correlated features tend to share weight instead of one taking all of it.
Here is the NumPy implementation from the earlier chapter with that one extra term. The demo uses four perfectly separable points:
import numpy as np
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def fit_logistic_l2(X, y, lam=0.0, lr=0.1, steps=2000):
n, d = X.shape
w = np.zeros(d)
b = 0.0
for _ in range(steps):
p = sigmoid(X @ w + b)
error = p - y
w -= lr * ((X.T @ error) / n + lam * w)
b -= lr * error.mean()
return w, b
X = np.array([[-2.0], [-1.0], [1.0], [2.0]])
y = np.array([0, 0, 1, 1])
for lam in [0.0, 0.01, 0.1]:
w, b = fit_logistic_l2(X, y, lam=lam)
print(f"lambda={lam}: w={w[0]:.2f}")With lam=0.0 the weight is still growing when the loop stops. With a positive λ it settles at a finite value, and a larger λ gives a smaller weight.
L1 penalty
The L1 penalty is the sum of absolute weights:
J(w, b) = mean log loss + λ · Σ |wⱼ|
Its pull toward zero does not weaken as a weight shrinks, unlike the L2 pull, which is proportional to the weight. A weight whose evidence is too weak to pay for its penalty ends up exactly zero. The result is a sparse model that uses only some of the features, so L1 also acts as feature selection.
The absolute value has no derivative at zero, so plain gradient descent does not apply directly. Solvers such as liblinear and saga handle it with coordinate or proximal updates.
| Property | L2 (ridge) | L1 (lasso) |
|---|---|---|
| Penalty | Sum of squared weights | Sum of absolute weights |
| Effect on weights | Shrinks all toward zero | Sets some exactly to zero |
| Correlated features | Spreads weight across them | Tends to keep one, drop the others |
| Smooth objective | Yes | No, needs a special solver |
| Good default when | Most features carry some signal | You expect few useful features, or want a compact model |
The scikit-learn parameter C
scikit-learn does not expose λ. It uses C, the inverse regularization strength. Its L2 objective is:
C · Σ (log loss per example) + ½ ‖w‖²
Dividing by C·n gives the mean-loss form above with λ = 1 / (C · n). Small C means strong regularization, and large C means weak regularization. The default is C=1.0.
Comparing penalties on real data
Always standardize before penalizing. The penalty treats all weights alike, so a feature measured in large units needs a small weight and escapes the penalty. A feature in small units needs a large weight and is penalized heavily. Scaling puts the features on equal terms, as covered in the previous chapter.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
print("penalty C nonzero train_loss test_loss")
for penalty in ["l2", "l1"]:
for C in [0.01, 0.1, 1.0, 10.0]:
model = make_pipeline(
StandardScaler(),
LogisticRegression(penalty=penalty, C=C, solver="liblinear"),
)
model.fit(X_train, y_train)
clf = model.named_steps["logisticregression"]
nonzero = int(np.count_nonzero(clf.coef_))
tr = log_loss(y_train, model.predict_proba(X_train))
te = log_loss(y_test, model.predict_proba(X_test))
print(f"{penalty:>7} {C:5} {nonzero:8d} {tr:11.3f} {te:10.3f}")This snippet also needs import numpy as np, as in the earlier examples. Typical output shows three patterns:
- Training loss rises as C shrinks, because the model is held back.
- Test loss often falls and then rises again as C grows, which is the overfitting pattern.
- The L1 rows show fewer nonzero coefficients at small C. The L2 rows keep all 30 nonzero.
The liblinear solver is used here because it supports both penalties. It also penalizes the intercept slightly, which lbfgs does not. For L1 on large datasets, saga is the usual choice.
Choosing the strength
Pick C with cross-validation, never on the test set. LogisticRegressionCV does this in one step, and it scores on log loss when you pass scoring="neg_log_loss". Search C on a logarithmic grid, such as 10⁻³ to 10³, since its effect is multiplicative.
Common errors
- Not scaling. The penalty then depends on the units of each feature. Put the scaler inside the pipeline so that cross-validation fits it only on training folds.
- Reading L1 sparsity as importance. Among correlated features, L1 may keep any one of them. A dropped feature is not necessarily useless.
- Reading penalized coefficients as unbiased effects. Shrinkage biases coefficients toward zero. Odds ratios from a heavily penalized model understate the effects. Use weak regularization when interpretation matters more than prediction.
- Convergence warnings. Strong data scaling issues or very large C can stop
lbfgsbefore it converges. Raisemax_iteror standardize. - Penalizing a one-hot dummy set unevenly. The penalty depends on which category you treat as the baseline. L2 handles this more gracefully than a dropped-column encoding.
Exercise
A model fitted with LogisticRegression(C=0.01) has smaller coefficients than one fitted with C=100 on the same standardized data. For C=0.01, the training set has n = 500 rows. What is the equivalent λ in the mean-loss form of the L2 objective, and why are the coefficients smaller?
Show answer
λ = 1 / (C · n) = 1 / (0.01 · 500) = 0.2. A small C means a large λ, so the penalty (λ/2)‖w‖² weighs more against the log loss. The optimizer accepts a worse fit to the training data in return for smaller weights, which is why the coefficients shrink.
Exercise
You fit an L1 model and a feature's coefficient is exactly zero. A teammate concludes that the feature has no relationship with the outcome. Give one reason this conclusion may be wrong.
Show answer
L1 sets weights to zero when other features, or the penalty cost, outweigh the feature's contribution. If the feature is correlated with a retained feature, L1 may drop it even though it is informative on its own. A different C, or a different training sample, could also keep it.