Lecture 6: Hyperparameter optimization
iClicker: CountVectorizer recap
Select all of the following statements which are TRUE.
CountVectorizer learns its vocabulary during fit.
With default settings, CountVectorizer preserves word order.
A word seen only in a validation fold adds a new feature when that fold is transformed.
In the code shown, different CV folds might have different numbers of features (columns).
Within a CV fold, the training and validation matrices use the same vocabulary and column order.
# Assume `X_train` is a Series of raw text documents.
pipe = make_pipeline(CountVectorizer(), SVC())
cross_validate(pipe, X_train, y_train)
Correct answers: A, D, E .
A: True. The vocabulary is learned from the documents passed to fit.
B: False. Default unigram bag-of-words counts discard word order.
C: False. transform ignores words outside the fitted vocabulary; it does not add columns.
D: True. Cross-validation fits a fresh pipeline on each training fold. Different training documents can produce different vocabularies and therefore different numbers of columns. The number of columns need not differ in every fold.
E: True. Within each fold, the fitted vectorizer transforms both training and validation documents using the vocabulary and column order learned from that fold’s training documents.
Imports: from sklearn.pipeline import make_pipeline, from sklearn.feature_extraction.text import CountVectorizer, from sklearn.svm import SVC, and from sklearn.model_selection import cross_validate.
Recap: Dealing with text features
Preprocessing text to fit into machine learning models using text vectorization.
Bag of words representation (CountVectorizer in sklearn)
Last time we turned text into numerical features. In bag of words, each vocabulary term becomes a feature, and an example is represented by counts or indicators of those terms. Today we will tune the text representation and model settings together, keeping both inside cross-validation.
Today’s big questions
How do we choose settings for a complete pipeline ?
How do grid and random search spend a search budget ?
How much should we trust the winning validation score ?
We will use slides to explain the choices and a live notebook to run the searches. Keep the central puzzle in mind: does a higher validation score after more trials necessarily mean a better model?
Recap: Parameters vs. hyperparameters
Logistic regression
Coefficients, intercept
C
Decision tree
Splits, leaf predictions
max_depth
Bag of words
Vocabulary
max_features
How should we choose the hyperparameters?
A search compares models fitted under different settings. The vocabulary is learned from training documents; its maximum size is a setting we choose. We have already compared tree depths with loops and validation scores.
Hyperparameter search
You have already done this with a for loop! For classification with numeric features:
C_vals = [0.01 , 0.1 , 1 , 10 ] # Define a parameter space.
scores = {}
for C in C_vals: # Iterate through possible values.
pipe = make_pipeline(StandardScaler(), SVC(C= C))
cv_results = cross_validate(pipe, X_train, y_train, cv= 5 ,
scoring= "accuracy" ) # Evaluate with CV.
scores[C] = cv_results["test_score" ].mean()
# Select best C
best_C = max (scores, key= scores.get)
What if we also want to tune gamma? What becomes harder as we add more hyperparameters?
Today: grid search and randomized search automate this process and systematically explore combinations of hyperparameters.
Here X_train is a DataFrame or 2D array of numeric features. Import StandardScaler from sklearn.preprocessing. Recall choosing a tree depth with a loop: this is the same workflow, now tuning the SVM’s C. Each call to cross_validate fits the entire pipeline independently within each training fold, including the scaler’s means and standard deviations. test_score is scikit-learn’s name for the held-out CV validation score; the test set is not used.
The loop selects C but does not fit a final model on all training data. More hyperparameters would require more loops and bookkeeping. GridSearchCV automates evaluating combinations, recording scores, selecting settings, and refitting. We still choose the search space and evaluation procedure.
From the loop to GridSearchCV
Same numeric data, pipeline, candidate values, and five-fold CV:
pipe = make_pipeline(StandardScaler(), SVC())
search = GridSearchCV(
pipe, param_grid= {"svc__C" : C_vals},
cv= 5 , scoring= "accuracy" ,
)
search.fit(X_train, y_train)
search.best_params_
It records the scores, selects C, and refits the selected pipeline on all training data .
To tune gamma too, add another entry to param_grid.
Import GridSearchCV from sklearn.model_selection. This evaluates the same C values as the loop using the same default CV splits. Unlike the loop, the search refits by default. svc__C identifies C inside the pipeline’s SVC step; we unpack this naming convention shortly.
Choosing a candidate pipeline
Our demo predicts whether a listener likes a song .
Inputs: song-title text plus numerical, categorical, and binary song features.
Target: whether this listener likes the song (like/dislike).
We will tune a pipeline with:
Preprocessing for numerical, categorical, binary, and text features.
An RBF SVM classifier.
The settings interact: changing the representation can change which model settings work well .
The Spotify target describes one listener’s preference, not universal song quality. The earlier title-and-lyrics example was hypothetical; this demo uses song titles alongside other song features, rather than lyrics. We omit artist identity. In the notebook, point out the actual numerical feature names when inspecting the data. The notebook constructs the column transformer and compares a most-frequent baseline with the default SVC using CV. Keep all preprocessing inside the searched pipeline.
Why does tuning get expensive?
The demo tries every combination of:
3 vocabulary sizes (max_features): 10, 100, 400.
4 regularization settings (C): 0.01, 0.1, 1, 10.
3 RBF kernel settings (gamma): 0.001, 0.01, 0.1.
How many model fits does five-fold cross-validation require?
\[3 \times 4 \times 3 = 36\text{ candidate pipelines}\] \[36 \times 5 = 180\text{ CV fits}\]
More combinations and more folds mean more fits.
Each CV fit trains the entire pipeline, including preprocessing. The 180 fits exclude the final refit of the selected pipeline on all training data (181 fits in total with refit=True). With five hyperparameters and ten values each, there are 100,000 candidates and 500,000 CV fits. Automation alone does not reduce this cost if it evaluates the same candidates and folds.
Demo 1: Data, pipeline, and baseline
Class Demo
Run Section 1 :
Reserve the test set.
Inspect the Spotify data and preprocessing pipeline.
Compare the dummy and default SVC baselines.
Which rows may the scaler and vocabulary learn from in each CV fold?
Run Section 1 only, then return to slides. Each transformer may learn only from the fold’s training portion. The pipeline is what enforces this. CountVectorizer receives the string column selector song_title; other transformers receive lists of columns.
Two ways to search in sklearn
GridSearchCV
Every specified combination
We have a small set of combinations to compare
RandomizedSearchCV
A fixed number of sampled combinations
We want to explore a larger space within a budget
Both use CV on training data , select a candidate, and by default refit on all training data .
Neither guarantees the best possible settings on future data. Both support parallel execution. We choose the pipeline, parameter space, CV procedure, scoring metric, and computational budget.
Naming pipeline hyperparameters
pipe_svm = make_pipeline(preprocessor, SVC())
svc__C: pipeline step \(\to\) setting (the SVM’s C).
For the vocabulary limit, go one level deeper:
columntransformer__countvectorizer__max_features
Pipeline step \(\to\) transformer \(\to\) setting
Use step__parameter , nesting further when needed.
These names come from make_pipeline and make_column_transformer. Inspect pipe_svm.get_params() to find available keys. The double underscores navigate through the pipeline’s structure.
How to use grid search
param_grid = {
"columntransformer__countvectorizer__max_features" :
[10 , 100 , 400 ],
"svc__gamma" : [0.001 , 0.01 , 0.1 ],
"svc__C" : [0.01 , 0.1 , 1 , 10 ],
}
grid_search = GridSearchCV(
pipe_svm, param_grid, cv= 5 , scoring= "accuracy" ,
n_jobs=- 1 , return_train_score= True ,
)
grid_search.fit(X_train, y_train)
Exhaustive within this grid , including preprocessing in every fit.
This is the notebook’s grid. n_jobs=-1 uses all available CPU cores; it can reduce elapsed time while increasing memory use. return_train_score=True requests training scores for diagnosis. refit=True is the default. All code on slides is illustrative; execution and outputs live in the notebook.
What does the fitted search contain?
best_params_
Selected settings
best_score_
Winning mean CV validation score
best_estimator_
Selected pipeline refitted on all training data
cv_results_
Scores and timings for all candidates
mean_test_score in cv_results_ refers to CV validation folds.
It is not a score on our reserved test set.
The search object can predict directly after refitting. Training scores help diagnose fitting behaviour; std_test_score describes fold variation, not a confidence interval for future accuracy. In the demo, inspect the compact table rather than the whole results dictionary.
Reading search results
Illustrative results, not demo output. Vocabulary size is fixed at 100.
0.1
0.01
0.78
0.04
0.2 s
1
0.01
0.82
0.03
0.3 s
10
0.1
0.821
0.05
3.0 s
Would you choose a much slower model for a tiny score improvement?
These invented values illustrate the columns in cv_results_: param_svc__C, param_svc__gamma, mean_test_score, std_test_score, and mean_fit_time. Fold SD describes variation across folds; it is not a confidence interval. A tiny difference does not establish a reliable improvement. Fit time measures training cost, not prediction latency. If choosing a simpler or faster candidate rather than the top-scoring one, make that decision using training-set CV and refit that candidate before test evaluation.
Choosing useful search ranges
For positive scale settings such as C and gamma, explore orders of magnitude .
Inspect promising regions and interactions, rather than only the winner.
If a winner lies at a boundary, consider extending that range.
Use training-set CV to guide further searches. Keep the test set reserved.
The demo heatmaps use the already-computed results, holding vocabulary size fixed in each panel. No additional fits are needed. A boundary result does not establish an optimum or guarantee that extending the range helps. Every refinement based on CV adds to model selection.
How to use random search
list_search = RandomizedSearchCV(
pipe_svm, param_distributions= param_grid, n_iter= 20 ,
cv= 5 , scoring= "accuracy" , random_state= 123 ,
n_jobs=- 1 , return_train_score= True ,
)
list_search.fit(X_train, y_train)
Sample 20 of the grid’s 36 combinations .
random_state makes candidate sampling reproducible.
n_iter counts candidates , not folds or elapsed time.
Using the same lists allows a comparison within the same search space. All-list configurations are sampled without replacement. A smaller budget can miss the grid’s winner. Random search is not inherently faster per fit; fewer candidates reduce total work.
Why sample on a log scale?
Log-uniform sampling gives each order of magnitude equal attention.
The table compares probabilities, not observed sample counts. Uniform sampling weights an interval by its width; log-uniform sampling weights its multiplicative span. Actual finite samples will vary. Neither distribution guarantees good settings: we still choose the bounds.
Sample distributions instead of lists
param_dist = {
"columntransformer__countvectorizer__max_features" :
randint(100 , 2001 ),
"svc__C" : loguniform(1e-4 , 1e4 ),
"svc__gamma" : loguniform(1e-4 , 1e4 ),
}
Pass param_dist as param_distributions to RandomizedSearchCV.
randint: integer values; the upper endpoint is excluded .
loguniform: equal-sized intervals on log scale have equal probability.
These are exactly the demo’s distribution ranges. randint includes 100 through 2000. Log-uniform assigns equal probability to tenfold intervals such as 0.01–0.1 and 0.1–1. Uniform sampling over a wide positive interval places most samples at its larger orders of magnitude. The notebook illustrates the difference with histograms. Distributions are our choices about where to search, not learned from data.
Effectiveness of random search
If one dimension matters more, a grid repeats its values while varying other dimensions.
Source: Bergstra and Bengio (2012)
The horizontal dimension matters more in the illustration. Random sampling over continuous ranges can try nine distinct values there; a three-by-three grid tries only three. We generally do not know which dimensions matter most. This does not guarantee random search wins.
Your turn: Count the fits
The demo uses 36 grid candidates , five-fold CV , and the default final refit.
How many pipeline fits does grid search require?
How many does random search require with n_iter=20?
What do we give up by evaluating fewer candidates?
Grid: 36 × 5 + 1 = 181. Random: 20 × 5 + 1 = 101. The extra fit refits the selected pipeline on all training data. Random search leaves combinations unevaluated and may miss a useful candidate. Parallelism changes elapsed time, not the fit count.
Demo 2: Run and inspect the searches
Run Sections 2 and 3 , stopping before final test evaluation.
Inspect selected settings, scores, and timings.
Compare C–gamma heatmaps at fixed vocabulary sizes (10, 100, and 400).
Try random search with lists and distributions.
Where would you spend more computation?
Pause before Section 4. Ask students to predict which regions might be useful before interpreting the heatmaps. Discuss the uniform/log-uniform plots as they appear. The distribution search uses a different space, so its score difference does not isolate the search algorithm. Return to slides before showing test accuracy.
Activity: Winning by guessing
https://forms.gle/KNmsCqF3ExCD8rEfA
How many times you tried?
What’s your best score?
More trials, higher score, better model?
Answer sheets \(\to\) candidate models; quiz questions \(\to\) validation examples.
A validation score reflects:
Predictive ability.
Variation from the particular evaluation examples. Selecting the highest score can select a candidate that benefited from favourable noise.
The winning validation score can be optimistic about new-data performance. This is optimization bias .
This selection effect is optimization bias, also called overfitting the validation set. It differs from overfitting the training examples.
Optional pizza analogy, kept off the slides: practise recipes at home (training), ask friends to taste (validation), repeatedly adjust for their ratings (selection), then serve competition judges (test). Tailoring the recipe to those friends may not generalize. Optimization bias can arise even when friends and judges come from the same population; distribution mismatch is not required.
Final evaluation: Protect the test set
Make modelling decisions using training-set CV .
Select the final configuration and refit on all training data .
Evaluate once on the untouched test set .
If a test result guides another modelling decision, that set is now part of development.
An independent evaluation must also be sufficiently large and representative. A disappointing test score should be reported honestly. If it guides further development, obtain fresh held-out evaluation for the revised model. Test accuracy may be above or below CV accuracy because evaluation samples and training sizes differ; a gap alone does not measure optimization bias.
Demo 3: Evaluate the selected model
Run Section 4 of the notebook.
selected_name = max (searches, key= lambda name: searches[name].best_score_)
selected_search = searches[selected_name]
selected_search.score(X_test, y_test)
Why might this differ from best_score_?
Choosing among searches is another selection step . Different search spaces also affect which candidates can win.
The selection uses CV only. The search’s selected pipeline is already refitted, so score can evaluate it directly. Different samples, different training sizes, and selection effects can all contribute to differences. Stop here for the core demo. Do not use the displayed test result to revise the search. The notebook’s optional extension is a separate training-only experiment.
Summary
Tune the complete pipeline within CV.
Grid search evaluates every specified combination.
Random search controls the candidate budget .
Search ranges matter; inspect more than the winning score.
Count candidates \(\times\) folds + final refit .
Selection can make the winning CV score optimistic.
Finish with an untouched test set .
Optional extensions
The core lecture ends here.
Nested CV: evaluate the whole model-selection procedure.
Adaptive searches: use intermediate or previous results to allocate computation.
These are extensions, not required for today’s core workflow.
Optional: Searches that adapt
Successive halving: begin with many candidates and small resource allocations; give more resources to promising candidates.
Bayesian optimization: use previous trial results to guide later choices.
Both require sensible search spaces and protected evaluation data.
The notebook has an optional halving extension. Early rankings with fewer examples can be noisy. Treat it as a separate training-only experiment, not an opportunity to revise choices in response to the core demo’s test score. These methods are beyond the core requirements today.