AI voor iedereen

Zoeken

Zoek in hoofdstukken en demo's

🏅 Modelevaluatie in Python

De volledige pipeline om AI-modellen te evalueren die voorspellen of een hotelgast de boeking annuleert, stap voor stap: een testset apart houden, kenmerken kiezen zonder datalekken, de data voorbereiden, zeven modellen vergelijken met kruisvalidatie, een drempelwaarde kiezen op basis van wat elke fout kost, het gekozen model onderzoeken en het één keer meten op de testset.

Uitvoeren in Google Colab

Colab vereist een Google-account, maar je kan de notebook ook .

Leesmodus. Hieronder staat de hele notebook, met de uitvoer van de code erbij. Je kan de volledige inhoud dus gewoon hier lezen. Om code aan te passen en de gevolgen te zien, kan je naar Google Colab (externe link) gaan.

How good is a model, really? The chapter Model Evaluation answered that with demos. This notebook does it step by step with scikit-learn (externe link), on real hotel bookings: from setting aside a test set to a report for the manager. On the way, you meet the three pitfalls from the chapter: measuring on the wrong data, measuring the wrong number, and measuring only once.

The question: will this guest cancel? A hotel that knows in time can sell the room again; a hotel that guesses wrong has to send a guest who turns up after all to another hotel.

The steps:

  1. ✂️ set aside a test set;
  2. 🔎 select the features, without columns that give the answer away;
  3. 🛠️ prepare the data in a pipeline;
  4. 🎯 choose what to measure;
  5. 🆚 compare seven models, and 🔧 tune one;
  6. 🎚️ choose a threshold from what each mistake costs;
  7. 🔬 study the chosen model in four ways, each with code that you can copy into your own project;
  8. 🏅 measure it once on the test set, and report the result.

Prior knowledge: the chapter Model Evaluation. You can run the whole notebook without changing a single line.

Estimated time: about 45 minutes.

This notebook is part of AI voor Iedereen (KU Leuven). The latest version is always at ai.kuleuven.be/aivooriedereen/en/notebook/model-evaluation, and you can open it directly in Google Colab (externe link).

🚀 First time in a notebook?

Then the short introductory notebook explains everything step by step. The most important things:

  1. Make your own copy: File → Save a copy in Drive (in the menu at the top left), and work in that copy.
  2. Run a cell by clicking in it and pressing Shift+Enter, or with the ▶ button to its left. The result appears below the cell.
  3. Run the cells in order, from top to bottom, because a cell uses what the cells above it made. Does something behave strangely? Choose Runtime → Restart session and run everything again from the top.

Prefer not to use Google? Download the notebook file and open it in Jupyter (externe link) or Visual Studio Code (externe link), with scikit-learn, pandas and matplotlib installed.

🐍 Python in this notebook

New to Python? The introductory notebook explains the basics: variables, lists, loops and functions. On top of those, this notebook uses:

CodeMeaning
make_pipeline(step, ..., model)A pipeline: steps that run one after the other. fit learns all of them on the training data only.
make_column_transformer((step, columns), ...)Prepares columns in different ways: numbers are scaled, categories become columns of zeros and ones.
cross_val_score(model, X, y, cv=cv, scoring="f1")Cross-validation: one score for every part of cv. cross_validate gives several scores at once, and times the training.
cross_val_predict(model, X, y, cv=cv)A prediction for every example, from the round in which it was left out.
model.predict_proba(X)[:, 1]The probability of a cancellation, instead of a yes or a no.
def compare(models, X, y, cv):A function: most studies in this notebook are one, so that you can copy them.
HTML(table.to_html())Shows a table neatly below the cell.

🏨 The bookings

Two hotels in Portugal, a resort hotel and a city hotel, published every booking for an arrival between July 2015 and August 2017: when it was made, for how many nights and guests, through which channel, at what price, and whether it was cancelled. This notebook uses a random sample of 12,000 of them, so that every cell runs in seconds.

The data are the Hotel booking demand datasets (externe link) by Nuno Antonio, Ana de Almeida and Luis Nunes (Data in Brief, 2019, CC BY 4.0), as combined by TidyTuesday (externe link).

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import HTML, display

DATA_URL = "https://ai.kuleuven.be/aivooriedereen/notebooks/data/"
bookings = pd.read_csv(DATA_URL + "hotel-bookings.csv")
print(len(bookings), "bookings, of which", bookings.duplicated().sum(), "are identical copies of another booking")
bookings = bookings.drop_duplicates()  # keep one of each: see below
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
bookings["arrival"] = pd.to_datetime(dict(year=bookings["arrival_date_year"], day=bookings["arrival_date_day_of_month"],
                                          month=bookings["arrival_date_month"].map({m: i for i, m in enumerate(months, 1)})))
