I was reminded by a Kaggler today that although I showed you guys sample code to add regularization for linear regression (Lasso and Ridge) I never explained how to do this for classification (logistic regression).
First off, fun fact: it turns out that sklearn’s LogisticRegression already uses regularization by default! Specifically, it uses L2 (ridge) regularization.
To control the regularization in LogisticRegression, there are three important parameters:
C: Controls the strength of regularization. UnlikealphainRidgeandLasso, smaller values mean stronger regularization. The default isC=1.0.l1_ratio: Controls the type of regularization:0: Pure L2 (ridge)1: Pure L1 (lasso)- Between 0 and 1: A mixture of L1 and L2 (elastic net)
solver: Specifies the optimization algorithm. Usesolver="saga"if you want L1 or elastic net regularization.
Here are some examples:
from sklearn.linear_model import LogisticRegression
# Ridge (L2) regularization — the default
model = LogisticRegression(C=1.0)
# Stronger ridge regularization
model = LogisticRegression(C=0.1)
# Lasso (L1) regularization
model = LogisticRegression(C=1.0, l1_ratio=1, solver="saga")
# Elastic net (50% L1, 50% L2)
model = LogisticRegression(C=1.0, l1_ratio=0.5, solver="saga")
# No regularization at all
model = LogisticRegression(C=float("inf"))
Important: You should generally scale your numerical features before applying regularization, since the penalty depends on the magnitudes of the coefficients.


