Learning path: Choose and Tune a Model: Classic Algorithms to a Saved Pipeline · Step 8 of 10
Hyperparameter Tuning with GridSearchCV and RandomizedSearchCV
Let scikit-learn try the settings for you. A random forest grid of 6 candidates (30 fits) lifts F1 from 0.558 to 0.630, and a random search of 10 out of 54 XGBoost combinations finds the same winner as the full grid, F1 0.649, in a third of the time.
What you will learn
- Tell a hyperparameter (a setting you pick) from a parameter (what the model learns)
- Search every combination with GridSearchCV and name pipeline settings as step__setting
- Search a random handful with RandomizedSearchCV and count the fits
- Send best_estimator_ to the test set once, at the very end
Before you start
- Cross-Validation: KFold and StratifiedKFold
- Pipelines and ColumnTransformer
Think about tuning a guitar. It has pegs, and every time you turn a peg the sound changes. With two pegs, three positions for one and two for the other, you can simply try all six and keep the one that sounds best. That's grid search.
Now imagine 54 possible positions. Trying every one takes ages, and the neighbours won't thank you. So you try a handful, picked at random, say ten. That's random search.
The pegs are the settings you choose before training, like a forest's max_depth. In a model they're called hyperparameters. What the model learns by itself from the data, such as the split points inside a tree or the weights of a logistic regression, are its parameters. Tuning means letting the computer try the hyperparameters and keep the ones with the best score.
What happens inside a search
A search is a loop around cross-validation. For every candidate setting it trains on four folds, scores on the fifth, repeats that five times and keeps the mean. Then it picks the candidate with the best mean score.
cv_results_; the balanced forest with no depth limit wins.The rain model at its default settings
We use Rain in Australia again (will it rain tomorrow?), but only 20,000 random days, so that every search runs in seconds. The split is the one from Train-Test Split and Data Leakage: drop Date and the leaky RISK_MM, stratify, 80/20.
import time
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.metrics import f1_score
from sklearn.model_selection import (GridSearchCV, ParameterGrid,
RandomizedSearchCV, cross_val_score, train_test_split)
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from xgboost import XGBClassifier
df = pd.read_csv("weatherAUS.csv")
df = df.dropna(subset=["RainTomorrow"])
df = df.sample(20_000, random_state=42)
drop_cols = ["Date", "RISK_MM", "RainTomorrow"]
X = df.drop(columns=drop_cols)
y = (df["RainTomorrow"] == "Yes").astype(int)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42)
print(X_train.shape, X_test.shape)
(16000, 21) (4000, 21)
16,000 days to learn from, 4,000 locked away. y is 1 for rain, so F1 measures how well we find rainy days (see Precision, Recall and F1).
The preprocessing is the two-lane recipe from Pipelines and ColumnTransformer, with a random forest at the end of the line:
num_cols = X.select_dtypes(include="number").columns
cat_cols = X.select_dtypes(exclude="number").columns
num = Pipeline([("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler())])
cat = Pipeline([("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore"))])
preprocess = ColumnTransformer([("num", num, num_cols),
("cat", cat, cat_cols)])
model = Pipeline([
("preprocess", preprocess),
("clf", RandomForestClassifier(random_state=42)),
])
f1s = cross_val_score(model, X_train, y_train,
cv=5, scoring="f1")
print("default F1:", round(f1s.mean(), 3))
default F1: 0.558
Five-fold F1 of 0.558. That's the number to beat.
GridSearchCV tries every combination
You describe the menu as a dictionary: each setting and the values to try.
param_grid = {
"clf__max_depth": [5, 10, None],
"clf__class_weight": [None, "balanced"],
}
grid = GridSearchCV(
model, param_grid, cv=5, scoring="f1",
n_jobs=-1, verbose=1)
grid.fit(X_train, y_train)
print("fits:", 6 * 5)
Fitting 5 folds for each of 6 candidates, totalling 30 fits
fits: 30
Three depths times two class weights is six candidates. Six candidates times five folds is 30 fits. n_jobs=-1 uses every CPU core, and verbose=1 prints that first line.
Why clf__max_depth?
The forest isn't the model we pass in; the whole pipeline is. Inside it, the forest sits under the step name clf. So the setting's name is the step name, two underscores, then the setting: clf__max_depth. Name the step model and it becomes model__max_depth.
Tune the pipeline, not the bare model. Then the imputer and scaler are refitted on the four training folds each time, and the scoring fold never leaks into them.
Read all six scores
cv_results_ holds every candidate and its mean score:
for p, s in zip(grid.cv_results_["params"],
grid.cv_results_["mean_test_score"]):
print(str(p["clf__max_depth"]).rjust(4),
str(p["clf__class_weight"]).ljust(9), round(s, 3))
5 None 0.36
10 None 0.508
None None 0.558
5 balanced 0.583
10 balanced 0.612
None balanced 0.63
The third row, no depth limit and no class weight, is our default forest: 0.558 again. Now look at the balanced rows. Every one beats its unbalanced partner. class_weight="balanced" makes each rainy day count for more, the idea from Handling Imbalanced Data.
print(grid.best_params_)
print("best F1:", round(grid.best_score_, 3))
{'clf__class_weight': 'balanced', 'clf__max_depth': None}
best F1: 0.63
Same forest, same data. Only the settings changed, and F1 went from 0.558 to 0.630.
A bigger menu for XGBoost
Now a stronger model, XGBoost. set_params swaps the model inside the pipeline; the preprocessing stays the same. This time the menu has four settings:
xgb = XGBClassifier(random_state=42)
model.set_params(clf=xgb)
params = {
"clf__n_estimators": [100, 200, 400],
"clf__max_depth": [3, 5, 7],
"clf__learning_rate": [0.03, 0.1, 0.3],
"clf__scale_pos_weight": [1, 3],
}
print(len(ParameterGrid(params)), "combinations")
54 combinations
3 x 3 x 3 x 2 = 54. scale_pos_weight=3 gives every rainy day three times the weight, a bit like class_weight did for the forest. A full grid would be 54 x 5 = 270 fits, and every extra setting multiplies that again.
RandomizedSearchCV tries a random handful
Same model, same menu, but n_iter=10: draw ten combinations at random and cross-validate only those.
search = RandomizedSearchCV(
model, params, n_iter=10, cv=5, scoring="f1",
n_jobs=-1, verbose=1, random_state=42)
start = time.time()
search.fit(X_train, y_train)
print("seconds:", round(time.time() - start))
for name, value in search.best_params_.items():
print(name.replace("clf__", ""), value)
print("best F1:", round(search.best_score_, 3))
Fitting 5 folds for each of 10 candidates, totalling 50 fits
seconds: 8
scale_pos_weight 3
n_estimators 400
max_depth 7
learning_rate 0.03
best F1: 0.649
Ten candidates times five folds is 50 fits, in 8 seconds on the lecture machine (your timing will differ). The best draw: rainy days weighted 3, 400 trees, depth 7, learning rate 0.03, with F1 0.649. There's no clever maths in the picking; they're plain random draws. random_state=42 makes the same ten come out every run.
How much did we miss? Run the full grid
full = GridSearchCV(
model, params, cv=5, scoring="f1",
n_jobs=-1, verbose=1)
start = time.time()
full.fit(X_train, y_train)
print("seconds:", round(time.time() - start))
print("best F1:", round(full.best_score_, 3))
Fitting 5 folds for each of 54 candidates, totalling 270 fits
seconds: 27
best F1: 0.649
270 fits in 27 seconds, and the best F1 is 0.649: the very same winner. To be honest, random search was a bit lucky here, since the winner happened to be among its ten draws. But it took about a third of the time, and the bigger the menu, the more it saves. A good habit: random search first on a wide menu, then a small grid around the best values if you want to squeeze more.
The winner meets the test set, once
After the search, best_estimator_ is already refitted on all 16,000 training rows with the winning settings (that's the default refit=True). Now, and only now, the test rows come out:
best = search.best_estimator_
test_f1 = f1_score(y_test, best.predict(X_test))
print("test F1:", round(test_f1, 3))
test F1: 0.637
0.637 on 4,000 days the search never saw, close to the 0.649 from the folds. The search chose with cross-validation on the training rows; the test set gives one honest final number. If you went back and re-tuned after seeing it, the test set would become just another validation set.
Common mistakes
- Searching on all the data. Fit the search on
X_trainonly. The test rows wait until the end. - Reporting
best_score_as the final score. It's the best of many tries on the same folds, so it leans optimistic. The test score is the honest one. - Wrong parameter names. Inside a pipeline it's
step__settingwith two underscores. A typo raises an "Invalid parameter" error. - A grid that explodes. Four settings with five values each is 625 candidates, 3,125 fits. Count with
len(ParameterGrid(params))before you press run, or switch to random search. - Tuning a bare model outside the pipeline. The preprocessing then sees the scoring fold. Tune the whole pipeline.
Quick recap
| Step | Code | Rain in Australia |
|---|---|---|
| Default forest, 5-fold CV | cross_val_score(model, ...) | F1 0.558 |
| Grid search, forest | GridSearchCV, 6 candidates | 30 fits, F1 0.630 |
| Random search, XGBoost | RandomizedSearchCV(n_iter=10) | 50 fits, F1 0.649 |
| Full grid, XGBoost | GridSearchCV, 54 candidates | 270 fits, F1 0.649 |
| Test once | search.best_estimator_ | test F1 0.637 |
Try it yourself
Put the forest back with model.set_params(clf=RandomForestClassifier(random_state=42)) and add "clf__min_samples_leaf": [1, 5] to the forest grid. How many fits does it run now, and does the best F1 change?
The notebook and weatherAUS.csv are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Voting and Stacking: Does a Team of Models Beat the Best One?
Next →Which Features Matter? Feature Importances, Permutation Importance and SHAP
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Linear Regression and the Cost Function: Draw a Line, Score It
Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.
Gradient Descent Explained: Feel the Slope, Step Downhill
Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.
Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.
Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.