Sub topic 10
Tuning with Cross-Validation and Grid Search
Assume you know Python, training and test sets, basic NumPy, and the earlier TF-IDF and logistic regression workflow. This chapter focuses on choosing settings without accidentally using the test set during training.
Why Tune a Pipeline?
A text classifier has hyperparameters. These are settings chosen before training, rather than learned from the data. For this workflow, important hyperparameters include:
ngram_range, which controls whether the vectorizer uses single words, word pairs, or both.min_df, which removes terms appearing in very few documents.C, which controls the strength of logistic regression regularization.- The scoring metric used to compare candidate models.
Trying one setting at a time can produce a model that works well by chance. Cross-validation gives each candidate several validation tests.
In k-fold cross-validation, the training data is divided into k parts called folds. The model trains on k - 1 folds and validates on the remaining fold. This repeats until every fold has been used for validation.
Grid Search
Grid search evaluates every combination in a predefined parameter grid. GridSearchCV performs this search with cross-validation.
Keep the final test set separate. Use only the training data in the grid search. After selecting the best settings, evaluate the refitted model once on the test data.
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import 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 = Pipeline([
("tfidf", TfidfVectorizer(stop_words="english")),
("classifier", LogisticRegression(max_iter=1000)),
])
param_grid = {
"tfidf__ngram_range": [(1, 1), (1, 2)],
"tfidf__min_df": [1, 2],
"classifier__C": [0.1, 1.0, 10.0],
}
search = GridSearchCV(
estimator=model,
param_grid=param_grid,
cv=5,
scoring="f1_macro",
n_jobs=-1,
refit=True,
)
search.fit(train.data, train.target)
print("Best parameters:", search.best_params_)
print("Best cross-validation F1:", round(search.best_score_, 3))
predictions = search.predict(test.data)
print(classification_report(
test.target,
predictions,
target_names=test.target_names,
))The double underscore in names such as tfidf__ngram_range addresses a parameter inside a pipeline step. The search tries 12 combinations: two n-gram choices, two min_df choices, and three values of C.
best_score_ is the average cross-validation score for the winning combination. Because refit=True, search then trains that pipeline again on all available training data. The test report measures its performance on data that did not guide the search.
Choosing the Scoring Metric
Accuracy can hide poor performance when one class is much larger than the others. f1_macro calculates F1 separately for each class and then gives every class equal weight. Use it when minority classes matter.
Other choices include:
| Scoring value | Useful when |
|---|---|
| `"accuracy"` | Classes have similar importance and size |
| `"f1_macro"` | Every class deserves equal attention |
| `"f1_weighted"` | You want class scores weighted by class frequency |
| `"precision_macro"` | False positives are especially costly |
| `"recall_macro"` | Missing a class is especially costly |
Practical Search Decisions
A larger grid is not automatically better. Each combination requires several model fits, so search time grows with the number of parameters and folds. Start with a small, meaningful grid. Expand it only when the results justify more computation.
Use cv=5 when the training set is reasonably large. With limited data, fewer folds may be faster, but the score can be less stable. Keep the vectorizer inside the pipeline so each fold learns its vocabulary and IDF values only from that fold's training portion.
Exercise
Why must the TF-IDF vectorizer remain inside the Pipeline during GridSearchCV?
Show answer
Each cross-validation fold must learn its vocabulary and IDF weights only from its training portion. Keeping it inside the Pipeline prevents validation text from leaking into those features.