print(len(bookings), "different bookings, of which", bookings["is_canceled"].sum(), "were cancelled")
HTML(bookings.head().to_html())
Uitvoer
12000 bookings, of which 1563 are identical copies of another booking
10437 different bookings, of which 3357 were cancelled
hotel is_canceled lead_time arrival_date_year arrival_date_month arrival_date_week_number arrival_date_day_of_month stays_in_weekend_nights stays_in_week_nights adults children babies meal country market_segment distribution_channel is_repeated_guest previous_cancellations previous_bookings_not_canceled reserved_room_type assigned_room_type booking_changes deposit_type agent company days_in_waiting_list customer_type adr required_car_parking_spaces total_of_special_requests reservation_status reservation_status_date arrival
0 Resort Hotel 0 354 2016 May 19 6 2 5 2 0.0 0 BB GBR Offline TA/TO TA/TO 0 0 0 A A 0 No Deposit 40.0 NaN 0 Transient 37.56 0 0 Check-Out 2016-05-13 2016-05-06
1 City Hotel 0 142 2017 August 35 31 0 3 2 0.0 0 BB DEU Online TA TA/TO 0 0 0 A A 0 No Deposit 85.0 NaN 0 Transient 86.10 0 0 Check-Out 2017-09-03 2017-08-31
2 City Hotel 1 304 2015 August 34 17 1 1 2 0.0 0 BB PRT Groups TA/TO 0 1 0 A A 0 Non Refund 1.0 NaN 0 Transient-Party 62.00 0 0 Canceled 2015-07-02 2015-08-17
3 City Hotel 0 5 2016 May 22 28 2 2 2 0.0 0 BB MAR Online TA TA/TO 0 0 0 D D 0 No Deposit 9.0 NaN 0 Transient 133.10 0 1 Check-Out 2016-06-01 2016-05-28
4 City Hotel 1 313 2015 August 35 26 0 2 2 0.0 0 BB PRT Groups TA/TO 0 1 0 A A 0 Non Refund 1.0 NaN 0 Transient-Party 62.00 0 0 Canceled 2015-07-02 2015-08-26

About one booking in eight is an identical copy of another one, often a room of a group, entered one by one. With one copy among the training bookings and another among the validation bookings, a model scores by recognizing a booking instead of predicting it: the overlap leak from the chapter. So the cell keeps one of each, before anything is split.

✂️ Setting aside a test set

Before anything else, put a test set aside, and don't look at it until the very end. It is the final exam from the training, validation and test split: every choice in this notebook (which features, which model, which settings, which threshold) is made on the other bookings, the training bookings. stratify gives both parts the same share of cancellations.

from sklearn.model_selection import train_test_split

train, test = train_test_split(bookings, test_size=0.25, random_state=0, stratify=bookings["is_canceled"])
print(len(train), "training bookings, of which", train["is_canceled"].sum(), "cancelled")
print(len(test), "test bookings, of which", test["is_canceled"].sum(), "cancelled: locked away until the end")
Uitvoer
7827 training bookings, of which 2518 cancelled
2610 test bookings, of which 839 cancelled: locked away until the end

🔎 Selecting the features

A model may only use what the hotel knows the moment a booking comes in. Most columns are clearly fine, but a few predict suspiciously well. Look at how often a booking was cancelled for three of them:

def cancelled(which):
    return f"{which.sum():5d} bookings, of which {train.loc[which, 'is_canceled'].mean():4.0%} cancelled"


print("reservation status 'Check-Out':", cancelled(train["reservation_status"] == "Check-Out"))
print("another room than reserved:    ", cancelled(train["assigned_room_type"] != train["reserved_room_type"]))
print("a parking space:               ", cancelled(train["required_car_parking_spaces"] > 0))
print("all training bookings:         ", cancelled(train["is_canceled"] >= 0))
Uitvoer
reservation status 'Check-Out':  5309 bookings, of which   0% cancelled
another room than reserved:      1064 bookings, of which   4% cancelled
a parking space:                  529 bookings, of which   0% cancelled
all training bookings:           7827 bookings, of which  32% cancelled

reservation_status is the answer itself: "Check-Out" means the guest came. The other two are sneakier. A guest gets another room than reserved at check-in, so only guests who come can get one. And not a single booking with a parking space was cancelled: the hotel probably only notes it on arrival. These are data leaks: information from after the moment of the prediction, the chapter's first pitfall of measuring on the wrong data. A model with them looks excellent here, and fails on every new booking.

So these three stay out, and so do booking_changes and reservation_status_date (also filled in later), the ID numbers of agent and company, and the year of arrival, which won't come back. When in doubt about a column, ask whoever made the data. These are the features:

numeric = ["lead_time", "arrival_date_week_number", "stays_in_weekend_nights", "stays_in_week_nights", "adults", "children",
           "babies", "is_repeated_guest", "previous_cancellations", "previous_bookings_not_canceled", "days_in_waiting_list",
           "adr", "total_of_special_requests"]  # lead_time: days between booking and arrival; adr: the price per night
categories = ["hotel", "meal", "country", "market_segment", "distribution_channel", "reserved_room_type", "deposit_type",
              "customer_type"]
