Sub topic 7
Regularization and choosing C
This chapter assumes you can fit a scikit-learn Pipeline with TfidfVectorizer and LogisticRegression. It also assumes you know how logistic regression turns a weighted sum of features into a probability, and that you know why a held-out set matters. The goal is to explain what the C parameter does and how to pick a value for it.
Why a text model needs regularization
A TF-IDF matrix usually has far more columns than rows. A vocabulary of 50,000 terms against 2,000 training documents is ordinary. With that many features, a linear model can almost always find weights that separate the training classes perfectly. It does this by giving large weights to rare terms that happen to occur in only one class, such as a misspelling, a username, or a single date.
Those weights fit the training set and generalize badly. Regularization counteracts this by adding a penalty for large weights. The model then has to trade fit against simplicity, and it keeps a large weight only when the evidence for it is strong.
The objective function
For binary logistic regression with weight vector w, scikit-learn minimizes this quantity:
0.5 * (w · w) + C * sum over documents of log_loss(y_i, p_i)The first term is the L2 penalty, which is half the squared length of the weight vector. The second term is the total log loss on the training documents. C multiplies the data-fit term, so it is the inverse of regularization strength:
- Small
Cmakes the penalty dominate. Weights shrink toward zero and the model is simple. - Large
Cmakes the data-fit term dominate. Weights can grow and the model fits the training set closely.
This is the opposite of the alpha or lambda convention used in Ridge and in most textbooks. Mixing the two up is a common source of confusion. In scikit-learn, C = 1 / lambda up to a constant factor.
The intercept is not penalized with the default lbfgs solver. In multiclass problems, lbfgs fits one multinomial model and the penalty covers every class's coefficients.
What the penalty does to the weights
L2 regularization shrinks all weights smoothly. It rarely sets any of them exactly to zero. Correlated terms, such as "launch" and "orbit" in a space corpus, tend to share weight instead of one winning outright. This is usually what you want for text, where many weakly informative words add up.
L1 regularization penalizes the sum of absolute weights instead. It drives many weights exactly to zero and gives a sparse model. It can pick one word from a correlated group arbitrarily, and the choice may change between training samples. Use it when you need a short list of active terms. L2 is the better default for accuracy.
| Setting | Effect on weights | Typical use |
|---|---|---|
| L2 (default) | Shrinks all weights, few exact zeros | General text classification |
| L1 | Many exact zeros, unstable among correlated terms | Feature selection, compact models |
| Elastic net | Mix of both, needs the `saga` solver | Sparse model that stays stable among correlated terms |
Underfitting and overfitting along the C axis
At very small C, the model predicts close to the class prior for every document. Both training and validation scores are low. At very large C, the training score approaches 100% while the validation score falls or stalls. The best C lies between the two, where the validation score peaks.
Search C on a logarithmic grid, such as 0.01, 0.1, 1, 10, 100. A step from 1.0 to 1.1 changes almost nothing, while a step from 1 to 10 changes a lot.
Measuring the effect
The next script compares training and validation scores for several values of C. It uses cross_validate on a pipeline, so the vectorizer is refit inside each fold and never sees the validation documents.
import numpy as np
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_validate
from sklearn.pipeline import make_pipeline
categories = ["sci.space", "rec.autos", "talk.politics.misc"]
remove = ("headers", "footers", "quotes")
train = fetch_20newsgroups(subset="train", categories=categories, remove=remove)
for C in [0.01, 0.1, 1.0, 10.0, 100.0]:
model = make_pipeline(
TfidfVectorizer(sublinear_tf=True, min_df=2, stop_words="english"),
LogisticRegression(C=C, max_iter=1000),
)
result = cross_validate(
model, train.data, train.target,
cv=5, scoring="f1_macro", return_train_score=True,
)
print(
f"C={C:<7} train={np.mean(result['train_score']):.3f} "
f"valid={np.mean(result['test_score']):.3f}"
)Expect the training score to rise steadily with C, close to 1.0 at the top of the range. The validation score should rise, flatten, and may slip slightly at the largest values. The exact numbers depend on the scikit-learn version and the data download. The shape is the point: the gap between the two columns is the overfitting you are paying for.
Watching the weights grow
You can also look at the weights directly. The script below fits the vectorizer once on the training text and tracks the length of the weight vector as C increases.
import numpy as np
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
categories = ["sci.space", "rec.autos", "talk.politics.misc"]
remove = ("headers", "footers", "quotes")
train = fetch_20newsgroups(subset="train", categories=categories, remove=remove)
vectorizer = TfidfVectorizer(sublinear_tf=True, min_df=2, stop_words="english")
X = vectorizer.fit_transform(train.data)
for C in [0.01, 0.1, 1.0, 10.0, 100.0]:
clf = LogisticRegression(C=C, max_iter=1000).fit(X, train.target)
norm = np.linalg.norm(clf.coef_)
largest = np.abs(clf.coef_).max()
print(f"C={C:<7} weight norm={norm:8.2f} largest weight={largest:7.2f}")The norm grows by roughly an order of magnitude or more across the range. That growth is the model putting more trust in individual terms. Fitting the vectorizer once is acceptable here because the script only describes weights. It is not a performance estimate. For a real estimate, keep the vectorizer inside the pipeline.
Interactions with the rest of the pipeline
The best C depends on the features, so it cannot be chosen once and reused.
- Row normalization.
TfidfVectorizerL2-normalizes each row by default, so every feature value is small, often below 0.3. Small feature values need larger weights to have an effect. For that reason TF-IDF models often preferCbetween 1 and 100, not the default of 1.0. Raw counts have larger values and usually prefer smallerC. - Sublinear TF and n-grams. Switching on
sublinear_tfor adding bigrams changes the number and scale of features, which moves the bestC. Tunengram_rangeandCtogether, as in the grid search in the tuning chapter. - Vocabulary size. A larger vocabulary, from a lower
min_dfor a widerngram_range, gives more room to overfit and usually favors a smallerC. - Class weights. With
class_weight="balanced", minority-class errors count for more in the data-fit term. This changes the effective balance against the penalty, so re-tuneCafter changing weights.
Practical gotchas
- Convergence warnings at large C. Large
Cmakes the optimization harder. If you see aConvergenceWarning, raisemax_iter, for example to 1000 or 5000, or trysolver="saga"or"liblinear". Do not ignore the warning, because the reported weights may not be the optimum. - Probabilities become overconfident. At large
C, the model pushes predicted probabilities toward 0 and 1. If you usepredict_probafor thresholds or ranking, a moderateCoften gives better calibrated outputs. Check calibration separately if the probabilities matter. - Never tune on the test set. Choose
Cwith cross-validation on training data, then score the test set once at the end. - Pick the simpler model on ties. If
C=1andC=10have validation scores within the noise, prefer the smallerC. It is more stable, and its weights are easier to interpret. - Use a sensible metric. Pick the scoring function that matches your goal, for example
f1_macrowhen classes are uneven. Accuracy can hide a poor minority-class result. - Use
LogisticRegressionCVas a shortcut. It searches a list ofCvalues with cross-validation. It is fast and handy, but it cannot tune vectorizer parameters. UseGridSearchCVon a pipeline when you want to tune both.
Choosing a search range
A sensible workflow is short:
- Start with a coarse logarithmic grid, such as
[0.01, 0.1, 1, 10, 100]. - Find the best value and check whether it sits at an edge of the grid. If it does, extend the grid in that direction, because the real optimum may lie beyond.
- Refine with a few values around the winner, such as
[3, 10, 30]. - Check the gap between training and validation scores at the chosen value. A very large gap suggests that you need a smaller
Cor fewer features. A tiny gap with low scores suggests underfitting, so try a largerCor richer features.
Exercise
A colleague trains LogisticRegression(C=0.001) on TF-IDF features. Training F1 is 0.55 and validation F1 is 0.54. Should they raise or lower C, and why?
Show answer
Raise C. The scores are low and almost equal, which is the signature of underfitting. C is the inverse of regularization strength, so a value of 0.001 applies a very strong penalty and keeps the weights near zero. Increasing C, for example to 1, 10, and 100, lets the model use its features, and the validation score should rise.
Exercise
In a grid search over C = [0.1, 1, 10, 100], the best cross-validated score is at C=100, the last value in the grid. What should you do next, and why?
Show answer
Extend the grid upward, for example to 300 and 1000, and rerun. A best value at the edge means the true optimum may lie beyond the grid. If the score keeps rising, keep extending. If it drops after a larger value, you have bracketed the peak. Then refine around it, and prefer a smaller C if scores are within noise.