Lecture 6: Hyperparameter optimization

Varada Kolhatkar

Focus on the breath!

iClicker: CountVectorizer recap

Select all of the following statements which are TRUE.

    1. CountVectorizer learns its vocabulary during fit.
    1. With default settings, CountVectorizer preserves word order.
    1. A word seen only in a validation fold adds a new feature when that fold is transformed.
    1. In the code shown, different CV folds might have different numbers of features (columns).
    1. 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)

Recap: Dealing with text features

  • Preprocessing text to fit into machine learning models using text vectorization.
  • Bag of words representation (CountVectorizer in sklearn)

Recap: CountVectorizer input

Suppose we want to predict whether a user will like a song using its title and lyrics.

One text column \(\to\) a 1D collection of strings (Series, array, or list).

CountVectorizer().fit_transform(df["title"])  # Series, not df[["title"]]
titles = ["Blowin' in the Wind", "Dancing Queen", "Hallelujah"]
CountVectorizer().fit_transform(titles)

Multiple text columns \(\to\) a separate vectorizer for each column.

preprocessor = make_column_transformer(
    (CountVectorizer(), "title"),  # string selector --> 1D input
    (CountVectorizer(), "lyrics"),
)

Today’s big questions

  1. How do we choose settings for a complete pipeline?
  2. How do grid and random search spend a search budget?
  3. How much should we trust the winning validation score?

Recap: Parameters vs. hyperparameters

Component Learned during fit Chosen before fitting
Logistic regression Coefficients, intercept C
Decision tree Splits, leaf predictions max_depth
Bag of words Vocabulary max_features

How should we choose the hyperparameters?

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.

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.

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.

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?

Two ways to search in sklearn

Method Candidates evaluated Useful when…
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.

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.

What does the fitted search contain?

Attribute Meaning
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.

Reading search results

Illustrative results, not demo output. Vocabulary size is fixed at 100.

C gamma Mean CV accuracy Fold SD Mean fit time
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?

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.

Why sample on a log scale?

Log-uniform sampling gives each order of magnitude equal attention.

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.

Your turn: Count the fits

The demo uses 36 grid candidates, five-fold CV, and the default final refit.

  1. How many pipeline fits does grid search require?
  2. How many does random search require with n_iter=20?
  3. What do we give up by evaluating fewer candidates?

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?

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.

Final evaluation: Protect the test set

  1. Make modelling decisions using training-set CV.
  2. Select the final configuration and refit on all training data.
  3. Evaluate once on the untouched test set.

If a test result guides another modelling decision, that set is now part of development.

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.

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.

Further reading