Section 4 · Lesson 2
Cross-validation and hyperparameter tuning
Get a more reliable score with k-fold cross-validation, then let GridSearchCV pick hyperparameters without touching the test set.
Every score so far came from one particular train/test split. Change random_state and you’ll
get a different score. Sometimes the difference is small, sometimes it’s large enough to change
which model looks best. Cross-validation averages over several splits so you’re not fooled by
one lucky or unlucky draw.
k-fold cross-validation
Cut the data into k equal folds (5 is a common choice). Train on four folds, score on the fifth, and repeat until every fold has been the scoring fold once:
from sklearn.model_selection import StratifiedKFold, cross_val_score
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X, y, cv=cv, scoring="roc_auc")
scores.mean(), scores.std()
- Stratified folds keep the 15% conversion rate in every fold.
shuffle=Truewith arandom_statemixes the rows before cutting, and makes the result repeatable.scoringnames the metric:"roc_auc","accuracy","neg_mean_absolute_error"and so on. Error metrics are negated because scikit-learn always maximizes.
For the scaled logistic regression, the five fold AUCs range from about 0.76 to 0.82, with a mean of 0.795. The mean is your estimate, and the spread tells you how much a single split’s score could mislead you. If two models differ by less than the fold-to-fold noise, you can’t really tell them apart.
Every row gets used for both training and scoring, which matters when data is limited. The cost is fitting k times.
Parameters and hyperparameters
A model learns its parameters during fit: coefficients, tree splits. You choose its
hyperparameters before fitting: max_depth, min_samples_leaf, the regularization strength C.
Tuning means searching for the hyperparameters that generalize best.
GridSearchCV
GridSearchCV tries every combination in a grid and cross-validates each:
from sklearn.model_selection import GridSearchCV
search = GridSearchCV(
DecisionTreeClassifier(random_state=42),
param_grid={"max_depth": [2, 3, 4, 5, 6, 8], "min_samples_leaf": [1, 20, 50, 100]},
cv=cv, scoring="roc_auc",
)
search.fit(X_train, y_train)
search.best_params_, search.best_score_
That’s 24 combinations × 5 folds = 120 fits. With the default refit=True, the search then refits
the best combination on all of X_train, so search itself behaves like the tuned model.
On our training data the winner is max_depth=5, min_samples_leaf=50, with a cross-validated AUC
of about 0.77. Larger leaves smooth out the tree’s probabilities, the same effect you saw when
limiting depth. Scored once on the untouched test set, the tuned tree reaches about 0.79.
Rules that keep scores honest
- Tune on the training set; score the test set once.
best_score_is slightly optimistic, because it’s the best of 24 tries on the same folds. The test score is the honest number. - Put preprocessing inside the pipeline. Cross-validating a pipeline refits the imputer,
scaler and encoder within each fold. Pipeline steps are tuned with double underscores:
{"logisticregression__C": [0.01, 0.1, 1, 10]}. - Respect time. For forecasting, use
TimeSeriesSplit, which always trains on the past and scores on the future. - Big grids get expensive fast.
RandomizedSearchCVsamples a fixed number of combinations and often finds a near-best setting for a fraction of the cost.
Practice
Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.
5-fold cross-validation
DoneCross-validate the scaled logistic regression on all 5,000 visitors (behavior features):
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
cv_scores = cross_val_score(make_pipeline(StandardScaler(), LogisticRegression()),
X, y, cv=cv, scoring="roc_auc")cv_scores: the five fold AUCscv_mean: their mean, rounded to 4 decimalscv_std: their standard deviation (cv_scores.std()), rounded to 4 decimalsspread: the best fold minus the worst fold, rounded to 4 decimals
Need a hint?
cross_val_scorereturns a NumPy array, so.mean(),.std(),.max()and.min()all work on it.- Pass the pipeline itself, not a fitted model: cross_val_score refits it once per fold.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
import numpy as np
import pandas as pd
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
audience = pd.read_csv("audience.csv")
features = ["sessions_30d", "pages_viewed_30d", "minutes_on_site_30d", "cart_adds_30d",
"days_since_last_visit", "past_purchases", "email_subscriber", "ad_impressions_7d"]
X = audience[features]
y = audience["converted"]
cv_scores = None
cv_mean = None
cv_std = None
spread = None
print(cv_scores, cv_mean, cv_std, spread)
Files in the working directory
audience.csv (5,000 rows)daily_stats.csv (1,561 rows)campaigns.csv (40 rows)Tune a decision tree
DoneSearch over tree depth and leaf size with 5-fold cross-validation on the training set only:
search = GridSearchCV(
DecisionTreeClassifier(random_state=42),
param_grid={"max_depth": [2, 3, 4, 5, 6, 8], "min_samples_leaf": [1, 20, 50, 100]},
cv=cv, scoring="roc_auc",
)search: the fitted search (fit it onX_train,y_train)best_params:search.best_params_best_cv_auc:search.best_score_, rounded to 4 decimalstest_auc: the test ROC-AUC of the refit best model, fromsearch.predict_proba(X_test)[:, 1],
rounded to 4 decimals
Need a hint?
search.fit(X_train, y_train)tries all 24 combinations with 5 folds each, then refits the best one on all of X_train.- After fitting,
search.predict_proba(X_test)uses the refit best model.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
import pandas as pd
from sklearn.model_selection import train_test_split, StratifiedKFold, GridSearchCV
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import roc_auc_score
audience = pd.read_csv("audience.csv")
features = ["sessions_30d", "pages_viewed_30d", "minutes_on_site_30d", "cart_adds_30d",
"days_since_last_visit", "past_purchases", "email_subscriber", "ad_impressions_7d"]
X_train, X_test, y_train, y_test = train_test_split(
audience[features], audience["converted"], test_size=0.25, random_state=42,
stratify=audience["converted"],
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
search = None
best_params = None
best_cv_auc = None
test_auc = None
print(best_params, best_cv_auc, test_auc)
Files in the working directory
audience.csv (5,000 rows)daily_stats.csv (1,561 rows)campaigns.csv (40 rows)