Skip to content

37. Model evaluation and tuning — Mini-project

The retention team of a subscription business plans a phone campaign. An agent calls each customer that the model flags and offers a discount. A call with its offer costs 40. A customer who would have churned and stays thanks to the call is worth 200. The team asks three questions:

  1. Which model should flag the customers?
  2. How good will it be on customers it has never seen? The team wants one honest number with an error bar, not the best score of a long search.
  3. Which customers should the agents call, and what profit should the team expect?

Write a script, churn_campaign.py, that answers the three questions with the tools of this module: a cross-validation strategy that fits the problem, a diagnosis with a learning curve, two tuned model families, nested cross-validation and a threshold tuned for the campaign profit. The test set is used once, at the very end.

data/customers.csv has 5,000 subscription customers with 12 features and the label churned (19.3% churners). See the data dictionary for every column. Drop customer_id (an identifier) and signup_date (its information is already in tenure_months). total_charges is blank for 10 brand-new customers; impute it inside the pipeline.

Each row is one customer, so the rows are independent and no group split is needed. The label is rare, so use stratified splits.

Your script must:

  1. Split off a stratified 25% test set with random_state=42 and leave it untouched until the final report.
  2. Report the cross-validated ROC-AUC and average precision of two baselines: a DummyClassifier(strategy="prior") and a default logistic regression.
  3. Compute a learning curve for the logistic regression and print, at the largest size, the training score, the validation score and the gap. State in one sentence if more data would help.
  4. Write two tuning procedures with average precision as the score: a logistic regression (C from a log-uniform distribution, class_weight in None or "balanced") with RandomizedSearchCV, and a decision tree (max_depth, min_samples_leaf, ccp_alpha) with Optuna and TPESampler(seed=42). Each procedure takes training rows and returns a fitted pipeline.
  5. Choose the family with nested cross-validation: run both procedures inside the same 5 outer folds, print each mean and standard deviation, and pick the higher mean. Never choose by comparing best_score_ values or test scores. Then refit the chosen procedure on all training rows.
  6. Tune the decision threshold for the campaign profit (+160 per caught churner, −40 per wasted call) with TunedThresholdClassifierCV.
  7. In the final report, print the test ROC-AUC, average precision, precision, recall, the number of calls and the profit, and compare the profit with two simple policies: call nobody and call everybody.
  8. Use random_state=42 or seed=42 everywhere, n_jobs=1, and silence Optuna’s logs. The whole script runs in under a minute.
  1. Load and split. Read the CSV, build X and y, and split with train_test_split(..., stratify=y, random_state=42). Print the shapes and the churn rate of each part.

  2. Build the preprocessing. One-hot encode the text columns; impute (median) and scale the numeric ones. Wrap it in a function that returns a new ColumnTransformer each time.

  3. Score the baselines. Use cross_validate with StratifiedKFold(5, shuffle=True, random_state=42) and scoring=["roc_auc", "average_precision"]. The dummy model’s average precision equals the churn rate. Every real model must beat it.

  4. Diagnose. Run learning_curve for the logistic regression. A small gap and a flat validation curve mean high bias: more rows will not help; better features or a more flexible model might.

  5. Write the logistic tuner. A function tune_logistic(X, y) runs RandomizedSearchCV with loguniform(1e-3, 1e2) for C, 15 draws and 3-fold stratified CV, and returns best_estimator_.

  6. Write the tree tuner with Optuna. A function tune_tree(X, y) defines an objective that builds a fresh pipeline from the trial’s values and returns the mean CV average precision on X, y. It runs 20 trials, then fits the best pipeline on X, y and returns it.

  7. Choose the family with nested CV. Loop over the 5 outer folds of StratifiedKFold(5, shuffle=True, random_state=42). In each, call both tuners on the outer-training part and score the returned pipelines on the outer-validation part. Report each family’s mean ± standard deviation, pick the higher mean and refit its tuner on all training rows.

  8. Tune the threshold. Wrap the chosen pipeline with its best parameters in TunedThresholdClassifierCV with a profit scorer. Print the threshold and compare it with the break-even probability 40 / 200 = 0.2.

  9. Report once on the test set. Fit, predict and print the final table. Compute the profit of calling nobody (0) and of calling everybody.

A skeleton to start from:

churn_campaign.py (starter)
# churn_campaign.py: an honest churn model for a retention campaign.
import numpy as np
import pandas as pd
# --- 1. Load and split -------------------------------------------------
# TODO: X, y, stratified 75/25 split
# --- 2. Preprocessing ---------------------------------------------------
# TODO: def make_preprocess(): ...
# --- 3. Baselines --------------------------------------------------------
# TODO: DummyClassifier and LogisticRegression with cross_validate
# --- 4. Learning curve ----------------------------------------------------
# TODO: gap and verdict
# --- 5-6. Two tuners ------------------------------------------------------
# TODO: def tune_logistic(X, y): RandomizedSearchCV -> fitted best pipeline
# TODO: def tune_tree(X, y): Optuna study -> fitted best pipeline
# --- 7. Nested CV to choose the family ---------------------------------------
# TODO: for each outer fold, call both tuners and score them on the held-out part
# TODO: pick the higher nested mean; refit its tuner on all training rows
# --- 8. Threshold ---------------------------------------------------------
# TODO: TunedThresholdClassifierCV with the campaign profit
# --- 9. Final report --------------------------------------------------------
# TODO: test metrics, calls, profit vs call nobody / call everybody
Criterion Points Full points when
Clean evaluation design 3 Stratified test split, used once at the end; every learned step inside a pipeline
Baselines 2 Dummy and default logistic scores with CV, both metrics
Diagnosis 2 Learning-curve numbers and a correct one-sentence verdict
Random search 2 Log-uniform C, class weights, fixed seed, a sensible number of draws
Optuna search 2 Objective builds a fresh pipeline; TPESampler(seed=42); logs silenced
Honest selection and estimate 3 Both tuners inside the same nested CV, family chosen by the nested means, mean ± std reported; no choice made from best_score_ or the test set
Threshold 3 Profit scorer, tuned threshold printed and compared with 0.2
Final report 2 Test metrics, number of calls and profit against the two simple policies
Reproducibility 1 Seeds everywhere, n_jobs=1, runs in under a minute
Total 20 16 or more: you are ready for module 38
  1. Add a third family, HistGradientBoostingClassifier with categorical_features="from_dtype", tuned with HalvingRandomSearchCV. Does it beat the logistic regression in nested CV by more than one standard deviation?
  2. Replace the fixed costs with a budget: the team can make at most 300 calls. Choose the 300 customers with the highest probabilities and compute the profit.
  3. Calibrate the chosen model with CalibratedClassifierCV (module 36) and check whether the tuned threshold moves closer to 0.2.
  4. Save the final model with joblib.dump to output/churn_campaign.joblib, load it in a new script and check that it gives the same predictions.
  5. Repeat the nested CV with RepeatedStratifiedKFold(n_splits=5, n_repeats=3, random_state=42) as the outer loop. How much does the standard deviation change?

Try the project yourself first. Then compare your script with this one. Your numbers must match if you use the same seeds, splits and search spaces.