X_train, y_train = train[numeric + categories], train["is_canceled"]  # y: 1 = cancelled
X_test, y_test = test[numeric + categories], test["is_canceled"]  # only used in the very last step
print(len(numeric), "numbers and", len(categories), "categories")
Uitvoer
13 numbers and 8 categories

🛠️ Preparing the data

This table has numbers on very different scales, categories (the meal, the country, the channel) and gaps (some bookings have no country). Preparing them learns from the data too: a mean, a spread, a median, the list of countries. So the preparation may only see the training part of each round, just like the model, or the validation bookings leak in: the "preprocessing on all data" leak from the chapter. A pipeline ties preparation and model together, and fit learns both on the training data only.

Below are the first training bookings as a model sees them: every number scaled (0 is the average, 1 is one spread above it), and every category spread over columns of zeros and ones, such as hotel_City Hotel. Countries with fewer than 20 bookings share one column.

from sklearn.compose import make_column_transformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler


def preparation(numbers=numeric, labels=categories):
    return make_column_transformer(
        (make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), numbers),  # fill gaps, then scale
        (OneHotEncoder(handle_unknown="infrequent_if_exist", min_frequency=20, sparse_output=False), labels),  # a 0/1 column per value
        verbose_feature_names_out=False)


def pipeline(model, numbers=numeric, labels=categories):
    return make_pipeline(preparation(numbers, labels), model)


prepare = preparation().fit(X_train)  # learns the means, spreads, medians and categories of the training bookings
prepared = pd.DataFrame(prepare.transform(X_train), columns=prepare.get_feature_names_out(), index=X_train.index)
print(X_train.shape[1], "columns become", prepared.shape[1], "numbers per booking")
HTML(prepared.head().round(2).to_html())
Uitvoer
21 columns become 77 numbers per booking
lead_time arrival_date_week_number stays_in_weekend_nights stays_in_week_nights adults children babies is_repeated_guest previous_cancellations previous_bookings_not_canceled days_in_waiting_list adr total_of_special_requests hotel_City Hotel hotel_Resort Hotel meal_BB meal_FB meal_HB meal_SC meal_Undefined country_AGO country_AUS country_AUT country_BEL country_BRA country_CHE country_CHN country_CN country_DEU country_DNK country_ESP country_FIN country_FRA country_GBR country_HUN country_IRL country_ISR country_ITA country_LUX country_NLD country_NOR country_POL country_PRT country_ROU country_RUS country_SWE country_TUR country_USA country_nan country_infrequent_sklearn market_segment_Complementary market_segment_Corporate market_segment_Direct market_segment_Groups market_segment_Offline TA/TO market_segment_Online TA market_segment_infrequent_sklearn distribution_channel_Corporate distribution_channel_Direct distribution_channel_TA/TO distribution_channel_infrequent_sklearn reserved_room_type_A reserved_room_type_B reserved_room_type_C reserved_room_type_D reserved_room_type_E reserved_room_type_F reserved_room_type_G reserved_room_type_H reserved_room_type_infrequent_sklearn deposit_type_No Deposit deposit_type_Non Refund deposit_type_infrequent_sklearn customer_type_Contract customer_type_Group customer_type_Transient customer_type_Transient-Party
11149 -0.76 -1.77 1.01 0.22 0.20 4.43 -0.09 -0.17 -0.09 -0.09 -0.11 0.83 -0.80 1.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 1.0
10240 0.03 1.15 1.01 0.74 0.20 4.43 -0.09 -0.17 -0.09 -0.09 -0.11 -0.10 2.87 0.0 1.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0
5219 1.17 -0.38 0.01 0.22 1.77 -0.28 -0.09 -0.17 -0.09 -0.09 -0.11 0.30 0.42 1.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0
9355 -0.80 0.13 0.01 0.22 0.20 -0.28 -0.09 -0.17 -0.09 -0.09 -0.11 0.22 -0.80 1.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0
3605 -0.35 -0.02 0.01 -0.81 0.20 4.43 -0.09 -0.17 -0.09 -0.09 -0.11 0.98 1.65 1.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0

🎯 Choosing what to measure

Which number tells you whether a model is good? The obvious one is the accuracy, the share of correct predictions. But a "model" that never predicts a cancellation is already right for 68% of the bookings. scikit-learn has it as DummyClassifier: the baseline that every real model has to beat. Compare it with two real models, on the counts of the confusion matrix and the numbers made from them. cross_val_predict gives every training booking a prediction from the round in which that booking was left out, so from a model that never saw it.

from sklearn.dummy import DummyClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score
from sklearn.model_selection import StratifiedKFold, cross_val_predict

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)  # five parts, each with the same share of cancellations
forest = RandomForestClassifier(n_estimators=200, random_state=0, n_jobs=-1)  # n_jobs=-1: use every processor


def scores(y, predicted):
    return {"accuracy": accuracy_score(y, predicted), "precision": precision_score(y, predicted, zero_division=0),
            "recall": recall_score(y, predicted), "F1": f1_score(y, predicted, zero_division=0),
            "cancellations caught": ((predicted == 1) & (y == 1)).sum(), "false alarms": ((predicted == 1) & (y == 0)).sum()}


