Sub topic 7
Regularization and Choosing `C`
Assume you know the basics of supervised learning, training and test sets, TF-IDF features, and logistic regression. This chapter focuses on how regularization controls model complexity and how to choose the logistic regression parameter C.
Why regularization matters
A TF-IDF vector can contain thousands of features. Most documents use only a small fraction of those features, so the feature matrix is sparse. A flexible classifier can assign large weights to rare words that happen to occur in the training data.
This behavior is called overfitting. An overfit model performs well on training documents but poorly on new documents.
Regularization adds a penalty for large model weights. The penalty encourages the model to use smaller, more stable coefficients. The model then gives up some training accuracy when that improves performance on unseen data.
For logistic regression with L2 regularization, the training objective has this general form:
\text{loss} + \lambda \sum_j w_j^2Here, \(w_j\) is a feature weight and \(\lambda\) controls the penalty. Larger values of \(\lambda\) produce stronger regularization.
Scikit-learn exposes the inverse of this value as C:
| `C` value | Regularization strength | Typical effect |
|---|---|---|
| Small | Strong | Smaller coefficients, simpler model |
| Large | Weak | Larger coefficients, more flexible model |
Therefore, a small C does not mean “less regularization.” It means stronger regularization.
How `C` changes the model
The following diagram shows the trade-off:
The best value is usually between these extremes. You should not choose it from training accuracy alone. Instead, compare candidate values using validation data or cross-validation.
Regularization is also useful when several words carry similar information. Without a penalty, the model may assign unstable weights to correlated features. L2 regularization usually spreads influence across them more smoothly.
Choosing `C` with cross-validation
A common approach is to test values across several orders of magnitude. For example, [0.01, 0.1, 1, 10, 100] covers increasingly flexible models.
Use a pipeline so that TF-IDF fitting happens separately inside each cross-validation fold. Otherwise, information from the validation fold could influence the vocabulary or inverse document frequency values.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import make_pipeline
documents = [
"the telescope observed a distant galaxy",
"the spacecraft entered orbit around the planet",
"the engine needs a new fuel filter",
"the car engine has a transmission problem",
"astronomers studied a bright star",
"the mechanic replaced the vehicle battery",
]
labels = [
"space",
"space",
"autos",
"autos",
"space",
"autos",
]
model = make_pipeline(
TfidfVectorizer(ngram_range=(1, 2)),
LogisticRegression(max_iter=1000),
)
search = GridSearchCV(
estimator=model,
param_grid={
"logisticregression__C": [0.01, 0.1, 1, 10, 100],
},
cv=3,
scoring="f1_macro",
)
search.fit(documents, labels)
print("Best C:", search.best_params_["logisticregression__C"])
print("Best validation F1:", round(search.best_score_, 3))The parameter name contains the pipeline step name, logisticregression, followed by two underscores and the classifier parameter, C.
Reading the validation results
GridSearchCV stores the result for every candidate in cv_results_. Comparing these scores helps you see whether the model is sensitive to C.
for c, score in zip(
search.cv_results_["param_logisticregression__C"],
search.cv_results_["mean_test_score"],
):
print(f"C={c}: macro F1={score:.3f}")If scores improve as C increases, the model may still be too constrained. If scores peak at a middle value and then fall, larger values are probably overfitting. If all values perform similarly, C is not a major source of error for this dataset.
Practical decisions
Start with logarithmically spaced values rather than many closely packed values. The useful scale can vary greatly between datasets.
Also consider the solver and convergence. Strong regularization or a very large feature matrix can require more iterations. If scikit-learn reports that the solver did not converge, increase max_iter before interpreting the score.
Exercise
A model has training macro F1 of 0.98 and validation macro F1 of 0.61. Should you try increasing or decreasing C first?
Show answer
Try decreasing C. That increases regularization and may reduce overfitting, although cross-validation should decide whether the change helps.