Sub topic 10
Tuning with cross-validation and grid search
This chapter assumes you can build the TF-IDF plus logistic regression Pipeline from the previous chapters. You should also know what a train/test split is, what ngram_range and C do, and how to read a classification report. Here you will tune those settings without leaking validation data and without overfitting the test set.
Why a single split is not enough
Every setting you have met so far is a hyperparameter. A hyperparameter is a value you choose before training, such as ngram_range, min_df, or C. The model does not learn it from the data.
Suppose you try ten settings and keep the one with the best score on the test set. That score is now optimistic. The test set helped you choose, so it no longer measures how the model behaves on new text. This is selection bias, and the effect grows with the number of settings you try.
A second problem is noise. One validation split of a few hundred documents gives a score that shifts when you reshuffle the data. A difference of 0.01 in F1 may be luck.
Cross-validation addresses both problems. You keep the test set locked away. You compare settings using only the training data, and you average several validation scores to reduce noise.
How k-fold cross-validation works
In k-fold cross-validation, you split the training data into k parts called folds. For each fold, you train on the other k-1 folds and score on the held-out fold. You then average the k scores.
Five folds is a common default. More folds give each model more training data and a less biased estimate, but they cost more time. Ten folds is also common. For text with large vocabularies, the cost matters, because each fold refits the vectorizer.
Stratified folds
For classifiers, scikit-learn uses StratifiedKFold by default when you pass an integer cv. It keeps the class proportions about the same in every fold. This matters when one class is rare. Plain KFold could produce a fold with almost no examples of that class, and the metric for that fold would be unreliable.
Why the whole pipeline must be cross-validated
Look at what the vectorizer learns during fit. It learns the vocabulary and the IDF values. The IDF of a term depends on how many documents contain it, so these are statistics of the data.
Consider this tempting but wrong approach:
- Fit
TfidfVectorizeron the whole training set. - Turn the text into a matrix
X. - Run cross-validation on
Xwith a classifier.
In every round, the validation fold has already influenced the vocabulary and the IDF values. The leak is small for TF-IDF, but it is real, and it makes scores slightly optimistic. With a supervised step such as feature selection by chi-squared score, the leak can be large.
The fix is to put the vectorizer inside the Pipeline and give the pipeline to the search object. For each fold, scikit-learn then fits the vectorizer on the training folds only and applies it to the validation fold.
GridSearchCV on a pipeline
GridSearchCV takes an estimator, a grid of parameter values, and a cross-validation setting. It tries every combination, scores each with cross-validation, and records the results.
First, rebuild the pipeline and data from the earlier chapter.
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
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)
test = fetch_20newsgroups(subset="test", categories=categories, remove=remove)
model = make_pipeline(
TfidfVectorizer(sublinear_tf=True, ngram_range=(1, 2), min_df=2, stop_words="english"),
LogisticRegression(C=1.0, max_iter=1000),
)Now run the search.
from sklearn.model_selection import GridSearchCV
param_grid = {
"tfidfvectorizer__ngram_range": [(1, 1), (1, 2)],
"logisticregression__C": [0.1, 1.0, 10.0],
}
search = GridSearchCV(model, param_grid, cv=5, scoring="f1_macro", n_jobs=-1)
search.fit(train.data, train.target)
print(search.best_params_)
print(round(search.best_score_, 3))The code works as follows.
- The keys in
param_gridfollow the patternstepname__parametername, with two underscores.make_pipelinenames each step with its lowercase class name, so the vectorizer istfidfvectorizerand the classifier islogisticregression. - The grid has 2 n-gram ranges and 3 values of
C, so 6 combinations. Withcv=5, scikit-learn fits 30 models, plus one final refit. scoring="f1_macro"averages the F1 score of each class with equal weight. It is a sound choice when you care about every class, and it is covered further in the chapter on class imbalance.n_jobs=-1runs the fits in parallel on all CPU cores.best_score_is the mean cross-validated score of the best combination. It is not a test score.
By default refit=True. After the search, scikit-learn refits the best combination on the whole training set and stores it in search.best_estimator_. You can call search.predict(...) directly.
Checking the search results
Do not look only at best_params_. The cv_results_ attribute holds the mean and spread of the score for every combination, and a table makes it readable.
import pandas as pd
results = pd.DataFrame(search.cv_results_)
columns = [
"param_tfidfvectorizer__ngram_range",
"param_logisticregression__C",
"mean_test_score",
"std_test_score",
"rank_test_score",
]
print(results[columns].sort_values("rank_test_score").round(3).to_string(index=False))Two things to look for:
- The standard deviation. If the top two combinations differ by less than
std_test_score, the data cannot tell them apart. In that case prefer the simpler one: a smaller n-gram range, a smaller vocabulary, or a stronger penalty (smallerC). - The edges of the grid. If the best
Cis the largest or smallest value you tried, the true optimum may lie outside the grid. Extend the grid in that direction and search again.
Using the test set once
After you choose settings, score the refit model on the test set a single time.
from sklearn.metrics import classification_report
pred = search.predict(test.data)
print(classification_report(test.target, pred, target_names=test.target_names))The test score should be close to best_score_. A test score much lower than the cross-validated score points to a problem. Common causes are a distribution shift between train and test, duplicate documents that appear in both train folds and validation folds, or a very large grid that overfit the validation folds.
If the test result disappoints, resist the urge to adjust the grid and re-score. Each repeat uses the test set as a validation set and weakens the estimate. If you need to iterate, collect a fresh holdout or use nested cross-validation, which runs an outer loop for evaluation and an inner search loop for tuning.
Choosing a scoring metric
The scoring argument decides what "best" means. The right choice depends on the task.
| Scoring value | What it measures | When to use it |
|---|---|---|
| `accuracy` | Fraction of correct predictions | Classes are balanced and all errors cost the same |
| `f1_macro` | Unweighted mean of per-class F1 | Every class matters equally, including small ones |
| `f1_weighted` | Mean of per-class F1, weighted by class size | You care about overall performance and accept that big classes dominate |
| `precision_macro` or `recall_macro` | Mean per-class precision or recall | One kind of error is clearly more costly |
| `neg_log_loss` | Quality of predicted probabilities | You use the probabilities, not only the labels |
You can pass several metrics as a list and set refit to the name of the one used to choose the final model. For example, scoring=["accuracy", "f1_macro"], refit="f1_macro".
Controlling the cost of a search
Grid search cost multiplies. The number of fits is the product of all grid sizes, times the number of folds. Adding a third parameter with four values to the grid above raises 30 fits to 120.
Several habits keep the cost manageable.
- Cache the vectorizer. The vectorizer is refit for every combination, even when only
Cchanges. Passmemoryto the pipeline, for examplemake_pipeline(..., memory="cache_dir"), so the fitted vectorizer is reused when its own parameters are unchanged. - Search coarsely, then finely. Try
Con a logarithmic scale, such as 0.01, 0.1, 1, 10, 100. Once you find the best region, run a second search with finer steps inside it. - Use randomized search for many parameters.
RandomizedSearchCVsamples a fixed number of combinations from distributions. With many parameters it often finds a comparable result at a fraction of the cost. - Limit the vocabulary. Raising
min_dfor settingmax_featuresmakes every fit faster, because the matrix has fewer columns.
A sketch of a randomized search follows.
from scipy.stats import loguniform
from sklearn.model_selection import RandomizedSearchCV
param_dist = {
"tfidfvectorizer__ngram_range": [(1, 1), (1, 2), (1, 3)],
"tfidfvectorizer__min_df": [1, 2, 5],
"logisticregression__C": loguniform(1e-2, 1e2),
}
random_search = RandomizedSearchCV(
model, param_dist, n_iter=12, cv=5, scoring="f1_macro", n_jobs=-1, random_state=0
)
random_search.fit(train.data, train.target)
print(random_search.best_params_)The loguniform distribution samples C evenly on a log scale, which matches how C behaves. A change from 0.01 to 0.1 matters about as much as a change from 1 to 10.
Common errors
| Error | Symptom | Fix |
|---|---|---|
| Vectorizer fit outside the pipeline | CV score higher than the test score | Put the vectorizer in the pipeline and search the pipeline |
| Wrong parameter name | `ValueError: Invalid parameter` | Run `model.get_params().keys()` and copy the exact name |
| Tuning on the test set | Great test score, poor results in production | Tune with CV on the training set, score the test set once |
| Best value at the grid edge | `best_params_` shows the smallest or largest value you tried | Extend the grid in that direction |
| Accuracy used on imbalanced data | High score, rare class ignored | Use `f1_macro` or a per-class metric |
| `ConvergenceWarning` for large `C` | Solver stops before converging | Raise `max_iter`, or reduce the largest `C` |
Summary of the workflow
- Split off a test set and do not touch it.
- Build a pipeline that contains every data-dependent step.
- Define a grid on a sensible scale and pick a metric that fits the task.
- Run
GridSearchCVorRandomizedSearchCVon the training data. - Read
cv_results_, check the spread and the grid edges, and prefer simpler settings when scores tie. - Score the refit model on the test set once.
Exercise
A colleague fits TfidfVectorizer on all training documents, converts them to a matrix X, and then runs GridSearchCV with a LogisticRegression on X, searching only C. Their cross-validated F1 is 0.91, but the test F1 is 0.88. Name the flaw, explain why it can inflate the CV score, and give the fix. Then say how many model fits a search over 4 values of C and 3 values of ngram_range makes with cv=5, not counting the final refit.
Show answer
The flaw is data leakage from fitting the vectorizer outside the cross-validation loop. The vocabulary and IDF values were computed using documents that later serve as validation folds, so the validation folds are not truly unseen. This makes the CV score slightly optimistic. The fix is to put the vectorizer and classifier in one Pipeline and pass the pipeline to GridSearchCV, so each fold fits the vectorizer on its training folds only. The grid has 4 x 3 = 12 combinations, and with 5 folds the search makes 12 x 5 = 60 fits.
Exercise
After a grid search, the best value of C is 100, the largest value in your grid [0.01, 0.1, 1, 10, 100]. The top two combinations have mean scores of 0.842 and 0.839, with a standard deviation of 0.015 across folds. What do you do next, and which combination do you prefer if you cannot get more data?
Show answer
Extend the grid upward, for example to 1000, and rerun, because a best value at the edge suggests the optimum may lie beyond it. The 0.003 gap between the top two is far smaller than the 0.015 standard deviation, so the data cannot separate them. Prefer the simpler combination, which is the one with the stronger regularization (smaller C) or the smaller n-gram range, since it is less likely to be overfitting.