Sub topic 11
Controlling overfitting with L2 and L1 penalties
This chapter assumes you know log loss, gradient descent, and why features should be scaled. It also assumes you can read a scikit-learn pipeline.
Why the model overfits
With many features, or few examples, logistic regression can push its weights very large. Large weights make the sigmoid steep, so the model becomes extremely confident on the training data and fits its noise. If the classes are perfectly separable, the loss keeps falling as the weights grow. Training never reaches a finite optimum.
Regularization adds a penalty on the weights to the loss. The optimizer then has to trade a better fit against smaller weights.
L2 and L1 penalties
- L2 (ridge) adds the sum of squared weights. It shrinks all weights toward zero smoothly. Correlated features share weight, and few weights become exactly zero.
- L1 (lasso) adds the sum of absolute weights. It can set weights exactly to zero, which acts as built-in feature selection.
In math, with λ as the penalty strength:
loss = mean log loss + λ · Σ wⱼ² (L2)
loss = mean log loss + λ · Σ |wⱼ| (L1)The bias term is conventionally left out of the penalty. Standard formulations leave it out, although some solvers such as liblinear do penalize it.
Strength in scikit-learn: C
scikit-learn does not expose λ. It exposes C, the inverse regularization strength. Roughly, C plays the role of 1/λ, up to how the loss is averaged:
| C value | Penalty | Typical effect |
|---|---|---|
| Small (0.01) | Strong | Small weights, risk of underfitting |
| 1.0 (default) | Moderate | A reasonable starting point |
| Large (100) | Weak | Large weights, risk of overfitting |
Comparing penalties
The penalty acts on weight size, so features must be on the same scale. Otherwise a feature measured in small units needs a large weight and gets penalized unfairly. Scale inside the pipeline.
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
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
)
for penalty in ["l2", "l1"]:
for C in [0.01, 0.1, 1.0]:
model = make_pipeline(
StandardScaler(),
LogisticRegression(penalty=penalty, C=C, solver="liblinear"),
)
model.fit(X_train, y_train)
coef = model[-1].coef_[0]
accuracy = model.score(X_test, y_test)
nonzero = int((coef != 0).sum())
print(penalty, C, round(accuracy, 3), nonzero)The last column counts nonzero weights out of 30. With L1, that count should drop as C shrinks. With L2, it should stay at or near 30 while the weights get smaller.
Choosing C
Do not pick C by test accuracy. Choose it by cross-validation on the training data, for example with LogisticRegressionCV or GridSearchCV over a logarithmic grid such as 0.001 to 100. Keep the test set for the final report.
Exercise
You fit an L1 logistic regression with C=0.05 and 20 of your 40 coefficients are exactly zero. A colleague says the 20 dropped features are useless. What is wrong with that claim, and what would you try to check it?
Show answer
L1 zeroes weights for the chosen strength, and with correlated features it may keep one and drop another that is equally informative. The claim also depends on C. Refit with a larger C or different cross-validation folds and see whether the same features survive. You can also fit an L2 model and check whether the dropped features carry sizeable weights there.