results = {}
for name, model in [("never 'cancelled'", DummyClassifier()), ("logistic regression", pipeline(LogisticRegression(max_iter=1000))),
                    ("random forest", pipeline(forest))]:
    results[name] = scores(y_train, cross_val_predict(model, X_train, y_train, cv=cv))
HTML(pd.DataFrame.from_dict(results, orient="index").round(3).to_html())
Uitvoer
accuracy precision recall F1 cancellations caught false alarms
never 'cancelled' 0.678 0.000 0.000 0.000 0 0
logistic regression 0.785 0.735 0.520 0.609 1309 473
random forest 0.810 0.766 0.589 0.666 1484 453

Logistic regression is right for 79% of the bookings and the forest for 81%, but the baseline already gets 68% by predicting nothing at all: here, accuracy is the wrong number, the chapter's second pitfall. The counts tell more: the forest catches three cancellations in five, and raises one false alarm for every three it catches. From here on, the F1-score is the main number. Whether a model saves money depends on what each mistake costs: that comes back when choosing the threshold.

🆚 Comparing models

🎰 One split is a lottery

To compare models, you measure each of them on bookings it didn't train on. But one split is a lottery: measure the same forest 20 times, each time with another quarter of the training bookings as the validation part.

f1_per_split = []
for seed in range(20):
    X_fit, X_val, y_fit, y_val = train_test_split(X_train, y_train, test_size=0.25, random_state=seed, stratify=y_train)
    f1_per_split.append(f1_score(y_val, pipeline(forest).fit(X_fit, y_fit).predict(X_val)))
print(f"F1 of the same forest in 20 different splits: from {min(f1_per_split):.2f} to {max(f1_per_split):.2f}")
Uitvoer
F1 of the same forest in 20 different splits: from 0.64 to 0.69

The same forest, on the same bookings, scores anywhere from 0.64 to 0.69, depending only on which bookings ended up in the validation part. That range is wider than the gap between most of the models below: with one split, you could easily crown the wrong one. That is the chapter's third pitfall, measuring only once.

🔁 Cross-validation

Cross-validation turns the lottery into a measurement: it splits the training bookings into five parts, uses each part once as the validation part, and gives five scores instead of one. The function compare below does that for any number of models. Because every model gets the same five parts (the same cv), you can also compare them part by part.

from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import cross_validate
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier

models = {
    "naive Bayes": pipeline(GaussianNB()),
    "logistic regression": pipeline(LogisticRegression(max_iter=1000)),
    "k-nearest neighbors": pipeline(KNeighborsClassifier()),
    "decision tree": pipeline(DecisionTreeClassifier(max_depth=5, random_state=0)),
    "SVM": pipeline(SVC()),
    "random forest": pipeline(forest),
    "gradient boosting": pipeline(HistGradientBoostingClassifier(random_state=0)),
}


def compare(models, X, y, cv):
    # cross-validates every model on the same parts: a table of mean scores, and the F1-score of every part
    table, f1_per_part = {}, {}
    for name, model in models.items():
        result = cross_validate(model, X, y, cv=cv, scoring=["f1", "precision", "recall", "roc_auc"])
        f1_per_part[name] = result["test_f1"]
        table[name] = {"F1": result["test_f1"].mean(), "± spread": result["test_f1"].std(),
                       "precision": result["test_precision"].mean(), "recall": result["test_recall"].mean(),
                       "ROC-AUC": result["test_roc_auc"].mean(),
                       "ms to train": 1000 * result["fit_time"].mean(), "ms to predict": 1000 * result["score_time"].mean()}
    return pd.DataFrame.from_dict(table, orient="index"), pd.DataFrame(f1_per_part)


comparison, f1_per_part = compare(models, X_train, y_train, cv)
display(HTML(comparison.round(2).to_html()))  # ms: milliseconds per part

plt.figure(figsize=(7, 4))
for row, name in enumerate(f1_per_part.columns):
    plt.plot(f1_per_part[name], [row] * len(f1_per_part), "o", color="#2563eb", alpha=0.5)
    plt.plot(f1_per_part[name].mean(), row, "|", color="black", markersize=20)
plt.yticks(range(len(f1_per_part.columns)), f1_per_part.columns)
plt.xlabel("F1-score in each of the five parts (| = mean)")
plt.show()
wins = (f1_per_part["gradient boosting"] > f1_per_part["random forest"]).sum()
print(f"Gradient boosting beats the random forest in {wins} of the {len(f1_per_part)} parts")
Uitvoer
F1 ± spread precision recall ROC-AUC ms to train ms to predict
naive Bayes 0.50 0.06 0.56 0.51 0.72 48.54 30.91
logistic regression 0.61 0.01 0.74 0.52 0.83 135.21 20.65
k-nearest neighbors 0.59 0.02 0.65 0.54 0.78 35.29 89.54
decision tree 0.61 0.03 0.74 0.52 0.84 53.65 17.65
SVM 0.62 0.02 0.80 0.51 0.85 1165.24 615.73
random forest 0.67 0.01 0.77 0.59 0.87 594.33 176.61
gradient boosting 0.67 0.01 0.75 0.62 0.88 490.89 24.65
Gradient boosting beats the random forest in 4 of the 5 parts