Reference solution
churn_campaign.py
# churn_campaign.py: an honest churn model for a retention campaign.
import numpy as np
import optuna
import pandas as pd
from scipy.stats import loguniform
from sklearn.base import clone
from sklearn.compose import make_column_selector, make_column_transformer
from sklearn.dummy import DummyClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
average_precision_score,
confusion_matrix,
make_scorer,
precision_score,
recall_score,
roc_auc_score,
)
from sklearn.model_selection import (
RandomizedSearchCV,
StratifiedKFold,
TunedThresholdClassifierCV,
cross_val_score,
cross_validate,
learning_curve,
train_test_split,
)
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.tree import DecisionTreeClassifier
optuna.logging.set_verbosity(optuna.logging.WARNING)
CALL_COST, CHURNER_VALUE = 40, 200
# --- 1. Load and split -------------------------------------------------
customers = pd.read_csv("data/customers.csv")
X = customers.drop(columns=["customer_id", "signup_date", "churned"])
y = customers["churned"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
print(f"train {X_train.shape}, churn {y_train.mean():.3f}")
print(f"test {X_test.shape}, churn {y_test.mean():.3f}")
# --- 2. Preprocessing ---------------------------------------------------
def make_preprocess():
numeric = Pipeline(
[("impute", SimpleImputer(strategy="median")), ("scale", StandardScaler())]
)
return make_column_transformer(
(
OneHotEncoder(handle_unknown="ignore"),
make_column_selector(dtype_include="str"),
),
(numeric, make_column_selector(dtype_include="number")),
)
def make_model(estimator):
return Pipeline([("prep", make_preprocess()), ("model", estimator)])
cv3 = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)
cv5 = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
# --- 3. Baselines --------------------------------------------------------
print("\nBaselines (5-fold CV)")
baselines = {
"dummy": make_model(DummyClassifier(strategy="prior")),
"logistic": make_model(LogisticRegression(max_iter=1000)),
}
for name, model in baselines.items():
scores = cross_validate(
model, X_train, y_train, cv=cv5, scoring=["roc_auc", "average_precision"]
)
print(f" {name:<9} ROC-AUC {scores['test_roc_auc'].mean():.3f}"
f" AP {scores['test_average_precision'].mean():.3f}")
# --- 4. Learning curve ----------------------------------------------------
sizes, train_scores, valid_scores = learning_curve(
baselines["logistic"], X_train, y_train, train_sizes=[0.25, 0.5, 1.0],
cv=cv5, scoring="average_precision", n_jobs=1,
)
train_ap, valid_ap = train_scores.mean(axis=1), valid_scores.mean(axis=1)
print("\nLearning curve (logistic, AP)")
print(" sizes", sizes.tolist(), "valid", valid_ap.round(3).tolist())
print(f" at {sizes[-1]} rows: train {train_ap[-1]:.3f}, valid {valid_ap[-1]:.3f},"
f" gap {train_ap[-1] - valid_ap[-1]:.3f}")
print(" verdict: small gap and flat curve -> high bias; more rows will not help much")
# --- 5. Tuner for the logistic regression -----------------------------------
def tune_logistic(X_fit, y_fit):
"""Random search on X_fit; return the best pipeline (refitted) and params."""
search = RandomizedSearchCV(
make_model(LogisticRegression(max_iter=1000)),
{"model__C": loguniform(1e-3, 1e2), "model__class_weight": [None, "balanced"]},
n_iter=15, cv=cv3, scoring="average_precision", random_state=42, n_jobs=1,
).fit(X_fit, y_fit)
params = search.best_params_
return search.best_estimator_, {
"C": round(float(params["model__C"]), 3),
"class_weight": params["model__class_weight"],
}
# --- 6. Tuner for the tree with Optuna ----------------------------------------
def tune_tree(X_fit, y_fit):
"""Optuna TPE study on X_fit; return the best pipeline (refitted) and params."""
def objective(trial):
tree = DecisionTreeClassifier(
max_depth=trial.suggest_int("max_depth", 2, 12),
min_samples_leaf=trial.suggest_int("min_samples_leaf", 5, 200, log=True),
ccp_alpha=trial.suggest_float("ccp_alpha", 1e-5, 1e-2, log=True),
random_state=42,
)
scores = cross_val_score(
make_model(tree), X_fit, y_fit, cv=cv3, scoring="average_precision"
)
return scores.mean()
study = optuna.create_study(
direction="maximize", sampler=optuna.samplers.TPESampler(seed=42)
)
study.optimize(objective, n_trials=20)
best = make_model(DecisionTreeClassifier(**study.best_params, random_state=42))
params = {k: round(v, 5) if isinstance(v, float) else v
for k, v in study.best_params.items()}
return best.fit(X_fit, y_fit), params
TUNERS = {"logistic": tune_logistic, "tree": tune_tree}
# --- 7. Nested CV: both tuners run inside the same outer folds ----------------
nested = {name: [] for name in TUNERS}
for train_idx, valid_idx in cv5.split(X_train, y_train):
X_inner, y_inner = X_train.iloc[train_idx], y_train.iloc[train_idx]
X_outer, y_outer = X_train.iloc[valid_idx], y_train.iloc[valid_idx]
for name, tune in TUNERS.items():
model, _ = tune(X_inner, y_inner)
proba_outer = model.predict_proba(X_outer)[:, 1]
nested[name].append(average_precision_score(y_outer, proba_outer))
print("\nNested CV (5 outer folds, AP)")
for name, scores in nested.items():
print(f" {name:<9} {np.mean(scores):.3f} +/- {np.std(scores):.3f}")
winner = max(nested, key=lambda name: np.mean(nested[name]))
chosen_pipeline, chosen_params = TUNERS[winner](X_train, y_train)
print(f"Chosen family: {winner}, refitted on all training rows with {chosen_params}")
# --- 8. Tune the threshold for the campaign profit -----------------------------
def campaign_profit(y_true, y_pred):
tn, fp, fn, tp = confusion_matrix(y_true, y_pred, labels=[0, 1]).ravel()
return (CHURNER_VALUE - CALL_COST) * tp - CALL_COST * fp
final_model = TunedThresholdClassifierCV(
chosen_pipeline, scoring=make_scorer(campaign_profit), cv=cv5, random_state=42,
).fit(X_train, y_train)
print(f"\nTuned threshold {final_model.best_threshold_:.3f}"
f" (break-even {CALL_COST / CHURNER_VALUE:.2f})")
# --- 9. Final report on the test set ----------------------------------------
proba = final_model.predict_proba(X_test)[:, 1]
pred = final_model.predict(X_test)
everybody = np.ones_like(y_test)
print("\nFinal test report")
print(f" ROC-AUC {roc_auc_score(y_test, proba):.3f},"
f" AP {average_precision_score(y_test, proba):.3f}")
print(f" precision {precision_score(y_test, pred):.3f},"
f" recall {recall_score(y_test, pred):.3f}, calls {pred.sum()} of {len(pred)}")
print(f" profit: model {campaign_profit(y_test, pred)},"
f" call nobody 0, call everybody {campaign_profit(y_test, everybody)}")
assert np.mean(nested[winner]) > y_train.mean() + 0.2
assert campaign_profit(y_test, pred) > campaign_profit(y_test, everybody)
Output
train (3750, 12), churn 0.193
test (1250, 12), churn 0.193
Baselines (5-fold CV)
dummy ROC-AUC 0.500 AP 0.193
logistic ROC-AUC 0.813 AP 0.553
Learning curve (logistic, AP)
sizes [750, 1500, 3000] valid [0.543, 0.546, 0.553]
at 3000 rows: train 0.560, valid 0.553, gap 0.007
verdict: small gap and flat curve -> high bias; more rows will not help much
Nested CV (5 outer folds, AP)
logistic 0.552 +/- 0.025
tree 0.504 +/- 0.031
Chosen family: logistic, refitted on all training rows with {'C': 0.421, 'class_weight': None}
Tuned threshold 0.223 (break-even 0.20)
Final test report
ROC-AUC 0.813, AP 0.557
precision 0.406, recall 0.739, calls 438 of 1250
profit: model 18080, call nobody 0, call everybody -1800

