Every model has settings you choose before training: the number of trees in a forest, k in KNN, C and gamma in an SVM. These are hyperparameters, and good values can make the difference between a mediocre model and a strong one. Instead of guessing, you can let scikit-learn try many combinations, score each one with cross-validation, and keep the best. This lesson covers GridSearchCV and the faster RandomizedSearchCV.
In this lesson you will learn
- The difference between parameters and hyperparameters
- Exhaustive search with
GridSearchCV - Tuning steps inside a pipeline with the
step__paramsyntax - Random search with
RandomizedSearchCV - Keeping a final test set untouched
This lesson builds on cross-validation and SVMs.
Grid Search
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
pipe = Pipeline([("scale", StandardScaler()), ("svm", SVC())])
param_grid = {
"svm__C": [0.1, 1, 10, 100],
"svm__gamma": [0.001, 0.01, 0.1],
}
search = GridSearchCV(pipe, param_grid, cv=5, scoring="accuracy")
search.fit(X_train, y_train)
print("Combinations tried:", len(search.cv_results_["params"]))
print("Best parameters:", search.best_params_)
print(f"Best cross-validation accuracy: {search.best_score_:.3f}")
print(f"Test accuracy of the best model: {search.score(X_test, y_test):.3f}")
Output
Combinations tried: 12
Best parameters: {'svm__C': 10, 'svm__gamma': 0.001}
Best cross-validation accuracy: 0.977
Test accuracy of the best model: 0.979
- Parameters are learned from data during
fit, such as regression weights. Hyperparameters are chosen by you before training. - The grid lists 4 values of
Cand 3 ofgamma, soGridSearchCVtries all 12 combinations. Withcv=5, that is 60 training runs. - Because the SVM sits inside a pipeline step named
"svm", its settings are writtensvm__Candsvm__gamma(two underscores). - After the search, the best combination is refitted on the whole training set automatically, so
search.scoreandsearch.predictuse the best model. - The test set was never used during tuning, so its score of 97.9% is an honest estimate of performance on new data.
Random Search
from scipy.stats import randint
from sklearn.datasets import load_wine
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import RandomizedSearchCV
X, y = load_wine(return_X_y=True)
param_dist = {
"n_estimators": randint(50, 300),
"max_depth": [None, 3, 5, 8],
"min_samples_leaf": randint(1, 6),
"max_features": ["sqrt", "log2"],
}
search = RandomizedSearchCV(
RandomForestClassifier(random_state=0), param_dist,
n_iter=15, cv=5, random_state=0, n_jobs=1,
)
search.fit(X, y)
print("Best parameters:", search.best_params_)
print(f"Best CV accuracy: {search.best_score_:.3f}")
# Top 3 settings from the search results
results = sorted(zip(search.cv_results_["mean_test_score"], search.cv_results_["params"]),
key=lambda r: -r[0])[:3]
for score, params in results:
print(f"{score:.3f} depth={params['max_depth']}, leaf={params['min_samples_leaf']}, "
f"trees={params['n_estimators']}")
Output
Best parameters: {'max_depth': None, 'max_features': 'log2', 'min_samples_leaf': 1, 'n_estimators': 117}
Best CV accuracy: 0.978
0.978 depth=None, leaf=1, trees=117
0.972 depth=3, leaf=1, trees=59
0.967 depth=5, leaf=1, trees=190
- A full grid grows multiplicatively: four settings with five values each is 625 combinations.
RandomizedSearchCVinstead samples a fixed number of combinations, here 15. - Settings can be lists, or distributions such as
randint(50, 300), so the search can try values you would never have typed into a grid. - Research and practice show that random search usually finds settings as good as a grid in far fewer tries, because only a few hyperparameters tend to matter much.
cv_results_stores every combination’s scores, which helps you see which settings matter. Here, every top result used a minimum leaf size of 1, while the best depth varied, so leaf size mattered more than depth.
Choosing a Search Method
| Method | How it works | Use when |
|---|---|---|
GridSearchCV | Tries every combination | Few hyperparameters with a handful of values each |
RandomizedSearchCV | Samples a fixed number of combinations | Many hyperparameters or wide ranges |
HalvingGridSearchCV | Gives more data only to promising candidates | Large datasets and slow models |
| Bayesian tools (e.g. Optuna) | Uses earlier results to pick the next try | Expensive models such as deep networks |
A good habit is to start with a coarse search on a log scale (0.01, 0.1, 1, 10, 100), then search more finely around the best value.
Common Mistakes
- Tuning on the test set, which makes the final test score too optimistic. Tune with cross-validation on training data only.
- Scaling outside the search, which leaks information across folds; put preprocessing in the pipeline.
- Huge grids that run for hours; use random search first.
- Reporting
best_score_as the final result; it is slightly biased upwards because it was used for selection.
Practice Exercises
Exercise 1. Tune n_neighbors (1 to 30) and weights (“uniform”, “distance”) for KNN on the wine data.
Show answer
from sklearn.datasets import load_wine
from sklearn.model_selection import GridSearchCV
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_wine(return_X_y=True)
pipe = Pipeline([("scale", StandardScaler()), ("knn", KNeighborsClassifier())])
grid = {"knn__n_neighbors": range(1, 31), "knn__weights": ["uniform", "distance"]}
search = GridSearchCV(pipe, grid, cv=5).fit(X, y)
print(search.best_params_, round(search.best_score_, 3))
Exercise 2. A grid has 5 values of C, 4 of gamma and 2 kernels, with 10-fold cross-validation. How many models are trained, including the final refit?
Show answer
5 × 4 × 2 = 40 combinations × 10 folds = 400 fits, plus 1 refit of the best model: 401.
Frequently Asked Questions
How can I make the search faster?
Set n_jobs=-1 to use all CPU cores, use random or halving search, reduce the number of folds while exploring, and tune on a sample of the data before the final run.
Which scoring should I use?
Whatever matches your goal: "f1" or "average_precision" for imbalanced classes, "neg_root_mean_squared_error" for regression. Accuracy is only sensible for balanced classes.
Summary
- Hyperparameters are set before training; search finds good values.
GridSearchCVtries everything;RandomizedSearchCVsamples.- Use
step__paramnames to tune pipeline steps. - Keep the test set out of tuning and check it only once at the end.
