TExcelTAD
Home › Machine Learning › ML Grid Search

ML Grid Search

Most models have settings you choose before training: the depth of a tree, the polynomial degree, the regularization strength C of logistic regression. These are called hyperparameters, to distinguish them from the parameters (coefficients, split thresholds) the model learns from data.

Good hyperparameters can make a big difference, and there is rarely a formula to compute them. The practical approach is to try several values and keep the best — a grid search.

A manual search

Let's tune C for logistic regression on the built-in wine data set (178 wines, 13 chemical measurements, 3 grape cultivars). Smaller C means stronger regularization (simpler model); larger C means the model is allowed to fit the training data more closely.

python · try it yourself
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=3, stratify=y)
scaler = StandardScaler().fit(X_train)
X_train_s, X_test_s = scaler.transform(X_train), scaler.transform(X_test)

for C in [0.001, 0.01, 0.1, 1, 10, 100]:
    model = LogisticRegression(C=C, max_iter=2000).fit(X_train_s, y_train)
    print(f"C={C:<6} train={model.score(X_train_s, y_train):.3f}  test={model.score(X_test_s, y_test):.3f}")
C=0.001  train=0.726  test=0.759
C=0.01   train=0.984  test=0.944
C=0.1    train=0.992  test=1.000
C=1      train=1.000  test=1.000
C=10     train=1.000  test=0.963
C=100    train=1.000  test=0.963

Very small C values over-simplify the model and accuracy drops. Medium values do best on the test set. With large C the model fits the training data perfectly, yet test accuracy slips slightly: a mild case of overfitting.

Warning: We just picked C by looking at the test score. Do that a lot and the test set is no longer an honest judge. Grid search solves this by using cross validation on the training set instead.

GridSearchCV

GridSearchCV tries every combination of the values you list, scores each one with k-fold cross validation (explained fully in the Cross Validation lesson) on the training data only, and finally refits the best combination on the whole training set:

python · try it yourself
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.tree import DecisionTreeClassifier

X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=3, stratify=y)

grid = {
    "max_depth": [1, 2, 3, 4, None],
    "min_samples_leaf": [1, 3, 5],
}
search = GridSearchCV(DecisionTreeClassifier(random_state=0), grid, cv=5)
search.fit(X_train, y_train)

print("combinations tried:", len(search.cv_results_["params"]))
print("best params:", search.best_params_)
print("best CV accuracy:", round(search.best_score_, 3))
print("test accuracy:   ", round(search.score(X_test, y_test), 3))
combinations tried: 15
best params: {'max_depth': 4, 'min_samples_leaf': 1}
best CV accuracy: 0.871
test accuracy:    0.87

The grid has 5 × 3 = 15 combinations, and each one is trained 5 times (once per fold): 75 fits in total. Grids grow quickly, so keep them small and sensible.

After fitting, the search object behaves like the best model: search.predict(...) and search.score(...) use search.best_estimator_.

Looking at all results

cv_results_ is a dictionary that converts nicely into a pandas table, so you can see how close the runners-up were:

python · try it yourself
import pandas as pd
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.tree import DecisionTreeClassifier

X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=3, stratify=y)
search = GridSearchCV(DecisionTreeClassifier(random_state=0),
                      {"max_depth": [1, 2, 3, 4, None], "min_samples_leaf": [1, 3, 5]}, cv=5)
search.fit(X_train, y_train)

results = pd.DataFrame(search.cv_results_)
table = results[["param_max_depth", "param_min_samples_leaf", "mean_test_score", "rank_test_score"]]
print(table.sort_values("rank_test_score").head(6).round(3).to_string(index=False))
param_max_depth  param_min_samples_leaf  mean_test_score  rank_test_score
              4                       1            0.871                1
           None                       1            0.871                1
              3                       1            0.854                3
              4                       3            0.837                4
           None                       3            0.837                4
              3                       3            0.829                6

If several combinations score about the same, prefer the simplest one (the shallowest tree, the strongest regularization).

Searching a scaled model

When a model needs scaling, the scaler must be part of what gets cross-validated — otherwise information from the validation folds leaks into the scaling. A pipeline bundles both steps; parameter names then get the step name as a prefix (logisticregression__C):

python · try it yourself
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=3, stratify=y)

pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000))
search = GridSearchCV(pipe, {"logisticregression__C": [0.001, 0.01, 0.1, 1, 10]}, cv=5)
search.fit(X_train, y_train)

print("best C:", search.best_params_["logisticregression__C"])
print("best CV accuracy:", round(search.best_score_, 3))
print("test accuracy:   ", round(search.score(X_test, y_test), 3))
best C: 10
best CV accuracy: 0.976
test accuracy:    0.963

Pipelines get their own lesson later in the course.

Tip: For large grids, RandomizedSearchCV samples a fixed number of random combinations instead of trying them all. It often finds an equally good setting in a fraction of the time.

Go further: Hyperparameter Tuning: Grid and Random Search explains why random search often wins, adds successive halving and scores the tuned model with nested cross-validation.

Test yourself

Which of these is a hyperparameter rather than a learned parameter?

  1. The coefficients of a linear regression
  2. The max_depth of a decision tree
  3. The split thresholds a tree learns
  4. The intercept

A grid has 4 values for one parameter and 3 for another, with cv=5. How many models are trained during the search (before the final refit)?

  1. 7
  2. 12
  3. 35
  4. 60

Where does GridSearchCV store the winning combination?

  1. search.best_params_
  2. search.coef_
  3. search.grid_
  4. search.winner