Gradient boosting (trees built one after the other, each correcting the mistakes of the ones before it) and the random forest come out on top, but their difference (0.675 against 0.666) is smaller than their spread, and the forest even wins one of the five parts: a tie. Choose between them on something else, such as speed: the forest asks 200 trees for every booking, and is several times slower to predict (the last column). Logistic regression, the tree and the SVM are close together, k-nearest neighbors is a little behind, and naive Bayes comes last, with one bad part: it treats every feature as independent evidence, while for example the market segment and the distribution channel say nearly the same thing.

🔧 Tuning a hyperparameter

The depth of a tree is a complexity knob, like the degree of the polynomial in the chapter's overfitting demo. For every depth, validation_curve cross-validates the tree, and reports the F1-score both on the bookings it trained on and on the validation bookings. Inside a pipeline, a setting of the model gets the name of its step in front: decisiontreeclassifier__max_depth.

from sklearn.model_selection import validation_curve

depths = [1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 30]
train_f1, validation_f1 = validation_curve(pipeline(DecisionTreeClassifier(random_state=0)), X_train, y_train,
                                           param_name="decisiontreeclassifier__max_depth", param_range=depths, cv=cv, scoring="f1")
plt.figure(figsize=(7, 4))
plt.plot(depths, train_f1.mean(axis=1), "o-", label="training bookings")
plt.plot(depths, validation_f1.mean(axis=1), "o-", label="validation bookings")
plt.xlabel("max_depth of the tree")
plt.ylabel("F1-score")
plt.legend()
plt.show()
print("Best depth on the validation bookings:", depths[validation_f1.mean(axis=1).argmax()])
Uitvoer
Best depth on the validation bookings: 8

On the training bookings, the tree keeps getting better as it grows deeper, up to a perfect 1.0: it learns every booking by heart. On the validation bookings, it peaks at a depth of 8 and then slowly gets worse: underfitting on the left, overfitting on the right. Even at its best (0.63), a single tree stays well below the forest and gradient boosting. Compare tuned models only with models tuned just as carefully; to tune several knobs at once, GridSearchCV tries every combination with the same cross-validation.

Try it yourself: tune n_neighbors of k-nearest neighbors, with pipeline(KNeighborsClassifier()) and param_name="kneighborsclassifier__n_neighbors".

🎚️ Choosing a threshold

predict_proba gives a probability of cancellation, and predict says "cancelled" above 50%. But that threshold is a choice. Suppose the hotel sells the room of every booking that the model calls a cancellation a second time. A cancellation the model misses leaves a room empty that could have been sold: say €100. A false alarm is worse: the guest arrives at a full hotel, which pays for a room elsewhere, a taxi and an apology: say €300. Which threshold costs the least? cross_val_predict again gives every training booking a probability from a model that never saw it.

COST_MISSED, COST_FALSE_ALARM = 100, 300  # euro per missed cancellation, euro per false alarm
THRESHOLDS = np.linspace(0.01, 0.99, 99)


def cost(threshold, probability, y):
    missed = ((probability < threshold) & (y == 1)).sum()
    false_alarms = ((probability >= threshold) & (y == 0)).sum()
    return missed * COST_MISSED + false_alarms * COST_FALSE_ALARM


def cheapest(probability, y):
    # the threshold with the lowest total cost, and that cost
    costs = [cost(threshold, probability, y) for threshold in THRESHOLDS]
    return THRESHOLDS[np.argmin(costs)], min(costs)


best_model = pipeline(HistGradientBoostingClassifier(random_state=0))
probability = cross_val_predict(best_model, X_train, y_train, cv=cv, method="predict_proba")[:, 1]
threshold, lowest = cheapest(probability, y_train)
never = y_train.sum() * COST_MISSED  # never sell a room twice: every cancellation leaves a room empty

plt.figure(figsize=(7, 4))
plt.plot(THRESHOLDS, [cost(t, probability, y_train) / 1000 for t in THRESHOLDS])
plt.axhline(never / 1000, color="grey", linestyle=":", label="never sell a room twice")
plt.axvline(threshold, color="crimson", linestyle="--", label=f"cheapest: {threshold:.0%}")
plt.xlabel("threshold on the probability of a cancellation")
plt.ylabel("total cost on the training bookings [k€]")
plt.legend()
plt.show()
print(f"Never selling a room twice: €{never:,}")
print(f"Threshold 50%:              €{cost(0.5, probability, y_train):,}")
print(f"Threshold {threshold:.0%}:              €{lowest:,}")
print(f"Cancellations expected by the model: {probability.sum():.0f}; real cancellations: {y_train.sum()}")
Uitvoer
Never selling a room twice: €251,800
Threshold 50%:              €254,100
Threshold 76%:              €181,700
Cancellations expected by the model: 2499; real cancellations: 2518

