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.

45 min 2 practice tasks
Machine Learning Fundamentals: Cross Validation by StatQuest with Josh Starmer on YouTube

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=True with a random_state mixes the rows before cutting, and makes the result repeatable.
  • scoring names 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

  1. 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.
  2. 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]}.
  3. Respect time. For forecasting, use TimeSeriesSplit, which always trains on the past and scores on the future.
  4. Big grids get expensive fast. RandomizedSearchCV samples 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.

1

5-fold cross-validation

Cross-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 AUCs
  • cv_mean: their mean, rounded to 4 decimals
  • cv_std: their standard deviation (cv_scores.std()), rounded to 4 decimals
  • spread: the best fold minus the worst fold, rounded to 4 decimals
Need a hint?
  1. cross_val_score returns a NumPy array, so .mean(), .std(), .max() and .min() all work on it.
  2. Pass the pipeline itself, not a fitted model: cross_val_score refits it once per fold.
Python 3
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)
user_id, age, country, device, source, sessions_30d, pages_viewed_30d, minutes_on_site_30d, cart_adds_30d, days_since_last_visit, past_purchases, email_subscriber, ad_impressions_7d, converted
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status