🎓 A1Learner
🔍
0 of 50 lessons completed

Python ML Hyperparameter Tuning

A hyperparameter is a setting you choose before training, like the depth of a tree. Tuning is the search for the setting that scores best on the training folds.

Grid search tries every combination

The grid tries three depths and two leaf sizes, which is six combinations. The best depth is 3 with a leaf size of 5.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42)
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier
grid = GridSearchCV(DecisionTreeClassifier(random_state=42), {'max_depth': [2, 3, 5], 'min_samples_leaf': [1, 5]}, cv=5)
grid.fit(X_train, y_train)
print(grid.best_params_)
print(round(grid.best_score_, 3))

Random search tries a sample

RandomizedSearchCV tries 6 random combinations from a wider grid. It finds the same best depth of 3 here.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42)
from sklearn.model_selection import RandomizedSearchCV
from sklearn.tree import DecisionTreeClassifier
search = RandomizedSearchCV(DecisionTreeClassifier(random_state=42), {'max_depth': [2, 3, 5, 8, None], 'min_samples_leaf': [1, 2, 5, 10]}, n_iter=6, cv=5, random_state=42)
search.fit(X_train, y_train)
print(search.best_params_)
print(round(search.best_score_, 3))

Check the winner on the test set

score() runs the tuned grid model on the held-out test rows. The test accuracy is 0.947, close to the best training-fold score.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42)
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier
grid = GridSearchCV(DecisionTreeClassifier(random_state=42), {'max_depth': [2, 3, 5], 'min_samples_leaf': [1, 5]}, cv=5)
grid.fit(X_train, y_train)
print(round(grid.score(X_test, y_test), 3))

Example

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV, train_test_split
from sklearn.tree import DecisionTreeClassifier
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42)
grid = GridSearchCV(DecisionTreeClassifier(random_state=42), {"max_depth": [2, 3, 5], "min_samples_leaf": [1, 5]}, cv=5)
grid.fit(X_train, y_train)
print("Grid best params:", grid.best_params_)
print("Grid best score:", round(grid.best_score_, 3))
print("Grid test accuracy:", round(grid.score(X_test, y_test), 3))
search = RandomizedSearchCV(DecisionTreeClassifier(random_state=42), {"max_depth": [2, 3, 5, 8, None], "min_samples_leaf": [1, 2, 5, 10]}, n_iter=6, cv=5, random_state=42)
search.fit(X_train, y_train)
print("Random best params:", search.best_params_)
print("Random best score:", round(search.best_score_, 3))
print("Random test accuracy:", round(search.score(X_test, y_test), 3))

Key points

  • Hyperparameter: a setting chosen before training, not learned from the data
  • GridSearchCV: a search that tries every combination in a grid
  • RandomizedSearchCV: a search that tries a random sample of combinations
  • Use best_params_ to read the winning settings after a search
  • Use best_score_ to read the best mean score across the training folds
  • Tune on the training folds only. The test set stays untouched until the end.
  • Use n_iter to set how many random combinations RandomizedSearchCV tries

In this example, the breast cancer table supplies the rows, and the label is benign or malignant. The final check runs on the 20 percent the split held back. GridSearchCV tries six combinations of depth and leaf size on the training folds only. Its best settings are max_depth 3 and min_samples_leaf 5, with a best score of 0.934. RandomizedSearchCV tries six random combinations and finds max_depth 3 with min_samples_leaf 2, with a best score of 0.93. Both tuned models score 0.947 on the test rows.

Note

A tuned model can still overfit the training folds, so the test score is the final check.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Where does hyperparameter tuning happen?