The cheapest threshold is 76%: sell a room twice only when the model is quite sure, because one false alarm costs as much as three empty rooms. Theory agrees: for probabilities that are right, the best threshold is 300 / (300 + 100) = 75%. At the default of 50%, the model costs even more than never selling a room twice; at 76%, it saves about €70,000, while catching only a third of the cancellations. And although it can't tell which bookings will be cancelled, its probabilities add up to almost exactly how many: that total is what hotels overbook on.

Which threshold is right depends on what a mistake costs, not on the model: change the two costs at the top of the cell, and watch the threshold move. The ROC curve from the chapter and the precision-recall curve show the trade-off for every threshold, with the cheapest one as a red dot:

from sklearn.metrics import PrecisionRecallDisplay, RocCurveDisplay

alarm = probability >= threshold
caught = (alarm & (y_train == 1)).sum()
fig, (left, right) = plt.subplots(1, 2, figsize=(11, 4.5))
RocCurveDisplay.from_predictions(y_train, probability, ax=left, name="gradient boosting")
left.plot((alarm & (y_train == 0)).sum() / (y_train == 0).sum(), caught / y_train.sum(), "o", color="crimson",
          label=f"threshold {threshold:.0%}")
PrecisionRecallDisplay.from_predictions(y_train, probability, ax=right, name="gradient boosting")
right.plot(caught / y_train.sum(), caught / alarm.sum(), "o", color="crimson", label=f"threshold {threshold:.0%}")
left.legend()
right.legend()
plt.show()
Uitvoer

The red dot sits far left on the ROC curve, where false alarms are rare (under 2% of the guests who come), and high on the precision-recall curve (92% of the alarms are real). The price is the low recall: most cancellations go unnoticed.

🔬 Studying the chosen model

Before the final measurement on the test set, four studies take a closer look at the chosen model: its mistakes, the features it needs, how much data it needs, and whether it holds up elsewhere and later.

🔍 Error analysis

Which cancellations does the model miss? Sort them by how far ahead the booking was made:

alarm = probability >= threshold  # the cross-validated alarms on the training bookings, at the cheapest threshold
is_cancelled = y_train == 1
ahead = pd.cut(train["lead_time"], [-1, 7, 30, 90, 180, 1000],
               labels=["within a week", "1 to 4 weeks", "1 to 3 months", "3 to 6 months", "more than 6 months"])
kinds = pd.DataFrame({"cancellations": ahead[is_cancelled].value_counts(), "missed": ahead[is_cancelled & ~alarm].value_counts(),
                      "false alarms": ahead[~is_cancelled & alarm].value_counts()}).sort_index()
kinds["share missed"] = (kinds["missed"] / kinds["cancellations"]).round(2)
display(HTML(kinds.to_html()))

no_refund = train["deposit_type"] == "Non Refund"
print(f"Non-refundable bookings: {no_refund.sum()}, of which {y_train[no_refund].mean():.0%} cancelled "
      f"and {(is_cancelled & ~alarm & no_refund).sum()} missed; {(train.loc[no_refund, 'country'] == 'PRT').mean():.0%} from Portugal, "
      f"booked a median {train.loc[no_refund, 'lead_time'].median():.0f} days ahead")
Uitvoer
cancellations missed false alarms share missed
lead_time
within a week 136 127 2 0.93
1 to 4 weeks 355 291 9 0.82
1 to 3 months 703 538 20 0.77
3 to 6 months 652 415 23 0.64
more than 6 months 672 212 24 0.32
Non-refundable bookings: 416, of which 99% cancelled and 0 missed; 96% from Portugal, booked a median 198 days ahead

The model misses almost every cancellation of a booking made within a week of arrival, and most of those made within a month: a change of plans shortly before a trip leaves no trace in the booking. It does catch every cancellation of a non-refundable booking, the oddest group in the data: nearly all cancelled, nearly all from Portugal, booked half a year ahead. They look more like blocks of rooms reserved and released again than like individual guests.

So the largest group of errors, the late cancellations, is a business question rather than a modelling problem: a deposit for late bookings, or overbooking on the expected total.

Try it yourself: group the missed cancellations by market segment, with train.loc[is_cancelled & ~alarm, "market_segment"].value_counts().

🧩 Ablation study

Which features does the model really need? An ablation study leaves out one group of features at a time, and measures again. The cost column chooses the cheapest threshold anew for every row.

def f1_and_cost(model, X, y, cv):
    probability = cross_val_predict(model, X, y, cv=cv, method="predict_proba")[:, 1]
    f1 = np.mean([f1_score(y.iloc[part], probability[part] >= 0.5) for _, part in cv.split(X, y)])
    return {"F1": f1, "lowest cost [k€]": cheapest(probability, y)[1] / 1000}


