Mini Project: An End-to-End Evaluation Report
A telecom company wants to call customers who are about to leave and offer them a better deal. You will build the model behind that list, and, more importantly, the evidence that it works: two candidate models, metrics chosen for the business goal, tuning with nested cross-validation, calibration, error analysis by slice, a robustness check against simulated changes, and a model-card style report. Each step is a complete program; run them in order or one at a time. The steps use almost every section of the course, and each one links back to its lesson.
About the data. Real churn data would come from billing and support systems; it is personal data, so its use needs a legal basis, access controls and a retention period (Data for ML covers sources, privacy and consent). Here a generator builds 2400 customers: region, contract type, months as a customer, monthly charge, support calls last quarter, paperless billing, and whether they left within three months. Churn follows a known logistic formula with one interaction (support calls hurt more on monthly contracts) and is random given the inputs, so no model can be perfect. The generator also takes three "what if" arguments used in step 7.
The business goal, and the metrics it implies
The retention team can call 15 % of customers per quarter. A call costs 8; a churner who is called stays with probability 0.35 and is then worth 240. So the model's job is to rank customers so the top 15 % contains as many churners as possible, and its probabilities should be trustworthy, because finance multiplies them by 240 to forecast the saved revenue.
| Need | Metric | Lesson |
|---|---|---|
| a good ranking where churners are the minority (23 %) | average precision (AP, the area under the PR curve), the main metric; ROC-AUC as a second view | ROC-AUC, PR-AUC and Average Precision |
| a good list at the team's capacity | precision and recall among the top 15 % | Classification Metrics |
| trustworthy probabilities | log loss, Brier score, expected calibration error (ECE) | Log Loss, Calibration |
| money | campaign value: |
Accuracy is not on the list: a model that predicts "stays" for everyone is 77 % accurate and useless.
Step 1: look at the data and put the test set aside
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import HistGradientBoostingClassifier
def make_customers(n=2400, seed=0, price_rise=0.0, region_mix=(0.4, 0.3, 0.2, 0.1), competitor=0.0):
"""Generated telecom customers (one row each) and whether they left within 3 months.
price_rise and region_mix shift the inputs; competitor raises the risk of monthly customers."""
rng = np.random.default_rng(seed)
region = rng.choice(["north", "south", "east", "west"], n, p=region_mix)
contract = rng.choice(["monthly", "one-year", "two-year"], n, p=[0.5, 0.3, 0.2])
tenure = np.round(rng.gamma(2.0, 14, n)).clip(1, 72) # months as a customer
charge = np.round(rng.normal(60, 18, n).clip(15, 120) * (1 + price_rise), 1)
calls = rng.poisson(np.where(region == "west", 2.2, 1.2)) # support calls last quarter
paperless = (rng.random(n) < 0.6).astype(int)
monthly = (contract == "monthly").astype(float)
z = (-2.2 + 1.6 * monthly - 0.9 * (contract == "two-year") - 0.035 * tenure + 0.025 * (charge - 60)
+ 0.25 * calls + 0.35 * calls * monthly + 0.3 * paperless + competitor * monthly)
churn = (rng.random(n) < 1 / (1 + np.exp(-z))).astype(int)
return pd.DataFrame({"region": region, "contract": contract, "tenure_m": tenure, "charge": charge,
"support_calls": calls, "paperless": paperless, "churn": churn})
df = make_customers()
X, y = df.drop(columns="churn"), df["churn"].to_numpy()
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
cat, num = ["region", "contract"], ["tenure_m", "charge", "support_calls", "paperless"]
logreg = make_pipeline(ColumnTransformer([("num", StandardScaler(), num), ("cat", OneHotEncoder(), cat)]),
LogisticRegression(max_iter=1000))
boost = make_pipeline(ColumnTransformer([("cat", OrdinalEncoder(), cat)], remainder="passthrough"),
HistGradientBoostingClassifier(categorical_features=[0, 1], early_stopping=False, random_state=0))
print(df.head().to_string())
print(f"{len(df)} customers, churn rate {df.churn.mean():.3f}")
print(df.groupby("contract").churn.agg(["size", "mean"]).round(3).to_string())
print(f"train {len(y_tr)} rows (churn {y_tr.mean():.3f}), test {len(y_te)} rows (churn {y_te.mean():.3f}), test set put aside") region contract tenure_m charge support_calls paperless churn
0 south monthly 11.0 70.7 0 1 1
1 north monthly 50.0 69.9 1 0 0
2 north one-year 22.0 79.3 3 0 0
3 north two-year 20.0 50.9 1 0 0
4 east monthly 16.0 29.8 1 1 1
2400 customers, churn rate 0.230
size mean
contract
monthly 1185 0.403
one-year 721 0.075
two-year 494 0.040
train 1800 rows (churn 0.230), test 600 rows (churn 0.230), test set put aside
Churn is 23 %, and contract type dominates it: 40 % of monthly customers leave, against 7.5 % and 4 % on one- and two-year contracts. The stratified split keeps the churn rate equal in both parts. The 600 test rows are now put aside: no step before step 5 looks at them (holdout and k-fold).
Step 2: two models, cross-validated
The candidates are a regularised logistic regression (scaled numbers, one-hot categories) and gradient-boosted trees (scikit-learn's HistGradientBoostingClassifier with its default settings and native categorical splits). Each is a pipeline, so preprocessing is fitted inside each training fold (the leakage rules). Both share the same five stratified folds (stratified cross-validation), and the custom scorer computes precision among the top 15 % of each validation fold.
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import cross_validate
from sklearn.metrics import make_scorer
def make_customers(n=2400, seed=0, price_rise=0.0, region_mix=(0.4, 0.3, 0.2, 0.1), competitor=0.0):
"""Generated telecom customers (one row each) and whether they left within 3 months.
price_rise and region_mix shift the inputs; competitor raises the risk of monthly customers."""
rng = np.random.default_rng(seed)
region = rng.choice(["north", "south", "east", "west"], n, p=region_mix)
contract = rng.choice(["monthly", "one-year", "two-year"], n, p=[0.5, 0.3, 0.2])
tenure = np.round(rng.gamma(2.0, 14, n)).clip(1, 72) # months as a customer
charge = np.round(rng.normal(60, 18, n).clip(15, 120) * (1 + price_rise), 1)
calls = rng.poisson(np.where(region == "west", 2.2, 1.2)) # support calls last quarter
paperless = (rng.random(n) < 0.6).astype(int)
monthly = (contract == "monthly").astype(float)
z = (-2.2 + 1.6 * monthly - 0.9 * (contract == "two-year") - 0.035 * tenure + 0.025 * (charge - 60)
+ 0.25 * calls + 0.35 * calls * monthly + 0.3 * paperless + competitor * monthly)
churn = (rng.random(n) < 1 / (1 + np.exp(-z))).astype(int)
return pd.DataFrame({"region": region, "contract": contract, "tenure_m": tenure, "charge": charge,
"support_calls": calls, "paperless": paperless, "churn": churn})
df = make_customers()
X, y = df.drop(columns="churn"), df["churn"].to_numpy()
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
cat, num = ["region", "contract"], ["tenure_m", "charge", "support_calls", "paperless"]
logreg = make_pipeline(ColumnTransformer([("num", StandardScaler(), num), ("cat", OneHotEncoder(), cat)]),
LogisticRegression(max_iter=1000))
boost = make_pipeline(ColumnTransformer([("cat", OrdinalEncoder(), cat)], remainder="passthrough"),
HistGradientBoostingClassifier(categorical_features=[0, 1], early_stopping=False, random_state=0))
def precision_at(y_true, score, share=0.15):
"""Share of churners among the 15 % of customers with the highest scores: the ones the team would call."""
top = np.argsort(-score)[:int(round(share * len(score)))]
return y_true[top].mean()
scoring = {"AP": "average_precision", "ROC-AUC": "roc_auc", "log loss": "neg_log_loss", "Brier": "neg_brier_score",
"prec@15%": make_scorer(precision_at, response_method="predict_proba")}
cv = StratifiedKFold(5, shuffle=True, random_state=0)
for name, model in {"logistic regression": logreg, "gradient boosting": boost}.items():
r = cross_validate(model, X_tr, y_tr, cv=cv, scoring=scoring)
print(name)
for k in scoring:
s = np.abs(r["test_" + k]) # scikit-learn negates losses so that higher is better
print(f" {k:9s} {s.mean():.3f} +/- {s.std():.3f}")logistic regression
AP 0.632 +/- 0.045
ROC-AUC 0.842 +/- 0.023
log loss 0.396 +/- 0.025
Brier 0.126 +/- 0.007
prec@15% 0.667 +/- 0.035
gradient boosting
AP 0.533 +/- 0.048
ROC-AUC 0.803 +/- 0.023
log loss 0.487 +/- 0.046
Brier 0.150 +/- 0.012
prec@15% 0.559 +/- 0.061
With default settings, logistic regression is better on every metric: AP 0.632 against 0.533, and two thirds of its top-15 % list are real churners, against 56 %. The boosted model's higher log loss and Brier score say its probabilities are worse too. Defaults are not a fair comparison, though: 100 trees of up to 31 leaves at learning rate 0.1 are a lot of capacity for 1440 training rows per fold. That is a tuning question.
Step 3: tune both with nested cross-validation
Tuning on the same folds you report would make the reported score optimistic, because the best of several noisy scores is biased upwards. Nested cross-validation wraps the search in an outer loop: inside each outer training part, a 3-fold grid search picks the hyperparameters, and the outer validation fold scores that choice (Nested Cross-Validation, Grid and Random Search). The nested score estimates the whole procedure "tune, then fit"; the final hyperparameters are then chosen once more on all training rows.
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import GridSearchCV, cross_val_score
def make_customers(n=2400, seed=0, price_rise=0.0, region_mix=(0.4, 0.3, 0.2, 0.1), competitor=0.0):
"""Generated telecom customers (one row each) and whether they left within 3 months.
price_rise and region_mix shift the inputs; competitor raises the risk of monthly customers."""
rng = np.random.default_rng(seed)
region = rng.choice(["north", "south", "east", "west"], n, p=region_mix)
contract = rng.choice(["monthly", "one-year", "two-year"], n, p=[0.5, 0.3, 0.2])
tenure = np.round(rng.gamma(2.0, 14, n)).clip(1, 72) # months as a customer
charge = np.round(rng.normal(60, 18, n).clip(15, 120) * (1 + price_rise), 1)
calls = rng.poisson(np.where(region == "west", 2.2, 1.2)) # support calls last quarter
paperless = (rng.random(n) < 0.6).astype(int)
monthly = (contract == "monthly").astype(float)
z = (-2.2 + 1.6 * monthly - 0.9 * (contract == "two-year") - 0.035 * tenure + 0.025 * (charge - 60)
+ 0.25 * calls + 0.35 * calls * monthly + 0.3 * paperless + competitor * monthly)
churn = (rng.random(n) < 1 / (1 + np.exp(-z))).astype(int)
return pd.DataFrame({"region": region, "contract": contract, "tenure_m": tenure, "charge": charge,
"support_calls": calls, "paperless": paperless, "churn": churn})
df = make_customers()
X, y = df.drop(columns="churn"), df["churn"].to_numpy()
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
cat, num = ["region", "contract"], ["tenure_m", "charge", "support_calls", "paperless"]
logreg = make_pipeline(ColumnTransformer([("num", StandardScaler(), num), ("cat", OneHotEncoder(), cat)]),
LogisticRegression(max_iter=1000))
boost = make_pipeline(ColumnTransformer([("cat", OrdinalEncoder(), cat)], remainder="passthrough"),
HistGradientBoostingClassifier(categorical_features=[0, 1], early_stopping=False, random_state=0))
grids = {
"logistic regression": (logreg, {"logisticregression__C": [0.01, 0.1, 1, 10]}),
"gradient boosting": (boost, {"histgradientboostingclassifier__learning_rate": [0.03, 0.1],
"histgradientboostingclassifier__max_leaf_nodes": [4, 15]}),
}
outer = StratifiedKFold(5, shuffle=True, random_state=1) # estimates how good the whole tuning procedure is
inner = StratifiedKFold(3, shuffle=True, random_state=2) # chooses the hyperparameters inside each outer fold
for name, (model, grid) in grids.items():
search = GridSearchCV(model, grid, cv=inner, scoring="average_precision")
nested = cross_val_score(search, X_tr, y_tr, cv=outer, scoring="average_precision")
best = search.fit(X_tr, y_tr).best_params_ # the final choice, made on all training rows
print(f"{name:20s} nested AP {nested.mean():.3f} +/- {nested.std():.3f} chosen: "
+ ", ".join(f"{k.split('__')[1]}={v}" for k, v in best.items()))logistic regression nested AP 0.623 +/- 0.035 chosen: C=10
gradient boosting nested AP 0.620 +/- 0.048 chosen: learning_rate=0.03, max_leaf_nodes=4
Tuning closes the gap: boosting with small trees (4 leaves) and a lower learning rate reaches a nested AP of 0.620, logistic regression 0.623. The difference, 0.003, is a tenth of the fold-to-fold spread (0.035 and 0.048). On this evidence the two models are tied, and the rule for a tie is to prefer the simpler, cheaper, more explainable model. Before deciding, check the probabilities.
Step 4: calibration, chosen on a validation split
Calibration methods are fitted inside CalibratedClassifierCV with 5 internal folds (Calibration): sigmoid is Platt scaling, isotonic a monotone step function. They are compared on a validation split of the training rows (450 customers), never on the test set.
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.base import clone
from sklearn.calibration import CalibratedClassifierCV
from sklearn.metrics import brier_score_loss, log_loss
def make_customers(n=2400, seed=0, price_rise=0.0, region_mix=(0.4, 0.3, 0.2, 0.1), competitor=0.0):
"""Generated telecom customers (one row each) and whether they left within 3 months.
price_rise and region_mix shift the inputs; competitor raises the risk of monthly customers."""
rng = np.random.default_rng(seed)
region = rng.choice(["north", "south", "east", "west"], n, p=region_mix)
contract = rng.choice(["monthly", "one-year", "two-year"], n, p=[0.5, 0.3, 0.2])
tenure = np.round(rng.gamma(2.0, 14, n)).clip(1, 72) # months as a customer
charge = np.round(rng.normal(60, 18, n).clip(15, 120) * (1 + price_rise), 1)
calls = rng.poisson(np.where(region == "west", 2.2, 1.2)) # support calls last quarter
paperless = (rng.random(n) < 0.6).astype(int)
monthly = (contract == "monthly").astype(float)
z = (-2.2 + 1.6 * monthly - 0.9 * (contract == "two-year") - 0.035 * tenure + 0.025 * (charge - 60)
+ 0.25 * calls + 0.35 * calls * monthly + 0.3 * paperless + competitor * monthly)
churn = (rng.random(n) < 1 / (1 + np.exp(-z))).astype(int)
return pd.DataFrame({"region": region, "contract": contract, "tenure_m": tenure, "charge": charge,
"support_calls": calls, "paperless": paperless, "churn": churn})
def ece(y, p, bins=10):
"""Expected calibration error: |mean p - churn rate| per probability bin, weighted by the bin's share."""
idx = np.minimum((p * bins).astype(int), bins - 1)
return sum(abs(p[idx == b].mean() - y[idx == b].mean()) * np.mean(idx == b) for b in range(bins) if np.any(idx == b))
df = make_customers()
X, y = df.drop(columns="churn"), df["churn"].to_numpy()
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
cat, num = ["region", "contract"], ["tenure_m", "charge", "support_calls", "paperless"]
logreg = make_pipeline(ColumnTransformer([("num", StandardScaler(), num), ("cat", OneHotEncoder(), cat)]),
LogisticRegression(max_iter=1000))
boost = make_pipeline(ColumnTransformer([("cat", OrdinalEncoder(), cat)], remainder="passthrough"),
HistGradientBoostingClassifier(categorical_features=[0, 1], early_stopping=False, random_state=0))
# A validation split inside the training rows: calibration is chosen here, never on the test set
X_fit, X_val, y_fit, y_val = train_test_split(X_tr, y_tr, test_size=0.25, random_state=0, stratify=y_tr)
models = {"logistic, C=10": logreg.set_params(logisticregression__C=10),
"boosting, tuned": clone(boost).set_params(histgradientboostingclassifier__learning_rate=0.03,
histgradientboostingclassifier__max_leaf_nodes=4),
"boosting, default": boost}
print(f"{'model':18s} {'calibration':11s} Brier log loss ECE")
for name, model in models.items():
for method in ["none", "sigmoid", "isotonic"]:
m = clone(model) if method == "none" else CalibratedClassifierCV(clone(model), method=method, cv=5)
p = m.fit(X_fit, y_fit).predict_proba(X_val)[:, 1]
print(f"{name:18s} {method:11s} {brier_score_loss(y_val, p):.4f} {log_loss(y_val, p):.4f} {ece(y_val, p):.3f}")model calibration Brier log loss ECE
logistic, C=10 none 0.1243 0.3914 0.033
logistic, C=10 sigmoid 0.1247 0.3915 0.036
logistic, C=10 isotonic 0.1270 0.4780 0.052
boosting, tuned none 0.1233 0.3883 0.055
boosting, tuned sigmoid 0.1210 0.3798 0.039
boosting, tuned isotonic 0.1211 0.3804 0.032
boosting, default none 0.1485 0.4808 0.085
boosting, default sigmoid 0.1356 0.4209 0.023
boosting, default isotonic 0.1365 0.4277 0.027
Three findings:
- Logistic regression is already calibrated (ECE 0.033). Platt scaling changes almost nothing, and isotonic regression makes it worse: its log loss jumps to 0.478 because the step function, fitted on small folds, gives some customers a probability of exactly 0 or close to it, and a churner among them costs a huge log loss.
- The default boosted model is overconfident (ECE 0.085). Both calibrators fix most of that (ECE 0.023 and 0.027), but its ranking stays worse, so calibration cannot rescue it.
- Tuned boosting with Platt scaling has the lowest Brier score (0.1210 against 0.1243 for logistic regression). On 450 rows a difference of 0.003 is well inside the noise.
Decision: logistic regression with , no calibration step. It ties on ranking, its probabilities are already good, it trains in milliseconds and its coefficients can be explained to the retention team. Write the decision and the reason down before step 5: the test set must not influence it.
Step 5: the final test, once
The chosen model is refitted on all 1800 training rows and scored once on the 600 test customers.
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import average_precision_score, roc_auc_score, brier_score_loss
def make_customers(n=2400, seed=0, price_rise=0.0, region_mix=(0.4, 0.3, 0.2, 0.1), competitor=0.0):
"""Generated telecom customers (one row each) and whether they left within 3 months.
price_rise and region_mix shift the inputs; competitor raises the risk of monthly customers."""
rng = np.random.default_rng(seed)
region = rng.choice(["north", "south", "east", "west"], n, p=region_mix)
contract = rng.choice(["monthly", "one-year", "two-year"], n, p=[0.5, 0.3, 0.2])
tenure = np.round(rng.gamma(2.0, 14, n)).clip(1, 72) # months as a customer
charge = np.round(rng.normal(60, 18, n).clip(15, 120) * (1 + price_rise), 1)
calls = rng.poisson(np.where(region == "west", 2.2, 1.2)) # support calls last quarter
paperless = (rng.random(n) < 0.6).astype(int)
monthly = (contract == "monthly").astype(float)
z = (-2.2 + 1.6 * monthly - 0.9 * (contract == "two-year") - 0.035 * tenure + 0.025 * (charge - 60)
+ 0.25 * calls + 0.35 * calls * monthly + 0.3 * paperless + competitor * monthly)
churn = (rng.random(n) < 1 / (1 + np.exp(-z))).astype(int)
return pd.DataFrame({"region": region, "contract": contract, "tenure_m": tenure, "charge": charge,
"support_calls": calls, "paperless": paperless, "churn": churn})
def ece(y, p, bins=10):
"""Expected calibration error: |mean p - churn rate| per probability bin, weighted by the bin's share."""
idx = np.minimum((p * bins).astype(int), bins - 1)
return sum(abs(p[idx == b].mean() - y[idx == b].mean()) * np.mean(idx == b) for b in range(bins) if np.any(idx == b))
df = make_customers()
X, y = df.drop(columns="churn"), df["churn"].to_numpy()
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
cat, num = ["region", "contract"], ["tenure_m", "charge", "support_calls", "paperless"]
logreg = make_pipeline(ColumnTransformer([("num", StandardScaler(), num), ("cat", OneHotEncoder(), cat)]),
LogisticRegression(max_iter=1000))
boost = make_pipeline(ColumnTransformer([("cat", OrdinalEncoder(), cat)], remainder="passthrough"),
HistGradientBoostingClassifier(categorical_features=[0, 1], early_stopping=False, random_state=0))
def campaign_value(called, y, save_rate=0.35, value=240, cost=8):
"""Each call costs 8; a called churner stays with probability 0.35 and is worth 240."""
return save_rate * value * y[called].sum() - cost * called.sum()
model = logreg.set_params(logisticregression__C=10).fit(X_tr, y_tr) # final model, refitted on all training rows
p = model.predict_proba(X_te)[:, 1] # the one and only look at the test set
n_call = int(round(0.15 * len(y_te)))
called = np.zeros(len(y_te), bool)
called[np.argsort(-p)[:n_call]] = True
print(f"test rows {len(y_te)}, churners {y_te.sum()}, calls allowed {n_call}")
print(f"AP {average_precision_score(y_te, p):.3f} ROC-AUC {roc_auc_score(y_te, p):.3f} "
f"Brier {brier_score_loss(y_te, p):.3f} ECE {ece(y_te, p):.3f}")
print(f"precision@15% {y_te[called].mean():.3f} recall@15% {y_te[called].sum() / y_te.sum():.3f}")
rule = ((X_te.contract == "monthly") & (X_te.support_calls >= 3)).to_numpy()
print(f"campaign value: model {campaign_value(called, y_te):.0f}, random 15 % (expected) "
f"{n_call * (0.35 * 240 * y_te.mean() - 8):.0f}, rule 'monthly and 3+ calls' ({rule.sum()} calls) "
f"{campaign_value(rule, y_te):.0f}")test rows 600, churners 138, calls allowed 90
AP 0.652 ROC-AUC 0.861 Brier 0.121 ECE 0.034
precision@15% 0.700 recall@15% 0.457
campaign value: model 4572, random 15 % (expected) 1019, rule 'monthly and 3+ calls' (33 calls) 1584
The test AP (0.652) is a little above the nested estimate (0.623 with a spread of 0.035), well inside the range the folds suggested; ROC-AUC 0.861. The ECE of 0.034 confirms the probabilities. At the team's capacity, 70 % of the 90 calls reach real churners and the list contains 46 % of all churners. In money, the model's list is worth about 4572 per 600 customers, against about 1019 for 90 random calls and 1584 for the obvious hand-written rule "monthly contract and three or more support calls" (which also finds only 33 customers to call). Those three numbers are the ones to show the business.
Step 6: error analysis by slice
A single score hides who the model fails. Slice the test predictions by contract, region and tenure (Error Analysis and Slices).
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import average_precision_score
def make_customers(n=2400, seed=0, price_rise=0.0, region_mix=(0.4, 0.3, 0.2, 0.1), competitor=0.0):
"""Generated telecom customers (one row each) and whether they left within 3 months.
price_rise and region_mix shift the inputs; competitor raises the risk of monthly customers."""
rng = np.random.default_rng(seed)
region = rng.choice(["north", "south", "east", "west"], n, p=region_mix)
contract = rng.choice(["monthly", "one-year", "two-year"], n, p=[0.5, 0.3, 0.2])
tenure = np.round(rng.gamma(2.0, 14, n)).clip(1, 72) # months as a customer
charge = np.round(rng.normal(60, 18, n).clip(15, 120) * (1 + price_rise), 1)
calls = rng.poisson(np.where(region == "west", 2.2, 1.2)) # support calls last quarter
paperless = (rng.random(n) < 0.6).astype(int)
monthly = (contract == "monthly").astype(float)
z = (-2.2 + 1.6 * monthly - 0.9 * (contract == "two-year") - 0.035 * tenure + 0.025 * (charge - 60)
+ 0.25 * calls + 0.35 * calls * monthly + 0.3 * paperless + competitor * monthly)
churn = (rng.random(n) < 1 / (1 + np.exp(-z))).astype(int)
return pd.DataFrame({"region": region, "contract": contract, "tenure_m": tenure, "charge": charge,
"support_calls": calls, "paperless": paperless, "churn": churn})
df = make_customers()
X, y = df.drop(columns="churn"), df["churn"].to_numpy()
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
cat, num = ["region", "contract"], ["tenure_m", "charge", "support_calls", "paperless"]
logreg = make_pipeline(ColumnTransformer([("num", StandardScaler(), num), ("cat", OneHotEncoder(), cat)]),
LogisticRegression(max_iter=1000))
boost = make_pipeline(ColumnTransformer([("cat", OrdinalEncoder(), cat)], remainder="passthrough"),
HistGradientBoostingClassifier(categorical_features=[0, 1], early_stopping=False, random_state=0))
model = logreg.set_params(logisticregression__C=10).fit(X_tr, y_tr)
p = model.predict_proba(X_te)[:, 1]
called = np.zeros(len(y_te), bool)
called[np.argsort(-p)[:90]] = True # the 90 customers the team would call
res = X_te.assign(churn=y_te, p=p, called=called,
tenure=pd.cut(X_te.tenure_m, [0, 12, 36, 72], labels=["0-12", "13-36", "37-72"]))
def slice_table(col):
g = res.groupby(col, observed=True)
return pd.DataFrame({
"n": g.size(), "churn": g.churn.mean().round(3), "mean p": g.p.mean().round(3),
"AP": g.apply(lambda s: average_precision_score(s.churn, s.p), include_groups=False).round(3),
"calls": g.called.sum(),
"recall": g.apply(lambda s: s.called[s.churn == 1].mean(), include_groups=False).round(3)})
for col in ["contract", "region", "tenure"]:
print(slice_table(col).to_string(), "\n")
missed = res[(res.churn == 1) & ~res.called].sort_values("p").head(4)
print("churners the model ranked lowest:")
print(missed[["region", "contract", "tenure_m", "charge", "support_calls", "p"]].round(3).to_string()) n churn mean p AP calls recall
contract
monthly 292 0.418 0.384 0.687 90 0.516
one-year 172 0.076 0.075 0.271 0 0.000
two-year 136 0.022 0.054 0.162 0 0.000
n churn mean p AP calls recall
region
east 128 0.266 0.216 0.774 19 0.471
north 237 0.232 0.213 0.633 35 0.455
south 185 0.184 0.217 0.599 25 0.412
west 50 0.300 0.282 0.698 11 0.533
n churn mean p AP calls recall
tenure
0-12 132 0.295 0.320 0.680 36 0.564
13-36 278 0.259 0.245 0.704 50 0.514
37-72 190 0.142 0.116 0.510 4 0.148
churners the model ranked lowest:
region contract tenure_m charge support_calls p
113 north one-year 48.0 55.8 1 0.021
272 north one-year 26.0 46.5 1 0.032
1182 north two-year 17.0 50.9 1 0.042
2141 south one-year 11.0 64.5 0 0.066
What the slices show:
- All 90 calls go to monthly customers, so the 13 one-year and 3 two-year churners in the test set are never called (recall 0). That is the ranking working as designed (their churn rates are 7.6 % and 2.2 %), but the team should know it: a separate, cheaper action, such as an e-mail, may suit those customers better.
- Long-standing customers are hard. Customers with more than three years of tenure churn at 14 %, and the list catches only 15 % of them (AP 0.510). The lowest-ranked churners are exactly that profile: one- or two-year contracts, few support calls, nothing in the data that signals risk. More features (complaints, usage trends) would be needed to find them.
- Calibration roughly holds per slice. The mean predicted probability is within about 3 points of the churn rate in most rows. The largest gap is east (0.216 predicted against 0.266 observed); with 128 customers the standard error of that churn rate is about , so a gap of 0.05 is not yet evidence of a problem, but it is worth watching.
- West is small (50 test customers), so its numbers carry wide uncertainty. Report the slice sizes next to every slice metric.
Step 7: robustness to a simulated shift
The model will be used next quarter, not on the test set. Three simulated quarters, 2400 customers each (Distribution Shift, Robustness Testing):
- no change: a new sample from the same generator;
- inputs shift (covariate shift): prices rise 15 % and the west region, with its higher support load, grows from 10 % to 30 % of customers; the churn formula is unchanged;
- competitor (concept shift): a competitor targets monthly customers, raising their log-odds of churn by 0.8; the inputs are unchanged.
A domain classifier tries to tell training inputs from the new inputs (AUC 0.5 means it cannot), and a perturbation test misrecords the support calls by up to one.
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.base import clone
from sklearn.model_selection import cross_val_score
from sklearn.metrics import average_precision_score, roc_auc_score
def make_customers(n=2400, seed=0, price_rise=0.0, region_mix=(0.4, 0.3, 0.2, 0.1), competitor=0.0):
"""Generated telecom customers (one row each) and whether they left within 3 months.
price_rise and region_mix shift the inputs; competitor raises the risk of monthly customers."""
rng = np.random.default_rng(seed)
region = rng.choice(["north", "south", "east", "west"], n, p=region_mix)
contract = rng.choice(["monthly", "one-year", "two-year"], n, p=[0.5, 0.3, 0.2])
tenure = np.round(rng.gamma(2.0, 14, n)).clip(1, 72) # months as a customer
charge = np.round(rng.normal(60, 18, n).clip(15, 120) * (1 + price_rise), 1)
calls = rng.poisson(np.where(region == "west", 2.2, 1.2)) # support calls last quarter
paperless = (rng.random(n) < 0.6).astype(int)
monthly = (contract == "monthly").astype(float)
z = (-2.2 + 1.6 * monthly - 0.9 * (contract == "two-year") - 0.035 * tenure + 0.025 * (charge - 60)
+ 0.25 * calls + 0.35 * calls * monthly + 0.3 * paperless + competitor * monthly)
churn = (rng.random(n) < 1 / (1 + np.exp(-z))).astype(int)
return pd.DataFrame({"region": region, "contract": contract, "tenure_m": tenure, "charge": charge,
"support_calls": calls, "paperless": paperless, "churn": churn})
def ece(y, p, bins=10):
"""Expected calibration error: |mean p - churn rate| per probability bin, weighted by the bin's share."""
idx = np.minimum((p * bins).astype(int), bins - 1)
return sum(abs(p[idx == b].mean() - y[idx == b].mean()) * np.mean(idx == b) for b in range(bins) if np.any(idx == b))
df = make_customers()
X, y = df.drop(columns="churn"), df["churn"].to_numpy()
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
cat, num = ["region", "contract"], ["tenure_m", "charge", "support_calls", "paperless"]
logreg = make_pipeline(ColumnTransformer([("num", StandardScaler(), num), ("cat", OneHotEncoder(), cat)]),
LogisticRegression(max_iter=1000))
boost = make_pipeline(ColumnTransformer([("cat", OrdinalEncoder(), cat)], remainder="passthrough"),
HistGradientBoostingClassifier(categorical_features=[0, 1], early_stopping=False, random_state=0))
model = logreg.set_params(logisticregression__C=10).fit(X_tr, y_tr)
def report(name, Xs, ys):
p = model.predict_proba(Xs)[:, 1]
k = int(round(0.15 * len(ys)))
top = np.argsort(-p)[:k]
value = 0.35 * 240 * ys[top].sum() - 8 * k
print(f"{name:13s} churn {ys.mean():.3f} mean p {p.mean():.3f} AP {average_precision_score(ys, p):.3f}"
f" ROC-AUC {roc_auc_score(ys, p):.3f} ECE {ece(ys, p):.3f} value/100 {100 * value / len(ys):.0f}")
scenarios = {"no change": make_customers(seed=1),
"inputs shift": make_customers(seed=1, price_rise=0.15, region_mix=(0.25, 0.25, 0.2, 0.3)),
"competitor": make_customers(seed=1, competitor=0.8)}
report("test set", X_te, y_te)
for name, new in scenarios.items():
report(name, new.drop(columns="churn"), new.churn.to_numpy())
# Can a classifier tell the training inputs from the new ones? AUC 0.5 means no visible change
for name, new in scenarios.items():
both = pd.concat([X_tr, new.drop(columns="churn")])
is_new = np.r_[np.zeros(len(X_tr)), np.ones(len(new))]
auc = cross_val_score(clone(boost), both, is_new, cv=StratifiedKFold(5, shuffle=True, random_state=0), scoring="roc_auc")
print(f"domain classifier AUC, {name:12s}: {auc.mean():.3f}")
# Perturbation: support calls misrecorded by -1, 0 or +1
rng = np.random.default_rng(0)
noisy = X_te.assign(support_calls=(X_te.support_calls + rng.integers(-1, 2, len(X_te))).clip(0))
p0, p1 = model.predict_proba(X_te)[:, 1], model.predict_proba(noisy)[:, 1]
print(f"support_calls +/-1 noise: AP {average_precision_score(y_te, p0):.3f} -> {average_precision_score(y_te, p1):.3f},"
f" median |change in p| {np.median(abs(p1 - p0)):.3f}")test set churn 0.230 mean p 0.221 AP 0.652 ROC-AUC 0.861 ECE 0.034 value/100 762
no change churn 0.219 mean p 0.225 AP 0.560 ROC-AUC 0.823 ECE 0.015 value/100 636
inputs shift churn 0.254 mean p 0.264 AP 0.673 ROC-AUC 0.845 ECE 0.017 value/100 790
competitor churn 0.303 mean p 0.225 AP 0.717 ROC-AUC 0.861 ECE 0.078 value/100 836
domain classifier AUC, no change : 0.520
domain classifier AUC, inputs shift: 0.657
domain classifier AUC, competitor : 0.520
support_calls +/-1 noise: AP 0.652 -> 0.580, median |change in p| 0.013
How to read it:
- Sampling noise is large. With no change at all, the AP on a fresh sample is 0.560 instead of 0.652 on the test set. The test set of 600 customers was a little lucky, and the nested estimate (0.623) sits between the two. Quote ranges, not single numbers.
- The input shift is visible and harmless. The domain classifier spots it (AUC 0.657), churn rises to 25.4 %, and the model follows: the mean predicted probability rises to 0.264, ECE stays at 0.017. Because the churn formula did not change, a model that learned it well extrapolates correctly; a model of the wrong shape might not.
- The concept shift is invisible and harmful. The inputs look exactly as before (domain AUC 0.520, the same as no change), yet churn jumps to 30.3 % while the model still predicts 22.5 % on average: ECE 0.078, so the revenue forecast is now about a quarter too low. The ranking still works (ROC-AUC 0.861), and AP even rises because churners are more common. Only monitoring the outcomes (predicted against observed churn per month) catches this kind of shift; monitoring the inputs alone does not.
- Noisy support-call counts cost ranking quality: AP drops from 0.652 to 0.580 when the count is off by one for about two thirds of customers, although the median probability moves by only 0.013. Support calls are the feature to keep clean.
Step 8: the report
Fill in a model card. The first block is the template; the second is the filled version for this project, with every number taken from the outputs above.
MODEL CARD (template)
1. Purpose Decision supported, users, what the model must not be used for.
2. Data Source, period, rows, target definition, licence and privacy notes, known gaps.
3. Split Test set (size, how drawn, when used); validation scheme for every choice.
4. Metrics Main metric and why it fits the goal; secondary metrics; the money metric.
5. Candidates Models compared, how tuned (nested CV), scores with spreads.
6. Choice The model chosen and the reason, written down before the test.
7. Calibration Method compared on validation data; ECE, Brier.
8. Test result Each metric once, compared with the CV estimate.
9. Slices Metrics by group with group sizes; who is served worst and why.
10. Robustness Shifts and perturbations tried; what breaks; what to monitor.
11. Limitations Known failure modes, uncertainty, ethical and legal points.
12. Maintenance Owner, monitoring signals and thresholds, retraining trigger.MODEL CARD: churn ranking for retention calls (generated data, 2400 customers)
1. Purpose Rank customers by 3-month churn risk; the team calls the top 15 %. Not for pricing
or for any decision about an individual beyond offering a retention deal.
2. Data 6 inputs, churn rate 23.0 %; generated, so no privacy issues here (real data: billing
and support records, personal data).
3. Split Stratified 75/25; test set (600) used once, in step 5. Choices made by 5-fold CV,
nested 5 x 3 CV for tuning, and a 450-row validation split for calibration.
4. Metrics Main: average precision. Also ROC-AUC, precision/recall at 15 %, log loss, Brier,
ECE, campaign value (0.35 x 240 per reached churner, 8 per call).
5. Candidates Logistic regression: nested AP 0.623 +/- 0.035. Gradient boosting: 0.620 +/- 0.048
(default settings 0.533).
6. Choice Logistic regression, C = 10: tied on AP, simpler and explainable, calibrated.
7. Calibration None needed (validation ECE 0.033); isotonic made log loss worse.
8. Test AP 0.652, ROC-AUC 0.861, Brier 0.121, ECE 0.034; precision@15 % 0.700,
recall@15 % 0.457; value 4572 per 600 customers (random calls 1019, rule 1584).
9. Slices Calls all go to monthly contracts; one-/two-year churners never reached.
Tenure > 36 months: AP 0.510, recall 0.148. West: only 50 test rows.
10. Robustness New sample: AP 0.560 (sampling noise). Price/region shift: detected (domain AUC
0.657), model stays calibrated. Competitor (concept) shift: not detected by inputs
(AUC 0.520), ECE 0.078, forecasts too low. Support-call noise: AP 0.652 -> 0.580.
11. Limits Misses low-signal long-tenure churners. Probabilities break under concept shift.
12. Maintain Monthly: predicted vs observed churn (alert if the gap exceeds 3 points), domain
classifier AUC on inputs (alert above 0.6), AP on labelled outcomes.
Retrain on alert or every quarter, with the same evaluation protocol.Extensions
- Add the interaction
support_calls x monthlyas a feature of the logistic regression. Does its nested AP move beyond the fold spread? (The generator contains that interaction.) - Replace the grid search of step 3 with
RandomizedSearchCVover a log-uniformCand learning rate (Grid and Random Search), or with the Gaussian-process search of Bayesian Optimisation. - In step 7, refit the model on 600 customers from the "competitor" quarter (labels arrive three months later) and measure how much of the calibration gap a refit closes. Then try only recalibrating the old model with Platt scaling on those 600 rows.
- Bootstrap the 600 test rows (1000 resamples) to put a 95 % interval on the test AP (Holdout and K-Fold). Does it contain the "no change" value of 0.560?
- Change the business numbers: a call costs 30 instead of 8. Is calling 15 % still worth it, and which share of customers maximises the campaign value (Log Loss and Choosing a Threshold)?
Test yourself
Why is average precision the main metric here instead of accuracy?
- Average precision is always better
- The goal is to rank a minority class (23 % churners) so the top of the list is rich in churners; accuracy rewards predicting 'stays' for everyone
- Accuracy cannot be computed for logistic regression
- Average precision measures calibration
Why does step 3 use nested cross-validation instead of reporting the best grid-search score?
- It is faster
- The best of several noisy scores is optimistic; the outer loop scores the whole tune-then-fit procedure on data the search never saw
- Grid search cannot use stratified folds
- To calibrate the probabilities
Logistic regression's validation log loss rose from 0.391 to 0.478 with isotonic calibration. What is the likely reason?
- Isotonic regression is not monotone
- The step function, fitted on small folds, gives some customers probabilities near 0, and a churner among them is punished heavily by log loss
- Logistic regression cannot be calibrated
- The Brier score was used by mistake
In step 7 the competitor scenario has a domain-classifier AUC of 0.520, but ECE jumps to 0.078. What does that show?
- The model is broken for every scenario
- Concept shift changes how inputs relate to the outcome without changing the inputs, so input monitoring misses it; only outcome monitoring catches it
- The domain classifier was trained wrongly
- Covariate shift is always harmless
With no change at all, the AP on a new sample was 0.560 against 0.652 on the test set. What is the right lesson?
- The model overfits the test set
- A 600-row test set gives a noisy estimate; report a range (the nested CV spread or a bootstrap interval), not a single number
- The generator is broken
- AP is not a valid metric