How it works:

  1. The test set is split off first and used only in step 9. Every decision before it (family, hyperparameters, threshold) uses cross-validation on the training set.
  2. The dummy model’s average precision equals the churn rate. The default logistic regression nearly triples it, so the features carry real signal.
  3. The learning curve has a small gap and a validation score that barely grows from half of the rows to all of them: high bias. More customers will not help much; better features or a more flexible model might.
  4. Each tuner is a complete procedure: search on the rows it gets, then refit. That is what nested CV needs. The outer loop calls both tuners on four-fifths of the training data and scores what they return on the fifth they never saw.
  5. Both families face the same outer folds, so their nested means are a fair comparison. Comparing logistic_search.best_score_ with study.best_value would not be: each is the best of many noisy scores, and the two searches try different numbers of candidates (15 random draws, 20 adaptive trials), so their selection biases differ. The logistic regression wins clearly (0.552 vs 0.504, about two standard deviations apart) and is also easier to explain. Its nested mean is the honest answer to “how good will this procedure be?”. Choosing the larger of two nested means adds a little optimism of its own, but with two candidates and a gap this large it is negligible.
  6. TunedThresholdClassifierCV refits the best pipeline and chooses the threshold with the best mean profit across 5 folds. If the search chose class_weight="balanced", the probabilities are shifted upward and the tuned threshold lands above 0.2; with unweighted probabilities, it lands near 0.2.
  7. The final report compares the model with two policies that need no model. Calling everybody loses money, because most customers would stay anyway. The model’s profit is what the team can plan with, and the nested estimate tells them how much to trust the ranking.