groups = {"the booking (lead time, deposit, waiting list)": ["lead_time", "deposit_type", "days_in_waiting_list"],
          "the channel (segment, distribution, customer type)": ["market_segment", "distribution_channel", "customer_type"],
          "the guest (country, party, history)": ["country", "adults", "children", "babies", "is_repeated_guest",
                                                  "previous_cancellations", "previous_bookings_not_canceled"],
          "the stay (hotel, week, nights, meal, room, price)": ["hotel", "arrival_date_week_number", "stays_in_weekend_nights",
                                                                 "stays_in_week_nights", "meal", "reserved_room_type", "adr"],
          "special requests": ["total_of_special_requests"]}
boosting = HistGradientBoostingClassifier(random_state=0)
results = {"all features": f1_and_cost(best_model, X_train, y_train, cv)}
for name, columns in groups.items():
    without = pipeline(boosting, [c for c in numeric if c not in columns], [c for c in categories if c not in columns])
    results[f"without {name}"] = f1_and_cost(without, X_train, y_train, cv)
HTML(pd.DataFrame.from_dict(results, orient="index").round(3).to_html())
Uitvoer
F1 lowest cost [k€]
all features 0.675 181.7
without the booking (lead time, deposit, waiting list) 0.635 206.2
without the channel (segment, distribution, customer type) 0.628 193.3
without the guest (country, party, history) 0.612 205.7
without the stay (hotel, week, nights, meal, room, price) 0.656 188.2
without special requests 0.616 197.1

Every group matters, the guest most. One single column, the number of special requests, matters about as much as a whole group: a guest who asks for a twin bed or a high floor means to come. Adding features is measured the same way, with and without them: in the decision-trees notebook, three features from physics let a tree find the failure rules of a machine.

📈 Data size impact

Would more bookings help? Train the model on smaller samples of the training part of every round, and measure it on the validation part: five rounds for every size.

from sklearn.utils import resample


def data_size_curve(model, X, y, sizes, cv):
    rows = []
    for size in sizes:
        for part, (train_part, validation_part) in enumerate(cv.split(X, y)):
            sample = resample(train_part, n_samples=size, replace=False, stratify=y.iloc[train_part], random_state=part)
            model.fit(X.iloc[sample], y.iloc[sample])
            f1 = f1_score(y.iloc[validation_part], model.predict(X.iloc[validation_part]), zero_division=0)
            rows.append({"training bookings": size, "F1": f1})
    return pd.DataFrame(rows).groupby("training bookings")["F1"].agg(["mean", "std"])


sizes = [250, 500, 1000, 2000, 4000, 6000]
curve = data_size_curve(best_model, X_train, y_train, sizes, cv)
plt.figure(figsize=(7, 4))
plt.errorbar(curve.index, curve["mean"], yerr=curve["std"], marker="o", capsize=4)
plt.xscale("log")
plt.xticks(sizes, [f"{size:,}" for size in sizes])
plt.minorticks_off()
plt.xlabel("number of training bookings")
plt.ylabel("F1-score on the validation bookings")
plt.show()
HTML(curve.round(3).to_html())
Uitvoer
mean std
training bookings
250 0.562 0.012
500 0.585 0.020
1000 0.626 0.021
2000 0.655 0.013
4000 0.671 0.019
6000 0.677 0.018

With only 250 bookings, the model already reaches an F1-score of 0.56. After that, every doubling adds less, and from 4,000 to 6,000 bookings hardly anything. More bookings of the same kind won't help much anymore. New kinds of information might, such as the cancellation conditions of each booking's rate.

🌍 Robustness: another hotel, later months

So far, the model learned from both hotels and all months at once. Does a model learned in one hotel still work in the other? And does it still work in later months, when it has only seen earlier ones?

from sklearn.model_selection import KFold, cross_val_score

monthly = train.groupby([pd.Grouper(key="arrival", freq="MS"), "hotel"])["is_canceled"].mean().unstack()
monthly.plot(figsize=(7, 3), xlabel="month of arrival", ylabel="share cancelled")
plt.show()

for trained, other in [("City Hotel", "Resort Hotel"), ("Resort Hotel", "City Hotel")]:
    here, there = X_train["hotel"] == trained, X_train["hotel"] == other
    own = cross_val_score(best_model, X_train[here], y_train[here], cv=cv, scoring="f1").mean()
    moved = f1_score(y_train[there], best_model.fit(X_train[here], y_train[here]).predict(X_train[there]))
    print(f"Learned in the {trained}: F1 {own:.2f} on its own bookings, {moved:.2f} in the {other}")

in_order = train.sort_values("arrival", kind="stable").index  # the training bookings, in the order of arrival
for split, splitter in [("shuffled parts", cv), ("five periods in a row", KFold(n_splits=5))]:
    f1 = cross_val_score(best_model, X_train.loc[in_order], y_train.loc[in_order], cv=splitter, scoring="f1")
    print(f"{split:22s} F1 {f1.mean():.2f}   per part: " + ", ".join(f"{score:.2f}" for score in f1))
Uitvoer
Learned in the City Hotel: F1 0.69 on its own bookings, 0.55 in the Resort Hotel
Learned in the Resort Hotel: F1 0.64 on its own bookings, 0.64 in the City Hotel
shuffled parts         F1 0.67   per part: 0.67, 0.64, 0.68, 0.69, 0.68
five periods in a row  F1 0.62   per part: 0.68, 0.64, 0.61, 0.58, 0.56

The two hotels behave differently, each with its own seasons. A model learned in the city hotel drops from 0.69 to 0.55 in the resort hotel; the other way around, it holds up. And validated on a later period, the model scores lower than on shuffled parts, the more so the later: the guests of 2017 behave a little differently from those of 2015.

So for a model that predicts next season, every shuffled score here is somewhat optimistic. When your model has to predict the future, train on the past and validate on what comes after: KFold on the rows in their order, or TimeSeriesSplit. The final report has to mention this, since the test set is a random quarter of the same two years.

🏅 Measuring once on the test set

Everything is chosen now: the features, gradient boosting, and the threshold. Train the model one last time on all training bookings, and measure it once on the test set that has been locked away since the first step, as in the chapter's evaluation workflow.

from sklearn.metrics import ConfusionMatrixDisplay

caught_per_part = [(probability[part] >= threshold)[y_train.iloc[part] == 1].mean() for _, part in cv.split(X_train, y_train)]
final_model = best_model.fit(X_train, y_train)
test_probability = final_model.predict_proba(X_test)[:, 1]
alarm = test_probability >= threshold
ConfusionMatrixDisplay.from_predictions(y_test, alarm.astype(int), display_labels=["came", "cancelled"], cmap="Blues", colorbar=False)
plt.show()
print(f"Threshold {threshold:.0%}: {(alarm & (y_test == 1)).sum()} of the {y_test.sum()} cancellations caught, "
      f"{(alarm & (y_test == 0)).sum()} false alarms, for a cost of €{cost(threshold, test_probability, y_test):,}")
print(f"Threshold 50%: €{cost(0.5, test_probability, y_test):,}; never selling a room twice: €{y_test.sum() * COST_MISSED:,}")
print(f"Cancellations caught in cross-validation: {np.mean(caught_per_part):.0%} "
      f"(from {min(caught_per_part):.0%} to {max(caught_per_part):.0%} per part); on the test set: {alarm[y_test == 1].mean():.0%}")
Uitvoer
Threshold 76%: 306 of the 839 cancellations caught, 38 false alarms, for a cost of €64,700
Threshold 50%: €85,500; never selling a room twice: €83,900
Cancellations caught in cross-validation: 37% (from 35% to 40% per part); on the test set: 36%

On 2,610 bookings it never saw, the model calls 344 bookings cancellations: 306 were indeed cancelled, and 38 guests turned up after all. That costs €64,700, against €83,900 when the hotel never sells a room twice, and €85,500 at the default threshold of 50%. The model catches 36% of the test cancellations, in line with the cross-validation (35% to 40%), as it should: a test score far above the cross-validation would be a reason for suspicion, not for joy.

What you would tell the hotel manager:

If we sell the room of every booking with a cancellation chance of 76% or more a second time, we save about €19,000 per 2,600 bookings, after paying for the 2% of guests we then have to send to another hotel. The model spots a third of the cancellations, and hardly any last-minute ones. Main limitation: it learned from 2015–2017 in two hotels together and scored lower in another hotel and in later months, so check it on new bookings before relying on it.

🧰 Evaluation for your own problem

The steps of this notebook, for your own data:

  1. Remove copies, then set aside a test set, split the way the model will be used.
  2. Select the features you know at the moment of the prediction.
  3. Prepare the data in a pipeline, so that every step learns from the training part only.
  4. Choose what to measure, starting from a baseline.
  5. Compare models with cross-validation on the same parts, with their spread, and tune them equally carefully.
  6. Choose the threshold from what each mistake costs.
  7. Study the chosen model, then measure it once on the test set, and report it with the spread of the cross-validation.

How your rows relate to each other decides the split. Every cell above uses one cv:

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)  # independent rows, like the bookings here
cv = TimeSeriesSplit(n_splits=5)       # you predict the future: always train on earlier rows only
cv = StratifiedGroupKFold(n_splits=5)  # several rows per guest, wash cycle or recording: also pass groups=...

For the test set: train_test_split(..., shuffle=False) keeps the last quarter of a time series, and GroupShuffleSplit keeps groups together.

Predicting a number? Use DummyRegressor (or "the same as yesterday") as the baseline, scoring="neg_mean_absolute_error", and KFold. There is no threshold, and a plot of predicted against real values replaces the confusion matrix.

StudyWhat to copy
🆚 Comparing modelscompare
🔧 Tuning a hyperparametervalidation_curve
🎚️ Choosing a thresholdcost, cheapest
🔍 Error analysisthe errors, grouped by a column
🧩 Ablation studyf1_and_cost
📈 Data size impactdata_size_curve
🌍 Robustnessanother group, and KFold in time order

The scikit-learn pages on common pitfalls (externe link) and cross-validation (externe link) go deeper.


By Thomas Winters (externe link) for AI voor Iedereen, KU Leuven. The latest version of this notebook: ai.kuleuven.be/aivooriedereen/en/notebook/model-evaluation.