Part 5 checkpoint
This checkpoint tests Part 5 as a whole. Each exercise is a piece of real modeling work on the course datasets, and most of them follow the same path: the math behind the model, the features, a pipeline, a model choice with cross-validation, one read of the test set, an explanation of the result and, at the end, a model that runs as a service. Most exercises mix two to four modules. Some reuse a dataset or a model from a module, but each asks a new question of it.
Four rules hold on every exercise of this page, as in every real project:
- Every step that learns from data (an imputer, a scaler, an encoder, a feature selector) learns from training rows only, inside a pipeline wherever a model is cross-validated. Gaps in a time series are filled forward, so no gap uses a later value.
- You make every choice (features, model, hyperparameters, threshold) on cross-validation or a validation split.
- You read the test set once, at the end, for the model that you already chose.
- You report the result that you got, even when it disappoints.
How to use it:
- Work without your notes first. Read the task and the expected output, then write your code.
- Stuck for more than 10 minutes? Open one hint at a time.
- Open the solution only after a real attempt. Compare your code, your numbers and your written reasoning with it.
- Score yourself with the rubric at the end of the page.
Plan about 9 to 13 hours in total: 15–20 minutes for each of the 3 warm-ups, 30–45 minutes for each of the 10 core exercises and 60–90 minutes for each of the 3 challenges. You can split the work over several sessions.
| Exercise | Tier | Type | Modules |
|---|---|---|---|
| P5-01 | Warm-up | Predict the output | 32, 33, 34, 42 |
| P5-02 | Warm-up | Fix the bugs | 33, 34, 36, 41 |
| P5-03 | Warm-up | Write the code | 34, 35, 36, 40 |
| P5-04 | Core | Write the code | 32, 36, 42 |
| P5-05 | Core | Write the code | 32, 33, 34, 35 |
| P5-06 | Core | Choose and justify | 36, 37, 40, 41 |
| P5-07 | Core | Interpret a result | 35, 37, 38 |
| P5-08 | Core | Write the code | 32, 36, 37 |
| P5-09 | Core | Interpret a result | 32, 39, 41 |
| P5-10 | Core | Interpret a result | 36, 43 |
| P5-11 | Core | Interpret a result | 33, 34, 39 |
| P5-12 | Core | Write the code | 37, 38, 40 |
| P5-13 | Core | Choose and justify | 35, 38, 44 |
| P5-14 | Challenge | Write the code | 34, 36, 39, 44 |
| P5-15 | Challenge | Fix the method | 33, 35, 37, 43 |
| P5-16 | Challenge | Refactor | 34, 37, 38, 42 |
Work in your course project folder with Python 3.12 or newer and the virtual environment of the course. The data/ folder from Get the data must be in that folder, because every path on this page is relative to it (data/customers.csv). The data dictionary lists the facts and the reference scores that you can check your results against. Run each exercise as its own script, for example python p5_05.py. A chart window opens at each plt.show(); close it to continue. Scripts that save models write them to models/ in the current folder, never into data/.
Every exercise starts from this block. It imports the scikit-learn pieces that most exercises use, fixes how pandas prints tables and names the feature columns of the churn data. Each exercise imports anything else it needs.
import numpy as npimport pandas as pdfrom lightgbm import LGBMClassifier # load before torch; the reverse can crashfrom sklearn.compose import ColumnTransformerfrom sklearn.dummy import DummyClassifier, DummyRegressorfrom sklearn.ensemble import ( HistGradientBoostingClassifier, HistGradientBoostingRegressor,)from sklearn.impute import SimpleImputerfrom sklearn.linear_model import LogisticRegression, Ridgefrom sklearn.metrics import average_precision_score, mean_absolute_error, roc_auc_scorefrom sklearn.model_selection import ( KFold, StratifiedKFold, cross_val_score, cross_validate, train_test_split,)from sklearn.pipeline import Pipeline, make_pipelinefrom sklearn.preprocessing import OneHotEncoder, StandardScaler
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)
CHURN_CAT = ["region", "plan", "contract", "payment_method"]CHURN_NUM = ["age", "has_autopay", "tenure_months", "monthly_charges", "total_charges", "support_tickets", "logins_last_30d", "avg_session_minutes"]Each solution ends with assert checks. Add the same checks to your own code: a silent run means that every check passed. The scores on this page come from small models, few folds and few epochs, so that each script runs in seconds on a laptop CPU.
P5-01 · Predict the output: shapes and fitted state
Section titled “P5-01 · Predict the output: shapes and fitted state”Predict the output: the code below multiplies a small data matrix by a weight vector, fits a tiny churn pipeline and pushes a batch through a PyTorch layer and through the first layers of a small CNN for 8×8 digit images. A new customer arrives with a plan, gold, that the training data never had. Write down what each print() shows, then run the code.
Acceptance criteria:
- Write your prediction for all 9 lines before you run the code.
- Your prediction matches the Output in the solution, value by value (the exact spacing of NumPy’s printout does not matter).
- For each line you got wrong, you can name the rule and the module that explains it.
import torchfrom sklearn.base import clone
torch.set_num_threads(1) # one thread: tiny tensors run faster, and LightGBM stays safetorch.manual_seed(42)X = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])w = np.array([0.5, -1.0])print((X @ w).shape, X.T.shape, (X.T @ X).shape)print(X @ w)
train = pd.DataFrame({"plan": ["basic", "premium", "basic", "standard"], "tickets": [0, 2, 4, 6]})churned = np.array([0, 1, 0, 1])pre = ColumnTransformer([ ("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["plan"]), ("num", StandardScaler(), ["tickets"]),])model = make_pipeline(pre, LogisticRegression())model.fit(train, churned)print(list(model.named_steps))print(model[:-1].get_feature_names_out().tolist())print(model[0].named_transformers_["num"].mean_, model[-1].coef_.shape)new = pd.DataFrame({"plan": ["gold"], "tickets": [2]})print(model[:-1].transform(new).round(3))fresh = clone(model)print(hasattr(model[-1], "coef_"), hasattr(fresh[-1], "coef_"))
batch = torch.tensor([[1, 2], [3, 4]])layer = torch.nn.Linear(2, 3)print(batch.dtype, layer(batch.float()).shape, layer.weight.shape)
digits = torch.zeros(2, 1, 8, 8) # 2 grayscale 8x8 images in NCHW orderconv = torch.nn.Conv2d(1, 4, kernel_size=3, padding=1)pool = torch.nn.MaxPool2d(2)features = pool(conv(digits))n_params = sum(p.numel() for p in conv.parameters())print(conv(digits).shape, features.shape, features.flatten(1).shape, n_params)# TODO: write your prediction for each print() line before you run itHint 1
Shapes follow one rule: (n, p) @ (p, k) gives (n, k), and a 1-D vector of length p behaves like (p,) and disappears from the result. StandardScaler uses the population standard deviation (ddof=0).
Hint 2
handle_unknown="ignore" turns an unknown category into a row of zeros. clone() copies the settings, not what fit() learned. nn.Linear(in_features, out_features) stores its weight as (out_features, in_features). A 3×3 convolution with padding=1 keeps the height and width; a 2×2 max pool halves them.
Solution
import torchfrom sklearn.base import clone
torch.set_num_threads(1) # one thread: tiny tensors run faster, and LightGBM stays safetorch.manual_seed(42)X = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])w = np.array([0.5, -1.0])print((X @ w).shape, X.T.shape, (X.T @ X).shape)print(X @ w)
train = pd.DataFrame({"plan": ["basic", "premium", "basic", "standard"], "tickets": [0, 2, 4, 6]})churned = np.array([0, 1, 0, 1])pre = ColumnTransformer([ ("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["plan"]), ("num", StandardScaler(), ["tickets"]),])model = make_pipeline(pre, LogisticRegression())model.fit(train, churned)print(list(model.named_steps))print(model[:-1].get_feature_names_out().tolist())print(model[0].named_transformers_["num"].mean_, model[-1].coef_.shape)new = pd.DataFrame({"plan": ["gold"], "tickets": [2]})print(model[:-1].transform(new).round(3))fresh = clone(model)print(hasattr(model[-1], "coef_"), hasattr(fresh[-1], "coef_"))
batch = torch.tensor([[1, 2], [3, 4]])layer = torch.nn.Linear(2, 3)print(batch.dtype, layer(batch.float()).shape, layer.weight.shape)
digits = torch.zeros(2, 1, 8, 8) # 2 grayscale 8x8 images in NCHW orderconv = torch.nn.Conv2d(1, 4, kernel_size=3, padding=1)pool = torch.nn.MaxPool2d(2)features = pool(conv(digits))n_params = sum(p.numel() for p in conv.parameters())print(conv(digits).shape, features.shape, features.flatten(1).shape, n_params)assert (X @ w).shape == (3,)assert model[-1].coef_.shape == (1, 4)assert not hasattr(fresh[-1], "coef_")assert layer.weight.shape == (3, 2)assert features.flatten(1).shape == (2, 64) and n_params == 40(3,) (2, 3) (2, 2)[-1.5 -2.5 -3.5]['columntransformer', 'logisticregression']['cat__plan_basic', 'cat__plan_premium', 'cat__plan_standard', 'num__tickets'][3.] (1, 4)[[ 0. 0. 0. -0.447]]True Falsetorch.int64 torch.Size([2, 3]) torch.Size([3, 2])torch.Size([2, 4, 8, 8]) torch.Size([2, 4, 4, 4]) torch.Size([2, 64]) 40How it works:
X @ wis(3, 2) @ (2,), so one prediction per row: shape(3,).X.T @ Xis(2, 3) @ (3, 2), the(p, p)matrix of the normal equations (module 32).- Each prediction is a weighted sum: row 1 gives 0.5 · 1 − 1 · 2 = −1.5.
make_pipelinenames each step after its class in lower case (module 34).get_feature_names_out()prefixes each column with the name of its transformer: three one-hot columns, one for each plan seen infit, then the scaled tickets.- The scaler learned the mean 3.0 of the training tickets. The model has one coefficient per output column of the preprocessing:
(1, 4). goldis unknown, so all three plan columns are 0 (module 33). Tickets: (2 − 3) / 2.236 = −0.447, because the population standard deviation of 0, 2, 4, 6 is √5. The model will score this customer as if the plan did not exist; P5-14 shows how an API rejects such input instead.clone()returns an unfitted copy with the same settings, so only the original hascoef_(module 34).torch.tensormakesint64from Python integers, andnn.Linearneedsfloat32, hence.float(). The layer maps 2 inputs to 3 outputs, and its weight is stored as(3, 2)(module 42).- A convolution works on NCHW tensors: batch, channels, height, width.
Conv2d(1, 4, 3, padding=1)turns 1 channel into 4 and keeps 8×8;MaxPool2d(2)halves each side to 4×4;flatten(1)gives 4 · 4 · 4 = 64 features per image for a finalLinearlayer. The 4 kernels share their weights over the whole image, so the layer has only 4 · (1 · 3 · 3) + 4 = 40 parameters (module 42).
P5-02 · Fix the bugs: a sentiment score that breaks the spec
Section titled “P5-02 · Fix the bugs: a sentiment score that breaks the spec”Fix the bugs: a teammate built a detector for negative reviews in data/reviews.csv (positive and negative reviews only). The team’s spec says:
- Clean each text: decode HTML entities, lowercase it and collapse runs of whitespace.
- Keep negations such as
notandnever, and use unigrams and bigrams that occur in at least 2 reviews. - Estimate the score with 5-fold stratified cross-validation on the training rows, then read the test set once.
- Report ROC-AUC on probabilities.
The script runs without an error, but it breaks the spec in six places:
from sklearn.feature_extraction.text import TfidfVectorizer
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)reviews = reviews[reviews["sentiment"] != "neutral"]y = (reviews["sentiment"] == "negative").astype(int)vec = TfidfVectorizer(stop_words="english")X = vec.fit_transform(reviews["text"])X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, stratify=y, random_state=42)model = LogisticRegression(max_iter=1000).fit(X_train, y_train)print(f"test ROC-AUC {roc_auc_score(y_test, model.predict(X_test)):.3f}")vocab = vec.vocabulary_print("'not' kept:", "not" in vocab, "| 'amp' kept:", "amp" in vocab)print(f"{X.shape[1]} words")test ROC-AUC 0.837'not' kept: False | 'amp' kept: True295 wordsFix it so that it follows the spec and prints these lines:
CV ROC-AUC 0.931 ± 0.021test ROC-AUC 0.948'not' kept: True | 'amp' kept: False1896 words, 'not worth' kept: Trueimport html
from sklearn.feature_extraction.text import TfidfVectorizer
def clean(text: str) -> str: # TODO: decode HTML entities, lowercase, collapse whitespace ...
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)reviews = reviews[reviews["sentiment"] != "neutral"]y = (reviews["sentiment"] == "negative").astype(int)# TODO: split the raw text first, then build one pipeline: vectorizer + model# TODO: 5-fold stratified CV on the training rows, then fit and score the test set onceHint 1
Which line learns something from the test rows before the split? Which built-in list removes not? What does predict() return, and what does ROC-AUC need?
Hint 2
TfidfVectorizer(preprocessor=clean) runs your function on each raw text. A custom preprocessor replaces the built-in lowercasing, so clean() must lowercase too. Split reviews["text"], not a matrix, and put the vectorizer inside the pipeline.
Solution
import html
from sklearn.feature_extraction.text import TfidfVectorizer
def clean(text: str) -> str: return " ".join(html.unescape(text).lower().split())
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)reviews = reviews[reviews["sentiment"] != "neutral"]y = (reviews["sentiment"] == "negative").astype(int)text_train, text_test, y_train, y_test = train_test_split( reviews["text"], y, test_size=0.25, stratify=y, random_state=42)model = make_pipeline( TfidfVectorizer(preprocessor=clean, ngram_range=(1, 2), min_df=2), LogisticRegression(max_iter=1000),)cv = StratifiedKFold(5, shuffle=True, random_state=42)cv_auc = cross_val_score(model, text_train, y_train, cv=cv, scoring="roc_auc")print(f"CV ROC-AUC {cv_auc.mean():.3f} ± {cv_auc.std():.3f}")model.fit(text_train, y_train)vocab = model[0].vocabulary_proba = model.predict_proba(text_test)[:, 1]print(f"test ROC-AUC {roc_auc_score(y_test, proba):.3f}")print("'not' kept:", "not" in vocab, "| 'amp' kept:", "amp" in vocab)print(f"{len(vocab)} words, 'not worth' kept: {'not worth' in vocab}")assert "not" in vocab and "amp" not in vocabassert roc_auc_score(y_test, proba) > 0.9CV ROC-AUC 0.931 ± 0.021test ROC-AUC 0.948'not' kept: True | 'amp' kept: False1896 words, 'not worth' kept: TrueHow it works:
- Leak:
fit_transformon all rows learned the vocabulary and the idf weights from the test reviews too. Split the raw text first, and let the pipeline fit the vectorizer on training rows only (modules 33 and 34). - Negations lost: the built-in English stop-word list contains
not,noandnever. For sentiment, those words carry the signal, so drop the list (module 41). - No phrases:
ngram_range=(1, 2)withmin_df=2adds bigrams such asnot worthand drops one-off typos. - No cross-validation: the original script’s only number came from the test set. The CV score on the training rows is the estimate; the test set confirms it once.
- No cleaning: the raw text contains
&, so the tokenampentered the vocabulary.html.unescapefixes it. The custom preprocessor also lowercases, because it replaces the built-in step. - Wrong input for ROC-AUC:
predict()returns 0/1 labels, so the “AUC” used one threshold only. Pass the probabilities of the positive class (module 36). - The test score is above the CV mean. The CV spread (± 0.021) says that a test set of 666 reviews can land this far from the mean by chance. Report both numbers; do not tune on the test.
P5-03 · Write the code: the baseline of every task
Section titled “P5-03 · Write the code: the baseline of every task”Write the code: before you build any model in this Part, you need the score of a model that ignores the features. Compute one baseline for each of the four course tasks and print it with the metric that fits the task:
- Churn (
data/customers.csv): aDummyClassifier(strategy="prior")on the standard split (test_size=0.25, stratified,random_state=42). Print accuracy, ROC-AUC and average precision (AP). - House prices (
data/houses.csv): aDummyRegressor(strategy="median")ontrain_test_split(test_size=0.25, random_state=42). Print the MAE in USD and the training median. - Daily visits (
data/web_traffic.csv, gaps filled forward): the naive forecast (yesterday) and the seasonal naive forecast (the same weekday last week) for the last 28 days. Print both MAEs. - Review sentiment with three classes (
data/reviews.csv): aDummyClassifier(strategy="most_frequent")on a stratified 25% split. Print accuracy and macro F1.
churn accuracy 0.807 ROC-AUC 0.500 AP 0.193houses MAE USD 202,090 (median price 373,500)traffic MAE naive 558 seasonal naive 542reviews accuracy 0.688 macro F1 0.272from sklearn.metrics import accuracy_score, f1_score
customers = pd.read_csv("data/customers.csv")houses = pd.read_csv("data/houses.csv")traffic = pd.read_csv("data/web_traffic.csv", parse_dates=["date"], index_col="date")reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)# TODO: one baseline per task, with the metric of that taskHint 1
A dummy model still has fit and predict, so it takes the same X as a real model: pass the feature columns even though it ignores them. ROC-AUC and AP need predict_proba(...)[:, 1].
Hint 2
For the forecasts, visits.shift(1) is yesterday’s value and visits.shift(7) is last week’s value. Select the last 28 dates after you shift, so the first test day still has its history.
Solution
from sklearn.metrics import accuracy_score, f1_score
# churn: a classifier that ignores the featurescustomers = pd.read_csv("data/customers.csv")X = customers[CHURN_CAT + CHURN_NUM]y = customers["churned"]X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=42)dummy = DummyClassifier(strategy="prior").fit(X_tr, y_tr)p = dummy.predict_proba(X_te)[:, 1]accuracy = accuracy_score(y_te, dummy.predict(X_te))print(f"churn accuracy {accuracy:.3f} ROC-AUC {roc_auc_score(y_te, p):.3f} " f"AP {average_precision_score(y_te, p):.3f}")
# houses: predict the median price of the training rowshouses = pd.read_csv("data/houses.csv")Xh = houses.drop(columns=["house_id", "sold_date", "price"])h_tr, h_te, p_tr, p_te = train_test_split(Xh, houses["price"], test_size=0.25, random_state=42)median = DummyRegressor(strategy="median").fit(h_tr, p_tr)mae = mean_absolute_error(p_te, median.predict(h_te))print(f"houses MAE USD {mae:,.0f} (median price {p_tr.median():,.0f})")
# web traffic: the last 28 days, forecast with naive and seasonal naivetraffic = pd.read_csv("data/web_traffic.csv", parse_dates=["date"], index_col="date")visits = traffic["visits"].ffill() # only past values fill a gaptest_days = visits.index[-28:]naive = visits.shift(1).loc[test_days]seasonal = visits.shift(7).loc[test_days]print(f"traffic MAE naive {mean_absolute_error(visits[test_days], naive):,.0f} " f"seasonal naive {mean_absolute_error(visits[test_days], seasonal):,.0f}")
# reviews: three sentiment classes, always the majority classreviews = pd.read_csv("data/reviews.csv", keep_default_na=False)r_tr, r_te = train_test_split(reviews, test_size=0.25, stratify=reviews["sentiment"], random_state=42)major = DummyClassifier(strategy="most_frequent").fit(r_tr[["text"]], r_tr["sentiment"])pred = major.predict(r_te[["text"]])print(f"reviews accuracy {accuracy_score(r_te['sentiment'], pred):.3f} macro F1 " f"{f1_score(r_te['sentiment'], pred, average='macro'):.3f}")assert np.isclose(average_precision_score(y_te, p), y_te.mean())assert (pred == "positive").all()churn accuracy 0.807 ROC-AUC 0.500 AP 0.193houses MAE USD 202,090 (median price 373,500)traffic MAE naive 558 seasonal naive 542reviews accuracy 0.688 macro F1 0.272How it works:
- The churn baseline gives every customer the same probability, 0.193. Its accuracy of 0.807 looks good only because 4 of 5 customers stay. Its ROC-AUC is 0.5 (no ranking) and its AP equals the churn rate. These are the floors for every churn model on this page (modules 34 and 36).
- Guessing the median price misses by about USD 202,000 per house. Every house model on this page must beat that by a wide margin (module 35).
- A forecast must beat the naive forecasts. The seasonal naive is a little better here because visits follow a weekly cycle. MAE stays in visits, a unit the marketing team understands (module 40).
- The majority class reaches 0.688 accuracy, but its macro F1 is 0.272: F1 is 0.815 for
positiveand 0 fornegativeandneutral, and macro F1 averages the three classes equally. Accuracy hides that the model never finds a complaint (module 36).
P5-04 · Write the code: one logistic regression, three ways
Section titled “P5-04 · Write the code: one logistic regression, three ways”Write the code: fit the same churn model three times and show that the three fits agree. The features are tenure_months, support_tickets and logins_last_30d, standardized with a scaler fitted on the training rows of the standard split (test_size=0.25, stratified, random_state=42).
- Write the mean log loss and its gradient in NumPy, where is the scaled matrix with a column of ones in front. Check the gradient at against PyTorch autograd.
- Run 2,000 steps of gradient descent with learning rate 0.5 from .
- Fit
LogisticRegression(C=np.inf), which has no penalty. - Write the model as an
nn.Modulewith onenn.Linearlayer, and train it withBCEWithLogitsLossand full-batchSGD(2,000 steps, learning rate 0.5).
Then turn the coefficients into odds ratios per standard deviation and score the test set once.
loss 0.697673 vs autograd 0.697673; same gradient: TrueGD [-1.833 -1.097 0.433 -0.305] loss 0.4190sklearn [-1.833 -1.097 0.433 -0.305]PyTorch [-1.833 -1.097 0.433 -0.305]odds ratio per 1 SD: {'tenure_months': 0.33, 'support_tickets': 1.54, 'logins_last_30d': 0.74}1 SD of tenure = 19.9 monthstest ROC-AUC 0.760import torchfrom torch import nn
torch.set_num_threads(1) # small models train faster on one thread, and repeat exactlytorch.manual_seed(42)
customers = pd.read_csv("data/customers.csv")cols = ["tenure_months", "support_tickets", "logins_last_30d"]# TODO: split, fit the scaler on the training rows, build A = [1 | Z]
def log_loss_grad(w: np.ndarray) -> tuple[float, np.ndarray]: # TODO: return the mean log loss and its gradient ...
# TODO: 1. gradient check with autograd 2. gradient descent# TODO: 3. LogisticRegression(C=np.inf) 4. an nn.Module trained with SGD# TODO: odds ratios, then the test ROC-AUC onceHint 1
For autograd, build the weights with torch.tensor(w0, requires_grad=True) (float64, like NumPy), compute the loss with nn.functional.binary_cross_entropy_with_logits(A @ w, y) and call .backward(). The gradient is in .grad.
Hint 2
scikit-learn keeps the intercept apart: compare np.r_[sk.intercept_, sk.coef_.ravel()] with your vector. In PyTorch, the intercept is linear.bias and the weights are linear.weight, shape (1, 3). The model must return logits; BCEWithLogitsLoss applies the sigmoid.
Solution
import torchfrom torch import nn
torch.set_num_threads(1) # small models train faster on one thread, and repeat exactlytorch.manual_seed(42)
customers = pd.read_csv("data/customers.csv")cols = ["tenure_months", "support_tickets", "logins_last_30d"]X_tr, X_te, y_tr, y_te = train_test_split( customers[cols], customers["churned"], test_size=0.25, stratify=customers["churned"], random_state=42,)scaler = StandardScaler().fit(X_tr) # training rows onlyZ = scaler.transform(X_tr)A = np.column_stack([np.ones(len(Z)), Z]) # intercept column firsty = y_tr.to_numpy().astype(float)
def sigmoid(z: np.ndarray) -> np.ndarray: return 1 / (1 + np.exp(-z))
def log_loss_grad(w: np.ndarray) -> tuple[float, np.ndarray]: p = sigmoid(A @ w) loss = -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p)) return loss, A.T @ (p - y) / len(y)
# 1. analytic gradient against autograd at one pointw0 = np.array([0.1, -0.2, 0.3, 0.05])loss0, grad0 = log_loss_grad(w0)wt = torch.tensor(w0, requires_grad=True)loss_t = nn.functional.binary_cross_entropy_with_logits( torch.tensor(A) @ wt, torch.tensor(y))loss_t.backward()print(f"loss {loss0:.6f} vs autograd {loss_t.item():.6f}; same gradient: " f"{np.allclose(grad0, wt.grad.numpy())}")
# 2. gradient descent from zerow = np.zeros(4)for _ in range(2000): loss, grad = log_loss_grad(w) w -= 0.5 * gradprint("GD ", w.round(3), f"loss {loss:.4f}")
# 3. scikit-learn without a penaltysk = LogisticRegression(C=np.inf).fit(Z, y_tr)w_sk = np.r_[sk.intercept_, sk.coef_.ravel()]print("sklearn", w_sk.round(3))
# 4. the same model as an nn.Moduleclass Logistic(nn.Module): def __init__(self, n_features: int) -> None: super().__init__() self.linear = nn.Linear(n_features, 1)
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.linear(x).squeeze(1) # logits, shape (n,)
net = Logistic(3)opt = torch.optim.SGD(net.parameters(), lr=0.5)loss_fn = nn.BCEWithLogitsLoss()Zt = torch.tensor(Z, dtype=torch.float32)yt = torch.tensor(y, dtype=torch.float32)for _ in range(2000): opt.zero_grad() loss_fn(net(Zt), yt).backward() opt.step()w_net = np.r_[net.linear.bias.item(), net.linear.weight.detach().numpy().ravel()]print("PyTorch", w_net.round(3))
odds = np.exp(w_sk[1:])print("odds ratio per 1 SD:", {c: round(float(o), 2) for c, o in zip(cols, odds, strict=True)})print(f"1 SD of tenure = {scaler.scale_[0]:.1f} months")p_te = sk.predict_proba(scaler.transform(X_te))[:, 1]print(f"test ROC-AUC {roc_auc_score(y_te, p_te):.3f}")assert np.allclose(grad0, wt.grad.numpy())assert np.allclose(w, w_sk, atol=1e-3)assert np.allclose(w_net, w_sk, atol=1e-3)loss 0.697673 vs autograd 0.697673; same gradient: TrueGD [-1.833 -1.097 0.433 -0.305] loss 0.4190sklearn [-1.833 -1.097 0.433 -0.305]PyTorch [-1.833 -1.097 0.433 -0.305]odds ratio per 1 SD: {'tenure_months': 0.33, 'support_tickets': 1.54, 'logins_last_30d': 0.74}1 SD of tenure = 19.9 monthstest ROC-AUC 0.760How it works:
- The gradient comes from the chain rule: log loss → sigmoid → linear score. Autograd applies the same chain rule to the recorded operations, so the two gradients agree to floating-point precision (modules 32 and 42).
- Log loss for logistic regression is convex. Gradient descent, scikit-learn’s L-BFGS solver and PyTorch’s
SGDall reach the same minimum. Standardized features let one learning rate work for every weight. - The PyTorch loop is the gradient descent of step 2 written with an optimizer:
zero_grad()clears the old gradient,backward()computes the new one andstep()moves the weights. It runs in float32, so it agrees to about 3 decimals. - An odds ratio of 0.33 means that one more standard deviation of tenure (19.9 months) divides the odds of churn by about 3, holding tickets and logins fixed. Each extra standard deviation of tickets multiplies the odds by 1.54 (module 36).
- With only three features the test ROC-AUC is 0.760, below the 0.813 of the full logistic model in the data dictionary. The math is right; the model just sees less.
P5-05 · Write the code: house features that earn their place
Section titled “P5-05 · Write the code: house features that earn their place”Write the code: the pricing team wants a linear model for data/houses.csv that they can read. Start from a pipeline that one-hot encodes neighborhood, imputes the median and standardizes the other columns, and fits RidgeCV(alphas=np.logspace(-3, 3, 13)) on log price inside a TransformedTargetRegressor, so that predictions come back in USD. Use train_test_split(test_size=0.25, random_state=42) and keep every choice on the training rows.
- Write a transformer class
HouseFeatures(names)onBaseEstimatorandTransformerMixin. Itsfitlearns two things from the training rows: the first sale date and the quartiles ofdistance_to_center_km. Itstransformdropssold_dateand adds the chosen candidates:age_at_sale,age_squared,log_sqft,log_lot,years_on_market(years since the first training sale) anddistance_band(0–3, a bin from the learned quartiles). - Wrapper selection: measure the 5-fold CV MAE (
KFold(5, shuffle=True, random_state=42)) of the base model and the paired gain of each candidate on its own. Keep a candidate when its mean gain is larger than the standard deviation of its fold gains. - Filter selection: compute the mutual information of each candidate with log price on the training rows.
- Embedded selection: fit
LassoCVon log price with all candidates, plus the pairwise interactions (PolynomialFeatures(2, interaction_only=True)) ofsqft,school_rating,distance_to_center_kmandcondition. Print its coefficient for each candidate and count the columns it keeps. - Fit the ridge model with the wrapper’s choice. Check that its weights solve , where is the centered matrix that Ridge saw and is log price. Score the test set once: MAE, MAPE and R² in USD.
gain gain_sd MI lasso_coefage_at_sale 2468.0 1029.0 0.04 -0.002age_squared 2950.0 1749.0 0.03 0.211log_sqft 120.0 528.0 0.40 0.108log_lot -55.0 120.0 0.09 0.020years_on_market 2952.0 1028.0 0.00 0.035distance_band -89.0 237.0 0.28 0.002base CV MAE 64,725; kept ['age_at_sale', 'age_squared', 'years_on_market']: CV MAE 59,567Lasso keeps 27 of 30 columns, 6 of 6 interactionsalpha 1.0; np.linalg.solve gives the same weights: Truetest MAE 58,815 MAPE 0.119 R² 0.915from sklearn.base import BaseEstimator, TransformerMixinfrom sklearn.compose import TransformedTargetRegressorfrom sklearn.feature_selection import mutual_info_regressionfrom sklearn.linear_model import LassoCV, RidgeCVfrom sklearn.metrics import mean_absolute_percentage_error, r2_scorefrom sklearn.preprocessing import PolynomialFeaturesfrom sklearn.utils.validation import check_is_fitted
houses = pd.read_csv("data/houses.csv")X = houses.drop(columns=["house_id", "price"])y = houses["price"]X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=42)CANDIDATES = ("age_at_sale", "age_squared", "log_sqft", "log_lot", "years_on_market", "distance_band")
class HouseFeatures(BaseEstimator, TransformerMixin): def __init__(self, names: tuple[str, ...] = ()) -> None: self.names = names # store the argument unchanged
def fit(self, X: pd.DataFrame, y=None) -> "HouseFeatures": # TODO: learn first_sale_ and distance_edges_ from the training rows return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame: # TODO: drop sold_date, compute the candidates, join only self.names ...
# TODO: build(names) -> TransformedTargetRegressor(HouseFeatures -> encoder -> RidgeCV)# TODO: wrapper gains with their fold SD, mutual information, LassoCV coefficients# TODO: fit the kept features, check with np.linalg.solve, score the test set onceHint 1
scikit-learn’s rules for a custom estimator: __init__ only stores its arguments, learned attributes end with _ and are set in fit, and fit returns self. Then clone() and every CV fold work, and each fold learns its own first sale date and quartiles.
Hint 2
Pass the same cv object to every cross_val_score call, so base - fold_mae((name,)) is a paired gain per fold. np.searchsorted(edges, values) turns a value into its bin number 0 to 3.
Hint 3
The fitted TransformedTargetRegressor keeps its pipeline in regressor_. regressor_[:-1].transform(X_tr) gives the matrix that RidgeCV saw, and regressor_[-1].alpha_ the alpha it chose. Ridge fits the intercept by centering, so center and log price before you solve.
Solution
from sklearn.base import BaseEstimator, TransformerMixinfrom sklearn.compose import TransformedTargetRegressorfrom sklearn.feature_selection import mutual_info_regressionfrom sklearn.linear_model import LassoCV, RidgeCVfrom sklearn.metrics import mean_absolute_percentage_error, r2_scorefrom sklearn.preprocessing import PolynomialFeaturesfrom sklearn.utils.validation import check_is_fitted
houses = pd.read_csv("data/houses.csv")X = houses.drop(columns=["house_id", "price"])y = houses["price"]X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=42)CANDIDATES = ( "age_at_sale", "age_squared", "log_sqft", "log_lot", "years_on_market", "distance_band",)
class HouseFeatures(BaseEstimator, TransformerMixin): """Turn sold_date into numbers and add the chosen candidate features."""
def __init__(self, names: tuple[str, ...] = ()) -> None: self.names = names
def fit(self, X: pd.DataFrame, y=None) -> "HouseFeatures": sold = pd.to_datetime(X["sold_date"]) self.first_sale_ = sold.min() # learned from the training rows only self.distance_edges_ = X["distance_to_center_km"].quantile([0.25, 0.5, 0.75]) return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame: check_is_fitted(self) out = X.copy() sold = pd.to_datetime(out.pop("sold_date")) age = sold.dt.year - out["year_built"] candidates = pd.DataFrame( { "age_at_sale": age, "age_squared": age**2, "log_sqft": np.log(out["sqft"]), "log_lot": np.log(out["lot_sqft"]), # NaN stays NaN for the imputer "years_on_market": (sold - self.first_sale_).dt.days / 365.25, "distance_band": np.searchsorted( self.distance_edges_.to_numpy(), out["distance_to_center_km"] ), } ) return out.join(candidates[list(self.names)])
def encoder(numeric: Pipeline) -> ColumnTransformer: return ColumnTransformer( [ ( "cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["neighborhood"], ) ], remainder=numeric, verbose_feature_names_out=False, )
def build(names: tuple[str, ...]) -> TransformedTargetRegressor: steps = make_pipeline( HouseFeatures(names), encoder(make_pipeline(SimpleImputer(strategy="median"), StandardScaler())), RidgeCV(alphas=np.logspace(-3, 3, 13)), ) return TransformedTargetRegressor(regressor=steps, func=np.log, inverse_func=np.exp)
cv = KFold(5, shuffle=True, random_state=42)
def fold_mae(names: tuple[str, ...]) -> np.ndarray: scores = cross_val_score( build(names), X_tr, y_tr, cv=cv, scoring="neg_mean_absolute_error" ) return -scores
# 1. wrapper: keep a candidate when its paired gain is larger than its fold noisebase = fold_mae(())table = pd.DataFrame(index=list(CANDIDATES))for name in CANDIDATES: gain = base - fold_mae((name,)) table.loc[name, ["gain", "gain_sd"]] = gain.mean(), gain.std()kept = table.index[table["gain"] > table["gain_sd"]].tolist()final = fold_mae(tuple(kept)).mean()
# 2. filter: mutual information of each candidate with log priceZ_all = HouseFeatures(CANDIDATES).fit(X_tr).transform(X_tr)[list(CANDIDATES)]Z_all = Z_all.fillna(Z_all.median())mi = mutual_info_regression(Z_all, np.log(y_tr), random_state=42)table["MI"] = mi
# 3. embedded: Lasso on all candidates plus pairwise interactions of the numbersCORE = ["sqft", "school_rating", "distance_to_center_km", "condition"]interactions = make_pipeline( SimpleImputer(strategy="median"), PolynomialFeatures(2, interaction_only=True, include_bias=False), StandardScaler(),)lasso_pre = ColumnTransformer( [ ( "cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["neighborhood"], ), ("core", interactions, CORE), ], remainder=make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), verbose_feature_names_out=False,)lasso = make_pipeline( HouseFeatures(CANDIDATES), lasso_pre, LassoCV(cv=cv, max_iter=10_000, random_state=42),)lasso.fit(X_tr, np.log(y_tr))names_out = lasso[1].get_feature_names_out()coef = pd.Series(lasso[-1].coef_, index=names_out)table["lasso_coef"] = coef[list(CANDIDATES)]print(table.round({"gain": 0, "gain_sd": 0, "MI": 2, "lasso_coef": 3}))print(f"base CV MAE {base.mean():,.0f}; kept {kept}: CV MAE {final:,.0f}")pairs = [c for c in coef.index if " " in c and set(c.split(" ")) <= set(CORE)]print( f"Lasso keeps {(coef != 0).sum()} of {len(coef)} columns, " f"{sum(coef[pairs] != 0)} of {len(pairs)} interactions")
# 4. the chosen ridge model, checked against the normal equations, tested oncemodel = build(tuple(kept)).fit(X_tr, y_tr)ridge = model.regressor_[-1]Z = model.regressor_[:-1].transform(X_tr) # the matrix that Ridge sawZc = Z - Z.mean(axis=0)t = np.log(y_tr.to_numpy())w = np.linalg.solve( Zc.T @ Zc + ridge.alpha_ * np.eye(Z.shape[1]), Zc.T @ (t - t.mean()))print( f"alpha {ridge.alpha_}; np.linalg.solve gives the same weights: " f"{np.allclose(w, ridge.coef_)}")pred = model.predict(X_te)print( f"test MAE {mean_absolute_error(y_te, pred):,.0f} MAPE " f"{mean_absolute_percentage_error(y_te, pred):.3f} R² {r2_score(y_te, pred):.3f}")assert final < base.mean()assert np.allclose(w, ridge.coef_) gain gain_sd MI lasso_coefage_at_sale 2468.0 1029.0 0.04 -0.002age_squared 2950.0 1749.0 0.03 0.211log_sqft 120.0 528.0 0.40 0.108log_lot -55.0 120.0 0.09 0.020years_on_market 2952.0 1028.0 0.00 0.035distance_band -89.0 237.0 0.28 0.002base CV MAE 64,725; kept ['age_at_sale', 'age_squared', 'years_on_market']: CV MAE 59,567Lasso keeps 27 of 30 columns, 6 of 6 interactionsalpha 1.0; np.linalg.solve gives the same weights: Truetest MAE 58,815 MAPE 0.119 R² 0.915How it works:
HouseFeaturesfollows the estimator rules, so it works inside a pipeline, in every CV fold and at prediction time. Its learned state (the first sale date and the distance quartiles) comes from training rows only, so the bins and the time feature cannot leak (modules 33 and 34).- Wrapper:
age_at_sale,age_squaredandyears_on_marketlower the CV MAE by more than their fold-to-fold noise.log_sqft,log_lotanddistance_banddo not. The three kept features cut the CV MAE from USD 64,725 to 59,567. That number comes from the same folds that chose the features, so it is a little optimistic. - Filter: mutual information ranks
log_sqftanddistance_bandhighest, andyears_on_marketat 0. It judges one feature at a time against the target. It cannot see thatlog_sqftrepeatssqft, which the model already has, or that the time trend matters only once size and location are known. - Embedded: at the alpha that
LassoCVchose, it keeps 27 of 30 columns, including all 6 interactions. With 2,250 rows and 30 columns there is little to prune. It does show the cost of correlated features: it moves the age effect toage_squaredand shrinksage_at_saleto almost 0. Lasso is most useful when there are many columns for few rows (module 35). RidgeCVchose alpha = 1.0 with its efficient leave-one-out CV, andnp.linalg.solveon the penalized normal equations gives the same weights. The penalty keeps the system well conditioned even with correlated columns (module 32).- On the test set, read once, the MAE is USD 58,815 and the typical error is 11.9% (MAPE). The R² of 0.915 is in USD, after the back-transform (module 35).
P5-06 · Choose and justify: a method, a metric and a validation split
Section titled “P5-06 · Choose and justify: a method, a metric and a validation split”Choose a method and justify it: six teams bring a request. For each one, choose the type of model, the metric and the validation strategy, and justify each choice in one sentence.
- Retention: each month, the call center can phone 250 of about 1,250 customers. Which 250 should it call? (
data/customers.csv, 19% churn) - Pricing: suggest a sale price to house sellers, who think in dollars. (
data/houses.csv, 8 extreme prices, a market that moves over time) - Traffic: forecast tomorrow’s visits every morning. (
data/web_traffic.csv) - Reviews: a dashboard shows each new review as positive, neutral or negative; neutral is only 11% of the reviews. Next year, new products join the catalog. (
data/reviews.csv) - Sensors: flag readings that look broken. Nobody has labeled faults; the
statuscolumn comes from a fixed rule. (data/sensors.csv) - Stores: group the 12 stores by their sales profile, so that managers can share plans. (
data/stores.csvwithdata/sales.csv)
Then run two experiments that back up your choices:
- Request 3: compare the CV score of a one-day-ahead forecaster under shuffled
KFoldand underTimeSeriesSplit, and compare both with the naive forecast (yesterday’s value). - Request 4: fit a three-class sentiment model (TF-IDF with unigrams and bigrams,
min_df=2, thenLogisticRegression(max_iter=1000)) and compare its macro F1 from out-of-fold predictions underStratifiedKFoldand underGroupKFoldbyproduct_id. Print the confusion matrix of the grouped predictions.
Acceptance criteria:
- A table with six rows: request, model type, metric, validation, and a one-sentence reason for each choice.
- Your reasons name the property of the request that decides the choice (a fixed call budget, units, outliers, time order, rare classes, new groups, no labels, a small number of items).
- Your first experiment prints the MAE per fold for both splitters and the MAE of the naive forecast on the time-ordered test folds, and you explain which number to trust.
- Your second experiment prints both macro F1 scores and a 3 × 3 confusion matrix, and you name the class the model confuses most.
- Compare your choices with the solution. A different choice is fine if your reason is sound.
from sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.metrics import confusion_matrix, f1_scorefrom sklearn.model_selection import GroupKFold, TimeSeriesSplit, cross_val_predict
traffic = pd.read_csv("data/web_traffic.csv", parse_dates=["date"], index_col="date")visits = traffic["visits"].ffill() # only past values fill a gap# TODO: features lag_1 ... lag_7 and day_of_week; target = visits; drop the first rows# TODO: HistGradientBoostingRegressor(max_iter=100, random_state=42)# TODO: CV MAE with KFold(5, shuffle=True, random_state=42)# TODO: CV MAE with TimeSeriesSplit(5, test_size=91); naive MAE on the same test folds
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)# TODO: cross_val_predict with StratifiedKFold and with GroupKFold(5), groups=product_id# TODO: macro F1 for both; confusion matrix with labels negative, neutral, positiveHint 1
Ask two questions for each request. How will the model be used: on new rows from the same population, on the future, or on new groups? What does a mistake cost, and in which unit?
Hint 2
In a shuffled fold, the test days sit between training days. Yesterday and tomorrow of a test day are often in the training rows, and their lags overlap with the test day’s lags.
Hint 3
cross_val_predict(clf, text, label, cv=GroupKFold(5), groups=reviews["product_id"]) keeps all reviews of a product in the same fold, so each product is scored by a model that never saw it.
Solution
| Request | Model | Metric | Validation |
|---|---|---|---|
| 1. Retention | gradient boosting or logistic regression that outputs probabilities: the team ranks customers, it does not need a yes/no label | precision in the top 250 (and average precision): a fixed budget of calls makes the top of the ranking the only part that matters | StratifiedKFold: 19% positives must appear in every fold in the same share |
| 2. Pricing | regression on log price (linear with good features, or boosting), back-transformed to USD | MAE in USD, with MAPE for a percent view: sellers think in dollars, and MAE does not let the 8 extreme prices dominate as RMSE would | shuffled KFold to choose; because the market moves, also check the last months as a time-ordered hold-out before you trust it for next year |
| 3. Traffic | lag-feature boosting or SARIMA, always against the naive and seasonal naive forecasts | MAE in visits, and MASE to compare with the naive forecast | TimeSeriesSplit: the model will only ever forecast the future, and the experiment below shows what shuffling does |
| 4. Reviews | TF-IDF (no stop-word list) + logistic regression with three classes | macro F1 and the confusion matrix: accuracy hides a model that never predicts the small neutral class | GroupKFold by product_id: new products are coming, so the score must come from products the model never saw |
| 5. Sensors | Isolation Forest or LOF on scaled readings (with time context, such as the deviation from a rolling median) | no CV score without labels: check the flagged rows by hand and against the status rule, and set contamination to the fault rate you can afford to inspect |
time-ordered: fit on the first days, score the later ones, because faults (S4 wear, S3 drift) develop over time |
| 6. Stores | agglomerative clustering with Ward linkage on standardized store profiles, read with a dendrogram | the profile table and the silhouette, then the managers’ judgment: there is no target | no split: 12 stores are too few to hold out; check that the groups stay when you drop one month of data |
from sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.metrics import confusion_matrix, f1_scorefrom sklearn.model_selection import GroupKFold, TimeSeriesSplit, cross_val_predict
# request 3: a one-day-ahead forecaster under two splitterstraffic = pd.read_csv("data/web_traffic.csv", parse_dates=["date"], index_col="date")visits = traffic["visits"].ffill() # only past values fill a gaplags = pd.DataFrame({f"lag_{k}": visits.shift(k) for k in range(1, 8)})lags["day_of_week"] = visits.index.day_of_weekdata = lags.assign(target=visits).dropna()X, y = data.drop(columns="target"), data["target"]model = HistGradientBoostingRegressor(max_iter=100, random_state=42)splitters = { "KFold, shuffled": KFold(5, shuffle=True, random_state=42), "TimeSeriesSplit": TimeSeriesSplit(5, test_size=91),}maes = {}for name, cv in splitters.items(): maes[name] = -cross_val_score(model, X, y, cv=cv, scoring="neg_mean_absolute_error") print(f"{name:16} MAE per fold {maes[name].round(0)} mean {maes[name].mean():.0f}")naive = (y - X["lag_1"]).abs()time_folds = splitters["TimeSeriesSplit"].split(X)print( "naive forecast (yesterday) MAE on the same 5 test quarters:", round(np.mean([naive.iloc[te].mean() for _, te in time_folds])),)
# request 4: three sentiment classes, new products to comereviews = pd.read_csv("data/reviews.csv", keep_default_na=False)text, label = reviews["text"], reviews["sentiment"]clf = make_pipeline( TfidfVectorizer(ngram_range=(1, 2), min_df=2), LogisticRegression(max_iter=1000))f1s = {}for name, cv, groups in [ ("StratifiedKFold", StratifiedKFold(5, shuffle=True, random_state=42), None), ("GroupKFold by product", GroupKFold(5), reviews["product_id"]),]: pred = cross_val_predict(clf, text, label, cv=cv, groups=groups) f1s[name] = f1_score(label, pred, average="macro") print(f"{name:22} macro F1 {f1s[name]:.3f}")classes = ["negative", "neutral", "positive"]print( pd.DataFrame( confusion_matrix(label, pred, labels=classes), index=classes, columns=classes ))assert maes["KFold, shuffled"].mean() < maes["TimeSeriesSplit"].mean()assert f1s["GroupKFold by product"] < f1s["StratifiedKFold"]KFold, shuffled MAE per fold [371. 372. 277. 300. 450.] mean 354TimeSeriesSplit MAE per fold [553. 230. 590. 653. 718.] mean 549naive forecast (yesterday) MAE on the same 5 test quarters: 496StratifiedKFold macro F1 0.822GroupKFold by product macro F1 0.814 negative neutral positivenegative 447 7 142neutral 3 210 125positive 97 7 1962How it works:
- Shuffled
KFoldreports an MAE of 354 visits, better than the naive forecast.TimeSeriesSplitreports 549, worse than the naive forecast (496). The same model, the same features: only the split changed (modules 37 and 40). - A shuffled fold leaks the future. A test day’s neighbors are in the training rows, so the model sees almost the same lags with the answer attached. It also trains on later days, when visits are higher, so it never has to extrapolate the upward trend. In production it must do both.
- Trees cannot predict above the largest value they saw in training. Under a growing trend, that costs a lot. The honest backtest shows it; the shuffled one hides it.
- The decision that follows, and the rule for every forecast on this page: ship a model only when it beats the naive forecast on an honest backtest. Until then, the naive forecast is the plan. P5-12 applies the same rule to a 14-day forecast.
- Groups: the grouped macro F1 (0.814) is only a little below the stratified one (0.822). The words of sentiment (“not worth it”, “love it”) are shared across products, so the model should carry over to new products. You could only know that by measuring it with groups. The confusion matrix shows the weak spot: 125 of 338 neutral reviews are predicted positive, and so are 142 negative reviews. The data dictionary warns that about 6% of the non-neutral ratings disagree with their text, so part of these errors is label noise (module 41).
- The six rows of the table follow one rule: the validation must copy how the model will be used. Rare positives need stratification, new groups need group splits, the future needs time splits, and no labels means no CV score at all (modules 36, 37 and 39).
P5-07 · Interpret a result: learning curves and a validation curve
Section titled “P5-07 · Interpret a result: learning curves and a validation curve”Interpret a result: the house team has two candidate models and a decision tree that a junior colleague wants to tune. Draw three curves on the training rows of data/houses.csv (train_test_split(test_size=0.25, random_state=42), 5-fold shuffled KFold):
- A learning curve for Ridge on log price (one-hot
neighborhood, median impute, scale,TransformedTargetRegressor), scored with R² in USD, at 10%, 25%, 50% and 100% of the training folds. - The same learning curve for
HistGradientBoostingRegressor(random_state=42)on log price. - A validation curve for a
DecisionTreeRegressor(random_state=42)on log price, formax_depthin 2, 4, 6, 8, 12 and 16.
Print the mean train and validation scores as tables, draw the three panels in one figure, then answer:
- Which model has high bias, and which one has high variance? What is your evidence?
- Will more house sales help Ridge? Will they help boosting?
- Which depth would you choose for the tree, and why must you choose it here and not on the test set?
- What should the team try next for each of the two candidates?
ridge rows train R2 valid R2 180 0.898 0.872 450 0.898 0.879 900 0.898 0.883 1800 0.889 0.884boosting rows train R2 valid R2 180 0.949 0.682 450 0.970 0.821 900 0.981 0.857 1800 0.963 0.871tree on log price max_depth train R2 valid R2 2 0.565 0.540 4 0.776 0.726 6 0.866 0.794 8 0.924 0.803 12 0.985 0.770 16 0.999 0.756Acceptance criteria:
- Your tables match the Expected output, and your figure has three labeled panels.
- Each answer cites a number from the tables: a gap, a slope or a peak.
import matplotlib.pyplot as pltfrom sklearn.compose import TransformedTargetRegressorfrom sklearn.model_selection import learning_curve, validation_curvefrom sklearn.tree import DecisionTreeRegressor
houses = pd.read_csv("data/houses.csv")X = houses.drop(columns=["house_id", "sold_date", "price"])y = houses["price"]X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=42)# TODO: one preprocessing step, two TransformedTargetRegressor models# TODO: learning_curve(model, X_tr, y_tr, cv=..., train_sizes=[0.1, 0.25, 0.5, 1.0])# TODO: validation_curve(tree, X_tr, np.log(y_tr), param_name=..., param_range=...)# TODO: print three tables, draw three panels, plt.show()Hint 1
learning_curve returns the absolute row counts and two arrays of shape (n_sizes, n_folds). Average over axis 1. The parameter name of a pipeline step is decisiontreeregressor__max_depth.
Hint 2
High bias: the two scores are close together, and adding rows does not raise them. The model has reached its limit, even if that limit is good. High variance: a high training score, a lower validation score, and a gap that shrinks as rows are added.
Solution
import matplotlib.pyplot as pltfrom sklearn.compose import TransformedTargetRegressorfrom sklearn.model_selection import learning_curve, validation_curvefrom sklearn.tree import DecisionTreeRegressor
houses = pd.read_csv("data/houses.csv")X = houses.drop(columns=["house_id", "sold_date", "price"])y = houses["price"]X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=42)pre = ColumnTransformer( [ ( "cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["neighborhood"], ) ], remainder=make_pipeline(SimpleImputer(strategy="median"), StandardScaler()),)models = { "ridge": TransformedTargetRegressor( make_pipeline(pre, Ridge()), func=np.log, inverse_func=np.exp ), "boosting": TransformedTargetRegressor( make_pipeline(pre, HistGradientBoostingRegressor(random_state=42)), func=np.log, inverse_func=np.exp, ),}cv = KFold(5, shuffle=True, random_state=42)sizes = [0.1, 0.25, 0.5, 1.0]fig, axes = plt.subplots(1, 3, figsize=(13, 4), layout="constrained")for ax, (name, model) in zip(axes, models.items(), strict=False): n, train, valid = learning_curve( model, X_tr, y_tr, cv=cv, train_sizes=sizes, scoring="r2" ) table = pd.DataFrame( {"rows": n, "train R2": train.mean(axis=1), "valid R2": valid.mean(axis=1)} ).round(3) print(name) print(table.to_string(index=False)) ax.plot(n, train.mean(axis=1), "o-", label="train") ax.plot(n, valid.mean(axis=1), "o-", label="validation") ax.set( title=f"Learning curve: {name}", xlabel="Training rows", ylabel="R²", ylim=(0.6, 1.0), ) ax.legend()
depths = [2, 4, 6, 8, 12, 16]tree = make_pipeline(pre, DecisionTreeRegressor(random_state=42))train, valid = validation_curve( tree, X_tr, np.log(y_tr), param_name="decisiontreeregressor__max_depth", param_range=depths, cv=cv, scoring="r2",)vc = pd.DataFrame( { "max_depth": depths, "train R2": train.mean(axis=1), "valid R2": valid.mean(axis=1), }).round(3)print("tree on log price")print(vc.to_string(index=False))axes[2].plot(depths, train.mean(axis=1), "o-", label="train")axes[2].plot(depths, valid.mean(axis=1), "o-", label="validation")axes[2].set( title="Validation curve: tree depth", xlabel="max_depth", ylabel="R² (log price)")axes[2].legend()assert valid.mean(axis=1).argmax() == depths.index(8)plt.show()ridge rows train R2 valid R2 180 0.898 0.872 450 0.898 0.879 900 0.898 0.883 1800 0.889 0.884boosting rows train R2 valid R2 180 0.949 0.682 450 0.970 0.821 900 0.981 0.857 1800 0.963 0.871tree on log price max_depth train R2 valid R2 2 0.565 0.540 4 0.776 0.726 6 0.866 0.794 8 0.924 0.803 12 0.985 0.770 16 0.999 0.756
How it works:
- Ridge has high bias. Its training and validation R² are close (0.889 and 0.884 at 1,800 rows), and its validation R² barely moves after 450 rows (0.879 to 0.884). Its scores are good, but they have stopped improving: the model is too simple for the data, not short of data. P5-05 confirms it: better features, not more rows, cut its error (module 37).
- Boosting has high variance, and more data helps it. At 180 rows it scores 0.949 on training and 0.682 on validation. The gap shrinks with every step, and validation R² still rises at the last step (0.857 → 0.871). More sales would likely help it; they would not help Ridge.
- The tree peaks at depth 8 (validation R² 0.803 on log price). Below that it underfits: at depth 2 both scores are near 0.55. Above it overfits: at depth 16 it scores 0.999 on training and 0.756 on validation. Choose the depth on these validation folds; a depth chosen on the test set makes the test score a selection score, not an estimate (modules 35 and 37).
- Next steps: Ridge needs better features, not rows: P5-05 shows that a curved age effect and a time trend cut its error. Boosting needs more rows or more regularization (a smaller learning rate, fewer leaves, early stopping). A single tree is the weakest of the three; an ensemble of trees is the usual fix (module 38).
- At full size the two candidates are close (0.884 and 0.871 R² in USD). The curves tell you which one has room to grow, which a single CV score cannot.
P5-08 · Write the code: which classifier’s probabilities can you price?
Section titled “P5-08 · Write the code: which classifier’s probabilities can you price?”Write the code: the retention team pays USD 15 per call, and a churner who gets a call is worth USD 150 on average. A call pays when , so the team wants to call every customer whose churn probability is above 0.10. That rule works only if a predicted 0.10 really means 10%. Find a model whose probabilities you can trust.
- Split
data/customers.csvinto 60% train, 20% validation and 20% test (stratified,random_state=42). Every candidate is a pipeline that starts with the same preprocessing (one-hot the text columns; median impute and scale the numbers). - Fit eight candidates on the training rows: logistic regression; Gaussian naive Bayes; the same naive Bayes wrapped in
CalibratedClassifierCV(method="isotonic", cv=5); KNN with k = 50; an RBFSVCwrapped inCalibratedClassifierCV(cv=3)(sigmoid calibration, because an SVM gives scores, not probabilities); a random forest (n_estimators=200, min_samples_leaf=5); LightGBM (n_estimators=200, learning_rate=0.05, num_leaves=15, verbose=-1); and logistic regression afterRandomUnderSamplerin an imbalanced-learn pipeline. Userandom_state=42wherever it exists. - On the validation rows, print ROC-AUC, log loss, the Brier score and the mean predicted probability of each candidate, and draw calibration curves (8 quantile bins) for logistic regression, both naive Bayes models and the undersampled model.
- Choose the model with the lowest validation log loss. On the test set, read once, apply the 0.10 rule: print the confusion matrix, check the precision with Bayes’ rule, and compare the profit with calling everyone.
ROC-AUC log loss Brier mean pmodellogistic 0.818 0.382 0.118 0.189naive Bayes 0.816 0.781 0.216 0.377naive Bayes + isotonic 0.816 0.383 0.119 0.187KNN (k=50) 0.795 0.469 0.127 0.178SVM + sigmoid 0.800 0.395 0.122 0.187random forest 0.837 0.367 0.115 0.193LightGBM 0.832 0.371 0.115 0.183logistic, undersampled 0.816 0.534 0.181 0.411validation churn rate 0.192chosen by validation log loss: random foresttest, call when p >= 0.10: TP 175, FP 402, FN 18, TN 405precision 0.303 = Bayes 0.303; profit USD 17,595 (call everyone: USD 13,950)import matplotlib.pyplot as pltfrom imblearn.pipeline import make_pipeline as make_imb_pipelinefrom imblearn.under_sampling import RandomUnderSamplerfrom lightgbm import LGBMClassifierfrom sklearn.calibration import CalibratedClassifierCV, calibration_curvefrom sklearn.ensemble import RandomForestClassifierfrom sklearn.metrics import brier_score_loss, confusion_matrix, log_lossfrom sklearn.naive_bayes import GaussianNBfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.svm import SVC
customers = pd.read_csv("data/customers.csv")X = customers[CHURN_CAT + CHURN_NUM]y = customers["churned"]# TODO: 60/20/20 split; a pre() function that returns a fresh ColumnTransformer# TODO: a dict of 8 candidate pipelines; fit each, score validation, one table# TODO: calibration curves for 4 models in one figure# TODO: lowest log loss -> test once: confusion matrix at 0.10, Bayes check, profitHint 1
ROC-AUC judges only the ranking. Log loss and the Brier score judge the probabilities themselves, and the mean predicted probability should be close to the churn rate of the validation rows, 0.192.
Hint 2
calibration_curve(y_va, p, n_bins=8, strategy="quantile") returns the observed churn rate and the mean predicted probability of each bin; a calibrated model lies on the diagonal. confusion_matrix(y_te, call).ravel() returns TN, FP, FN and TP in that order.
Hint 3
Bayes’ rule gives the precision from the recall , the false-positive rate and the churn rate of the test rows.
Solution
import matplotlib.pyplot as pltfrom imblearn.pipeline import make_pipeline as make_imb_pipelinefrom imblearn.under_sampling import RandomUnderSamplerfrom lightgbm import LGBMClassifierfrom sklearn.calibration import CalibratedClassifierCV, calibration_curvefrom sklearn.ensemble import RandomForestClassifierfrom sklearn.metrics import brier_score_loss, confusion_matrix, log_lossfrom sklearn.naive_bayes import GaussianNBfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.svm import SVC
customers = pd.read_csv("data/customers.csv")X = customers[CHURN_CAT + CHURN_NUM]y = customers["churned"]X_rest, X_te, y_rest, y_te = train_test_split( X, y, test_size=0.2, stratify=y, random_state=42)X_tr, X_va, y_tr, y_va = train_test_split( X_rest, y_rest, test_size=0.25, stratify=y_rest, random_state=42)
def pre() -> ColumnTransformer: return ColumnTransformer( [ ( "cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), CHURN_CAT, ), ( "num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), CHURN_NUM, ), ] )
candidates = { "logistic": make_pipeline(pre(), LogisticRegression(max_iter=1000)), "naive Bayes": make_pipeline(pre(), GaussianNB()), "naive Bayes + isotonic": CalibratedClassifierCV( make_pipeline(pre(), GaussianNB()), method="isotonic", cv=5 ), "KNN (k=50)": make_pipeline(pre(), KNeighborsClassifier(50)), "SVM + sigmoid": CalibratedClassifierCV(make_pipeline(pre(), SVC()), cv=3), "random forest": make_pipeline( pre(), RandomForestClassifier(n_estimators=200, min_samples_leaf=5, random_state=42), ), "LightGBM": make_pipeline( pre(), LGBMClassifier( n_estimators=200, learning_rate=0.05, num_leaves=15, random_state=42, n_jobs=1, verbose=-1, ), ), "logistic, undersampled": make_imb_pipeline( pre(), RandomUnderSampler(random_state=42), LogisticRegression(max_iter=1000) ),}rows, probas = [], {}for name, model in candidates.items(): p = model.fit(X_tr, y_tr).predict_proba(X_va)[:, 1] probas[name] = p rows.append( { "model": name, "ROC-AUC": roc_auc_score(y_va, p), "log loss": log_loss(y_va, p), "Brier": brier_score_loss(y_va, p), "mean p": p.mean(), } )print(pd.DataFrame(rows).set_index("model").round(3))print(f"validation churn rate {y_va.mean():.3f}")
fig, ax = plt.subplots(figsize=(6, 5), layout="constrained")for name in [ "logistic", "naive Bayes", "naive Bayes + isotonic", "logistic, undersampled",]: frac, mean_p = calibration_curve(y_va, probas[name], n_bins=8, strategy="quantile") ax.plot(mean_p, frac, "o-", label=name)ax.plot([0, 1], [0, 1], "k--", label="perfect calibration")ax.set( xlabel="Mean predicted probability", ylabel="Observed churn rate", title="Calibration on the validation rows",)ax.legend()
# a call costs USD 15; a churner reached is worth USD 150: call when p > 0.10best = min(rows, key=lambda r: r["log loss"])["model"]p_te = candidates[best].predict_proba(X_te)[:, 1]call = p_te >= 15 / 150tn, fp, fn, tp = confusion_matrix(y_te, call).ravel()prior = y_te.mean()recall, fpr = tp / (tp + fn), fp / (fp + tn)bayes = recall * prior / (recall * prior + fpr * (1 - prior))print(f"chosen by validation log loss: {best}")print(f"test, call when p >= 0.10: TP {tp}, FP {fp}, FN {fn}, TN {tn}")profit = 150 * tp - 15 * (tp + fp)everyone = 150 * (tp + fn) - 15 * len(y_te)print( f"precision {tp / (tp + fp):.3f} = Bayes {bayes:.3f}; " f"profit USD {profit:,} (call everyone: USD {everyone:,})")assert np.isclose(bayes, tp / (tp + fp))assert profit > everyoneplt.show() ROC-AUC log loss Brier mean pmodellogistic 0.818 0.382 0.118 0.189naive Bayes 0.816 0.781 0.216 0.377naive Bayes + isotonic 0.816 0.383 0.119 0.187KNN (k=50) 0.795 0.469 0.127 0.178SVM + sigmoid 0.800 0.395 0.122 0.187random forest 0.837 0.367 0.115 0.193LightGBM 0.832 0.371 0.115 0.183logistic, undersampled 0.816 0.534 0.181 0.411validation churn rate 0.192chosen by validation log loss: random foresttest, call when p >= 0.10: TP 175, FP 402, FN 18, TN 405precision 0.303 = Bayes 0.303; profit USD 17,595 (call everyone: USD 13,950)
How it works:
- Ranking and probabilities are different things. Logistic regression, both naive Bayes models and the undersampled model all reach a ROC-AUC near 0.816–0.818, but their log loss ranges from 0.382 to 0.781. Naive Bayes predicts 0.377 on average for a churn rate of 0.192: it assumes independent features, and correlated columns such as tenure and total charges make it overconfident (module 36).
- Calibration repairs probabilities without changing the ranking. Isotonic calibration, learned with internal CV on the training rows, brings naive Bayes to a log loss of 0.383 and a mean of 0.187, close to logistic regression, with the same ROC-AUC. The curve moves onto the diagonal. The SVM needs the same step for a different reason: it outputs distances to a boundary, not probabilities.
- Resampling breaks calibration. Undersampling the stayers trains the model on a 50/50 world, so it predicts 0.411 on average, and its log loss jumps to 0.534. The ranking does not improve. Resample only when you need a better ranking for a rare class, and recalibrate afterwards if you need probabilities (module 37).
- Model choice: the random forest has the lowest validation log loss (0.367) and the best ROC-AUC, with LightGBM close behind; KNN is the weakest. Choosing on validation keeps the test set honest.
- The 0.10 rule on the test set: the forest calls 577 customers. Bayes’ rule rebuilds the precision of 0.303 from the recall, the false-positive rate and the churn rate. Only 30% of the calls reach a churner, but each one is worth 10 calls, so the plan earns USD 17,595 against USD 13,950 for calling everyone (module 32).
P5-09 · Interpret a result: do review clusters follow the categories?
Section titled “P5-09 · Interpret a result: do review clusters follow the categories?”Interpret a result: the product team hopes that the 3,000 texts of data/reviews.csv fall into natural groups, one per category. Test that idea without labels, then read what the groups really are.
- Build LSA embeddings in one pipeline: TF-IDF on cleaned text (
html.unescape, lowercase, collapsed whitespace) withstop_words="english", min_df=5, max_df=0.5, thenTruncatedSVD(50, random_state=42), thenNormalizer(). - Cluster the embeddings with
KMeans(6, n_init=10, random_state=42), one cluster per category. Print the silhouette and the adjusted Rand index (ARI) between the clusters andcategory. - For each cluster, print its size, its most common category with that category’s share, and its 5 top words.
- Fit two topic models with 6 topics each:
NMF(6, init="nndsvda", max_iter=1000, random_state=42)on the same TF-IDF weights, andLatentDirichletAllocation(6, max_iter=10, random_state=42)on raw word counts from aCountVectorizerwith the same settings. Print the 5 top words of each topic and the ARI between each review’s dominant NMF topic and its category. - Use the embeddings as a search engine: print the 3 reviews closest to the query “The battery died after two days.” by cosine similarity.
Then answer: do the clusters follow the categories? If not, what do they follow? Do the topic models agree with the clusters? Why is the stop-word list fine here, when P5-02 had to drop it?
embeddings (3000, 50), variance kept 0.61, row length 1.00silhouette 0.062, ARI with category 0.063cluster 0: 1255 reviews, 21% Home | price delivery sturdy months builtcluster 1: 253 reviews, 21% Beauty | customer service question great avoidcluster 2: 380 reviews, 25% Books | material feels quality solid premiumcluster 3: 295 reviews, 83% Clothing | size true fits fit perfectcluster 4: 339 reviews, 68% Electronics | battery charge life holds chargescluster 5: 478 reviews, 26% Beauty | quality build overall price goodNMF topic 0: months lasted delivery money valueNMF topic 1: battery charge holds days fastNMF topic 2: sturdy built recommend friends definitelyNMF topic 3: feels material quality premium cheapNMF topic 4: price point beat lower storesNMF topic 5: great customer service question looksLDA topic 0: customer great service arrived packageLDA topic 1: price quality point purchase happyLDA topic 2: size sturdy built recommend friendsLDA topic 3: battery weeks setup easy chargeLDA topic 4: material quality feels cheap premiumLDA topic 5: months money lasted value deliveryARI of the dominant NMF topic with category 0.0460.86 Electronics mine broke within days. the battery died after a few months.0.82 Electronics setup was so confusing. the battery takes forever to charge.0.79 Home cheaply made, it broke within days. the battery drains veryAcceptance criteria:
- Your output matches the Expected output.
- Your answer names what each large cluster is about and explains the two clusters with a high category share.
import html
from sklearn.cluster import KMeansfrom sklearn.decomposition import NMF, LatentDirichletAllocation, TruncatedSVDfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizerfrom sklearn.metrics import adjusted_rand_score, silhouette_scorefrom sklearn.preprocessing import Normalizer
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)# TODO: lsa = make_pipeline(TfidfVectorizer(...), TruncatedSVD(...), Normalizer())# TODO: KMeans(6), silhouette, ARI with the category# TODO: per cluster: size, top category and its share, top 5 words# TODO: NMF on TF-IDF, LDA on counts: top 5 words per topic; ARI of the NMF topic# TODO: embed the query, rank the reviews by cosine similarityHint 1
Map the centroids back to word space with lsa[1].inverse_transform(km.cluster_centers_), then sort each row and look up lsa[0].get_feature_names_out(). pd.crosstab(km.labels_, reviews["category"]) gives the category counts per cluster.
Hint 2
After Normalizer(), every embedding has length 1, so the cosine similarity of two rows is their dot product: E @ query scores every review at once.
Solution
import html
from sklearn.cluster import KMeansfrom sklearn.decomposition import NMF, LatentDirichletAllocation, TruncatedSVDfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizerfrom sklearn.metrics import adjusted_rand_score, silhouette_scorefrom sklearn.preprocessing import Normalizer
def clean(text: str) -> str: return " ".join(html.unescape(text).lower().split())
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)lsa = make_pipeline( TfidfVectorizer(preprocessor=clean, stop_words="english", min_df=5, max_df=0.5), TruncatedSVD(50, random_state=42), Normalizer(),)E = lsa.fit_transform(reviews["text"])print( f"embeddings {E.shape}, " f"variance kept {lsa[1].explained_variance_ratio_.sum():.2f}, " f"row length {np.linalg.norm(E[0]):.2f}")
km = KMeans(6, n_init=10, random_state=42).fit(E)print( f"silhouette {silhouette_score(E, km.labels_):.3f}, " f"ARI with category {adjusted_rand_score(reviews['category'], km.labels_):.3f}")terms = lsa[0].get_feature_names_out()centers = lsa[1].inverse_transform(km.cluster_centers_)table = pd.crosstab(km.labels_, reviews["category"])for c in range(6): top_cat = table.loc[c].idxmax() share = table.loc[c].max() / table.loc[c].sum() words = " ".join(terms[np.argsort(centers[c])[::-1][:5]]) print( f"cluster {c}: {table.loc[c].sum():4} reviews, " f"{share:4.0%} {top_cat:11} | {words}" )
# topics: NMF on the TF-IDF weights, LDA on raw countsT = lsa[0].transform(reviews["text"])nmf = NMF(6, init="nndsvda", max_iter=1000, random_state=42).fit(T)counts = CountVectorizer(preprocessor=clean, stop_words="english", min_df=5, max_df=0.5)lda = LatentDirichletAllocation(6, max_iter=10, random_state=42)lda.fit(counts.fit_transform(reviews["text"]))for name, model, vocab in [ ("NMF", nmf, terms), ("LDA", lda, counts.get_feature_names_out()),]: for k, row in enumerate(model.components_): print(f"{name} topic {k}: {' '.join(vocab[np.argsort(row)[::-1][:5]])}")dominant = nmf.transform(T).argmax(axis=1)print( f"ARI of the dominant NMF topic with category " f"{adjusted_rand_score(reviews['category'], dominant):.3f}")
query = lsa.transform(["The battery died after two days."])[0]similarity = E @ queryfor i in np.argsort(similarity)[::-1][:3]: snippet = clean(reviews["text"].iloc[i])[:60].rstrip() print(f"{similarity[i]:.2f} {reviews['category'].iloc[i]:11} {snippet}")assert np.allclose(np.linalg.norm(E, axis=1), 1)embeddings (3000, 50), variance kept 0.61, row length 1.00silhouette 0.062, ARI with category 0.063cluster 0: 1255 reviews, 21% Home | price delivery sturdy months builtcluster 1: 253 reviews, 21% Beauty | customer service question great avoidcluster 2: 380 reviews, 25% Books | material feels quality solid premiumcluster 3: 295 reviews, 83% Clothing | size true fits fit perfectcluster 4: 339 reviews, 68% Electronics | battery charge life holds chargescluster 5: 478 reviews, 26% Beauty | quality build overall price goodNMF topic 0: months lasted delivery money valueNMF topic 1: battery charge holds days fastNMF topic 2: sturdy built recommend friends definitelyNMF topic 3: feels material quality premium cheapNMF topic 4: price point beat lower storesNMF topic 5: great customer service question looksLDA topic 0: customer great service arrived packageLDA topic 1: price quality point purchase happyLDA topic 2: size sturdy built recommend friendsLDA topic 3: battery weeks setup easy chargeLDA topic 4: material quality feels cheap premiumLDA topic 5: months money lasted value deliveryARI of the dominant NMF topic with category 0.0460.86 Electronics mine broke within days. the battery died after a few months.0.82 Electronics setup was so confusing. the battery takes forever to charge.0.79 Home cheaply made, it broke within days. the battery drains veryHow it works:
- The clusters do not follow the categories. An ARI of 0.063 is close to 0 (random labels) and far from 1 (the same partition). A silhouette of 0.062 says that the clusters overlap heavily: text does not fall into clean groups (module 39).
- They follow aspects. The top words name what the reviewer talks about: price and delivery (the large mixed cluster 0), customer service, material quality, size and fit, battery life, and build quality. These are the aspects of the data dictionary, and most reviews mix several of them (module 41).
- Two clusters look like categories, but they are aspects too. Size and fit is 83% Clothing, because only clothing and shoes have sizes. Battery is 68% Electronics; most of the rest are the battery devices of other categories: the electric toothbrush (Beauty), the robot vacuum (Home) and the fitness tracker (Sports). The category shows up only where an aspect belongs to one category.
- Stop words: for topics and similarity, words such as
theanditonly add noise, so the list helps. For sentiment, the list removesnotandnever, which flip the meaning. The right preprocessing depends on the task. - Topics tell the same story. NMF and LDA find battery, material quality, price, customer service, durability and value topics, the same aspects as the clusters, and the dominant NMF topic matches the category no better (ARI 0.046). A review can belong to several topics at once, which suits text that mixes aspects. NMF works on TF-IDF weights, LDA on counts, because LDA models how often each word occurs. The two models split the aspects a little differently (LDA puts size and sturdiness together), so read topics as a summary, not as fixed truth (module 41).
- Search: the embedding puts the query near reviews about batteries that die or drain, with no word list written by hand. The scores are cosines because every row has length 1, so
E @ queryis the cosine similarity of module 32. - If the team needs categories, it has labels: train a classifier. Clustering answers a different question, “what do people write about?”
P5-10 · Interpret a result: partial dependence, ICE and SHAP disagree
Section titled “P5-10 · Interpret a result: partial dependence, ICE and SHAP disagree”Interpret a result: the head of retention reads two claims in a model report. “Older customers churn more” and “every extra year of tenure lowers churn by the same amount”. Check both with three tools that look at the model from different angles.
- Fit a pipeline on the standard split of
data/customers.csv(test_size=0.25, stratified,random_state=42): one-hot encode the four text columns (pass the numbers through, withset_output(transform="pandas")), thenHistGradientBoostingClassifier(learning_rate=0.05, max_iter=200, max_leaf_nodes=15, random_state=42). Castageandtenure_monthsto float first. Print the ROC-AUC on the held-out rows. - Age: for the bands 18–30, 31–45, 46–60 and 61–80 of the held-out rows, print the observed churn rate, the partial dependence (PD) at the band centers 24, 38, 53 and 70, and the mean SHAP value of
age(in log-odds). - Tenure: print the PD of
tenure_monthsat 1, 6, 12, 24, 48 and 72 months for all held-out customers, for month-to-month customers only and for two-year customers only. - Impossible rows: PD keeps every other column of a row when it sets tenure to 72. Print the share of held-out rows whose total charges are below half of 72 × their monthly charges.
- Draw PD with ICE curves for
tenure_monthsandage(100 sampled rows).
Then answer: is the age claim right? Is the tenure claim right? What do the ICE curves add to the PD? How far can you trust the tenure PD at 72 months? Will keeping a customer longer lower their risk the way the PD suggests?
held-out ROC-AUC 0.831 observed churn PD at center mean SHAPage18-30 0.276 0.281 0.58231-45 0.179 0.150 -0.20146-60 0.132 0.171 -0.25861-80 0.314 0.326 0.469 tenure 1 tenure 6 tenure 12 tenure 24 tenure 48 tenure 72all 0.297 0.200 0.174 0.170 0.104 0.075month-to-month 0.423 0.285 0.247 0.244 0.148 0.105two-year 0.071 0.046 0.039 0.035 0.024 0.019rows with total charges below half of 72 x monthly charges: 78%Acceptance criteria:
- Your numbers match the Expected output, and your figure shows PD and ICE curves for both features.
- Your answers cite the tables and the figure, and the last answer separates what the model does from what the world does.
import matplotlib.pyplot as pltimport shapfrom sklearn.inspection import PartialDependenceDisplay, partial_dependence
customers = pd.read_csv("data/customers.csv")X = customers[CHURN_CAT + CHURN_NUM].astype({"age": float, "tenure_months": float})y = customers["churned"]# TODO: split, pipeline (encode -> gbm), held-out ROC-AUC# TODO: age bands: observed churn, partial_dependence(..., custom_values=...), mean SHAP# TODO: tenure PD for all, month-to-month and two-year customers# TODO: share of impossible rows at tenure 72; PartialDependenceDisplay with kind="both"Hint 1
partial_dependence(model, X_va, ["age"], custom_values={"age": [24.0, 38.0, 53.0, 70.0]}) returns a dictionary; its "average" entry holds the mean predicted probability at each grid value. partial_dependence refuses integer columns, which is why you cast to float.
Hint 2
shap.TreeExplainer(model["gbm"])(model["encode"].transform(X_va)) returns an Explanation; sv[:, "age"].values holds the SHAP value of age for each customer. Group it by the age bands with pd.cut.
Hint 3
An ICE curve shows one customer’s prediction as one feature changes. The PD is the average of the ICE curves. Curves that differ in shape, not only in height, reveal an interaction.
Solution
import matplotlib.pyplot as pltimport shapfrom sklearn.inspection import PartialDependenceDisplay, partial_dependence
customers = pd.read_csv("data/customers.csv")X = customers[CHURN_CAT + CHURN_NUM].astype({"age": float, "tenure_months": float})y = customers["churned"]X_tr, X_va, y_tr, y_va = train_test_split( X, y, test_size=0.25, stratify=y, random_state=42)encode = ColumnTransformer( [("cat", OneHotEncoder(sparse_output=False), CHURN_CAT)], remainder="passthrough", verbose_feature_names_out=False,).set_output(transform="pandas")model = Pipeline( [ ("encode", encode), ( "gbm", HistGradientBoostingClassifier( learning_rate=0.05, max_iter=200, max_leaf_nodes=15, random_state=42 ), ), ]).fit(X_tr, y_tr)print(f"held-out ROC-AUC {roc_auc_score(y_va, model.predict_proba(X_va)[:, 1]):.3f}")
# 1. age: observed churn, partial dependence and mean SHAP value per bandbands = pd.cut( X_va["age"], [17, 30, 45, 60, 80], labels=["18-30", "31-45", "46-60", "61-80"])centers = [24.0, 38.0, 53.0, 70.0]pd_age = partial_dependence(model, X_va, ["age"], custom_values={"age": centers})sv = shap.TreeExplainer(model["gbm"])(model["encode"].transform(X_va))shap_age = pd.Series(sv[:, "age"].values, index=X_va.index)age_table = pd.DataFrame( { "observed churn": y_va.groupby(bands, observed=True).mean(), "PD at center": pd_age["average"][0], "mean SHAP": shap_age.groupby(bands, observed=True).mean(), })print(age_table.round(3))
# 2. tenure: partial dependence overall and per contract type (an interaction)grid = [1.0, 6.0, 12.0, 24.0, 48.0, 72.0]rows = {}everyone = pd.Series(True, index=X_va.index)for name, mask in [ ("all", everyone), ("month-to-month", X_va["contract"] == "month-to-month"), ("two-year", X_va["contract"] == "two-year"),]: res = partial_dependence( model, X_va[mask], ["tenure_months"], custom_values={"tenure_months": grid} ) rows[name] = res["average"][0]print(pd.DataFrame(rows, index=[f"tenure {g:.0f}" for g in grid]).round(3).T)
# 3. impossible rows: PD sets tenure to 72 but keeps each row's total chargesimplied = 72 * X_va["monthly_charges"]impossible = (X_va["total_charges"] < 0.5 * implied).mean()print(f"rows with total charges below half of 72 x monthly charges: {impossible:.0%}")
fig, axes = plt.subplots(1, 2, figsize=(10, 4), layout="constrained")PartialDependenceDisplay.from_estimator( model, X_va, ["tenure_months", "age"], kind="both", subsample=100, random_state=42, ice_lines_kw={"alpha": 0.2}, ax=axes,)assert age_table["observed churn"].idxmin() != "18-30"assert (np.diff(rows["all"]) <= 0).all()plt.suptitle("Partial dependence (dashed) and ICE curves (thin), held-out customers")plt.show()held-out ROC-AUC 0.831 observed churn PD at center mean SHAPage18-30 0.276 0.281 0.58231-45 0.179 0.150 -0.20146-60 0.132 0.171 -0.25861-80 0.314 0.326 0.469 tenure 1 tenure 6 tenure 12 tenure 24 tenure 48 tenure 72all 0.297 0.200 0.174 0.170 0.104 0.075month-to-month 0.423 0.285 0.247 0.244 0.148 0.105two-year 0.071 0.046 0.039 0.035 0.024 0.019rows with total charges below half of 72 x monthly charges: 78%
How it works:
- The age claim is half right. Churn is U-shaped in age: 27.6% for ages 18–30, 13–18% in the middle and 31.4% above 60. The PD and the mean SHAP values show the same U: positive pushes for the young and the old, negative pushes in the middle. “Older customers churn more” misses that the young churn as much. Three tools on different scales agree, which makes the finding solid (module 43).
- The tenure claim is wrong. The PD falls fast in the first months (0.297 at 1 month, 0.200 at 6) and slowly afterwards (0.170 at 24, 0.075 at 72). The effect is not the same for every year.
- ICE reveals an interaction. For month-to-month customers, the PD falls from 0.423 to 0.105; for two-year customers, from 0.071 to 0.019. In the figure, the ICE curves of high-risk customers drop far in the first months, while those of low-risk customers barely move. Tenure matters most for customers who can leave at any time. A single PD curve averages this away.
- The tenure PD at 72 months stands on impossible rows. For 78% of the held-out customers, setting tenure to 72 while keeping their total charges creates a customer who cannot exist, because total charges are about tenure × monthly charges. The model has never seen such rows, and part of the tenure signal sits in
total_charges. Read the right end of the tenure curve with care. - Not causal. PD shows how the model’s prediction moves when you change one input, not how a customer changes. Customers who stay long differ from new ones in other ways (they chose to stay). To learn what a retention action does, run an experiment (module 29).
- The model reaches 0.831 ROC-AUC on the held-out rows, close to the reference scores of the data dictionary, so the explanations describe a model worth explaining.
P5-11 · Interpret a result: segments that are not really there
Section titled “P5-11 · Interpret a result: segments that are not really there”Interpret a result: marketing wants four customer segments from usage data, and the data science lead wants to know if those segments help the churn model. Work on the training rows of the standard split of data/customers.csv (test_size=0.25, stratified, random_state=42) and the five usage columns tenure_months, monthly_charges, support_tickets, logins_last_30d and avg_session_minutes.
- Standardize the usage columns. Print the explained variance ratios of a full PCA.
- For k = 2 to 7, print the k-means inertia, the silhouette score and the BIC of a
GaussianMixture(k, n_init=3, random_state=42). - Fit
KMeans(4, n_init=10, random_state=42)and print a profile table: size, mean usage and churn rate per segment. - Cluster the same scaled rows two other ways: agglomerative clustering with Ward linkage (4 clusters, print the sizes and the ARI with k-means), and DBSCAN with
min_samples=10andepsat the 90th percentile of the distances to the 10th nearest neighbor (print the number of clusters and the noise share). - Draw a t-SNE map and a UMAP map of 600 random training customers, colored by k-means segment. Run t-SNE inside
threadpool_limits(limits=1)and give UMAPn_jobs=1, so both maps repeat exactly. - Compare two logistic regression pipelines with 5-fold stratified CV ROC-AUC: the base features, and the base features plus the distances to 4 k-means centroids, learned inside the pipeline. Print the paired gain per fold.
Then answer: do these customers form natural clusters? What do the other clusterers and the maps add? Are the four segments still useful to marketing? Do the segment distances help the churn model, and is the gain real?
PCA variance ratios: [0.27 0.24 0.2 0.16 0.13] k inertia silhouette GMM BIC 2 15649 0.211 51034 3 13272 0.175 49809 4 11351 0.193 49293 5 9882 0.204 49133 6 9005 0.213 49032 7 8589 0.205 49087 size tenure charges tickets logins minutes churnsegment0 1059 16.47 84.25 0.73 9.20 11.84 0.251 1336 13.17 45.50 1.88 9.75 12.27 0.252 748 53.97 56.39 0.97 10.03 12.58 0.053 607 19.81 58.86 1.07 22.68 25.28 0.14Ward sizes [1840 526 755 629], ARI with k-means 0.38DBSCAN eps 1.14: 1 cluster(s), noise 5.0%base CV ROC-AUC 0.813 ± 0.011+ segment distances CV ROC-AUC 0.819 ± 0.009paired gain per fold [0.006 0.005 0.001 0.008 0.013], mean 0.007 ± 0.004Acceptance criteria:
- Your output matches the Expected output.
- Your figure shows the two maps side by side.
- Each answer cites at least one number or the figure: a silhouette, an ARI, the DBSCAN result, a churn rate or a paired gain.
import matplotlib.pyplot as pltimport umapfrom sklearn.cluster import DBSCAN, AgglomerativeClustering, KMeansfrom sklearn.decomposition import PCAfrom sklearn.manifold import TSNEfrom sklearn.metrics import adjusted_rand_score, silhouette_scorefrom sklearn.mixture import GaussianMixturefrom sklearn.neighbors import NearestNeighborsfrom threadpoolctl import threadpool_limits
customers = pd.read_csv("data/customers.csv")X = customers[CHURN_CAT + CHURN_NUM]y = customers["churned"]USAGE = ["tenure_months", "monthly_charges", "support_tickets", "logins_last_30d", "avg_session_minutes"]# TODO: split; standardize USAGE on the training rows; PCA variance ratios# TODO: k = 2..7: inertia, silhouette, GMM BIC# TODO: KMeans(4) profile table with the churn rate# TODO: Ward (4 clusters) and DBSCAN (eps from the 10-NN distances); t-SNE and UMAP maps# TODO: CV ROC-AUC with and without ("seg", make_pipeline(StandardScaler(), KMeans(4, ...)), USAGE)Hint 1
KMeans is a transformer: inside a ColumnTransformer, its transform() returns the distance of each row to each centroid. Because it sits in the pipeline, each CV fold learns its own centroids from its own training rows.
Hint 2
cross_val_score with the same cv object gives the same folds for both pipelines, so you can subtract the two arrays fold by fold.
Solution
import matplotlib.pyplot as pltimport umapfrom sklearn.cluster import DBSCAN, AgglomerativeClustering, KMeansfrom sklearn.decomposition import PCAfrom sklearn.manifold import TSNEfrom sklearn.metrics import adjusted_rand_score, silhouette_scorefrom sklearn.mixture import GaussianMixturefrom sklearn.neighbors import NearestNeighborsfrom threadpoolctl import threadpool_limits
customers = pd.read_csv("data/customers.csv")X = customers[CHURN_CAT + CHURN_NUM]y = customers["churned"]X_tr, X_te, y_tr, y_te = train_test_split( X, y, test_size=0.25, stratify=y, random_state=42)USAGE = [ "tenure_months", "monthly_charges", "support_tickets", "logins_last_30d", "avg_session_minutes",]Z = StandardScaler().fit_transform(X_tr[USAGE])print("PCA variance ratios:", PCA().fit(Z).explained_variance_ratio_.round(2))rows = []for k in range(2, 8): km = KMeans(k, n_init=10, random_state=42).fit(Z) gm = GaussianMixture(k, n_init=3, random_state=42).fit(Z) rows.append( { "k": k, "inertia": round(km.inertia_), "silhouette": round(silhouette_score(Z, km.labels_), 3), "GMM BIC": round(gm.bic(Z)), } )print(pd.DataFrame(rows).to_string(index=False))
km = KMeans(4, n_init=10, random_state=42).fit(Z)short = { "tenure_months": "tenure", "monthly_charges": "charges", "support_tickets": "tickets", "logins_last_30d": "logins", "avg_session_minutes": "minutes",}profile = ( X_tr[USAGE] .rename(columns=short) .assign(churn=y_tr, segment=km.labels_) .groupby("segment") .mean())profile.insert(0, "size", np.bincount(km.labels_))print(profile.round(2))
# two other clusterers on the same scaled rowsward = AgglomerativeClustering(4, linkage="ward").fit(Z)print( f"Ward sizes {np.bincount(ward.labels_)}, " f"ARI with k-means {adjusted_rand_score(km.labels_, ward.labels_):.2f}")k_dist = NearestNeighbors(n_neighbors=10).fit(Z).kneighbors(Z)[0][:, -1]eps = np.quantile(k_dist, 0.9) # the knee of the sorted 10-NN distancesdb = DBSCAN(eps=eps, min_samples=10).fit(Z).labels_print(f"DBSCAN eps {eps:.2f}: {db.max() + 1} cluster(s), noise {(db == -1).mean():.1%}")
# 2-D maps of 600 customers, colored by k-means segmentidx = np.random.default_rng(42).choice(len(Z), 600, replace=False)with threadpool_limits(limits=1): # one thread: fast and repeatable for t-SNE tsne_map = TSNE(perplexity=30, random_state=42).fit_transform(Z[idx])umap_map = umap.UMAP(random_state=42, n_jobs=1).fit_transform(Z[idx])fig, axes = plt.subplots(1, 2, figsize=(10, 4.5), layout="constrained")for ax, emb, title in [(axes[0], tsne_map, "t-SNE"), (axes[1], umap_map, "UMAP")]: points = ax.scatter(emb[:, 0], emb[:, 1], c=km.labels_[idx], cmap="viridis", s=8) ax.set(title=f"{title} map, colored by k-means segment", xticks=[], yticks=[])fig.colorbar(points, ax=axes, label="segment", ticks=range(4))
num = make_pipeline(SimpleImputer(strategy="median"), StandardScaler())segments = make_pipeline(StandardScaler(), KMeans(4, n_init=10, random_state=42))base = ColumnTransformer( [ ("cat", OneHotEncoder(handle_unknown="ignore"), CHURN_CAT), ("num", num, CHURN_NUM), ])with_segments = ColumnTransformer( [ ("cat", OneHotEncoder(handle_unknown="ignore"), CHURN_CAT), ("num", num, CHURN_NUM), ("seg", segments, USAGE), # 4 distances to the centroids, learned per fold ])cv = StratifiedKFold(5, shuffle=True, random_state=42)auc = {}for name, pre in [("base", base), ("+ segment distances", with_segments)]: model = make_pipeline(pre, LogisticRegression(max_iter=1000)) auc[name] = cross_val_score(model, X_tr, y_tr, cv=cv, scoring="roc_auc") print(f"{name:20} CV ROC-AUC {auc[name].mean():.3f} ± {auc[name].std():.3f}")gain = auc["+ segment distances"] - auc["base"]print( f"paired gain per fold {gain.round(3)}, mean {gain.mean():.3f} ± {gain.std():.3f}")assert (gain > 0).all()assert max(r["silhouette"] for r in rows) < 0.25assert db.max() + 1 == 1plt.show()PCA variance ratios: [0.27 0.24 0.2 0.16 0.13] k inertia silhouette GMM BIC 2 15649 0.211 51034 3 13272 0.175 49809 4 11351 0.193 49293 5 9882 0.204 49133 6 9005 0.213 49032 7 8589 0.205 49087 size tenure charges tickets logins minutes churnsegment0 1059 16.47 84.25 0.73 9.20 11.84 0.251 1336 13.17 45.50 1.88 9.75 12.27 0.252 748 53.97 56.39 0.97 10.03 12.58 0.053 607 19.81 58.86 1.07 22.68 25.28 0.14Ward sizes [1840 526 755 629], ARI with k-means 0.38DBSCAN eps 1.14: 1 cluster(s), noise 5.0%base CV ROC-AUC 0.813 ± 0.011+ segment distances CV ROC-AUC 0.819 ± 0.009paired gain per fold [0.006 0.005 0.001 0.008 0.013], mean 0.007 ± 0.004
How it works:
- No natural clusters. The silhouette stays near 0.2 for every k, and no k stands out; the inertia falls smoothly with no elbow. That is the main evidence. The rest is context: the PCA variance is spread almost evenly (0.27 down to 0.13), so the cloud has no dominant direction, and the BIC prefers ever more Gaussian components, so the density is not a few Gaussian blobs (module 39).
- Other methods agree. Ward linkage splits the same rows very differently from k-means (ARI 0.38): when clusters are real, different algorithms find similar groups. DBSCAN, at the knee of the 10-NN distances, finds one dense cluster and 5% noise: one continuous cloud. The maps show the same: the segments are neighboring regions of one cloud, not islands. UMAP draws strands and gaps anyway, partly because columns such as ticket counts take only a few values. Gaps and sizes in t-SNE and UMAP maps are not distances, so do not read them as cluster boundaries.
- The segments can still be useful. k-means always returns k groups, natural or not, so treat them as a convenient partition. The profile table gives four groups that marketing can act on: long-tenure customers with a 5% churn rate, highly engaged customers (22.7 logins, 14% churn) and two short-tenure groups with 25% churn, one with high charges and one with many tickets. Present them as slices of a continuum, not as types of people.
- The distances add a small, consistent gain. The CV ROC-AUC moves from 0.813 to 0.819. That is less than the fold spread (± 0.011), but the paired gain is positive in all 5 folds (mean 0.007 ± 0.004). The distances give the linear model a nonlinear view of the usage columns, such as “short tenure and high charges together” (modules 33 and 34).
- The pipeline matters. Fitting k-means on all rows first would let the test rows shape the centroids. Inside the
ColumnTransformer, each fold learns its own centroids. - Before you ship the extra step, compare it with a model that finds such interactions by itself: gradient boosting already scores higher on this data (data dictionary). A small gain for a linear model is not a reason to add a clustering step to production.
P5-12 · Write the code: a two-week forecast, chosen on a backtest
Section titled “P5-12 · Write the code: a two-week forecast, chosen on a backtest”Write the code: every second Monday, the marketing team plans the next 14 days and needs a forecast of daily visits from data/web_traffic.csv. Choose a forecaster on a backtest, then check it once on the last 8 weeks.
- Set a daily frequency, fill the 5 missing days forward (
ffill, so no gap uses a later value) and take the log of visits. Resample to weekly totals and print the busiest week. Decompose log visits withSTL(period=7, robust=True)and print the strength of the trend and of the weekly season, for a component and the remainder . Run the ADF test on the log series and on its first difference, and print the ACF of the difference at lags 1, 7 and 14. - Write three forecasters for a 14-day horizon:
- seasonal naive: repeat the last observed week;
- SARIMA(1, 1, 1)(1, 0, 1, 7) on log visits (
maxiter=200; check that it converged); HistGradientBoostingRegressor(max_iter=200, learning_rate=0.05, random_state=42)on log visits, with the direct strategy: lags of 14, 21 and 28 days, the mean of lags 14–20, the day of the week and the month.
- Score each forecaster with MASE (the MAE divided by the in-sample MAE of the seasonal naive forecast) on a
TimeSeriesSplit(n_splits=5, test_size=14)backtest of all days except the last 56. - Choose the forecaster with the lowest mean MASE. Then run it once on 4 more origins inside the last 8 weeks, and print its test MASE next to the seasonal naive one.
158 weekly totals (2 partial), busiest week ends 2024-04-14 with 71,954 visitsSTL strength: trend 0.76, weekly season 0.35ADF p-value: log visits 0.306, difference 1.2e-16ACF of the difference at lags 1, 7, 14: [0.08 0.36 0.4 ]seasonal naive backtest MASE 1.942 ± 1.638 folds [0.53 4.6 3.12 0.55 0.92]SARIMA backtest MASE 1.402 ± 1.594 folds [0.38 4.56 0.46 0.58 1.03]boosting backtest MASE 1.594 ± 1.600 folds [0.57 4.78 0.85 0.96 0.81]chosen SARIMA: test MASE 1.384 (seasonal naive 1.268)from sklearn.model_selection import TimeSeriesSplitfrom statsmodels.tsa.seasonal import STLfrom statsmodels.tsa.statespace.sarimax import SARIMAXfrom statsmodels.tsa.stattools import acf, adfuller
traffic = pd.read_csv("data/web_traffic.csv", parse_dates=["date"], index_col="date")# TODO: asfreq("D"), ffill, log; weekly resample; STL strengths; ADF and ACFH = 14# TODO: lag features with shifts of at least H
def forecast(name: str, train: pd.DatetimeIndex, horizon: pd.DatetimeIndex) -> np.ndarray: # TODO: seasonal naive, SARIMA or boosting, in visits ...
def mase(train: pd.DatetimeIndex, horizon: pd.DatetimeIndex, pred: np.ndarray) -> float: # TODO: MAE / in-sample MAE of the seasonal naive forecast ...
# TODO: backtest on all but the last 56 days, choose, test once on the last 56 daysHint 1
With the direct strategy, every feature of a target day must be known at the forecast origin. For a horizon of 14 days, the most recent value you may use for any day of the window is 14 days old, hence lags of 14 and more.
Hint 2
Selecting a DatetimeIndex with a list of labels drops its frequency, and SARIMAX then warns. Slice instead: log_v.loc[train[0]:train[-1]]. TimeSeriesSplit(n_splits=4, test_size=14) on the full index puts its 4 test windows exactly in the last 56 days.
Solution
from sklearn.model_selection import TimeSeriesSplitfrom statsmodels.tsa.seasonal import STLfrom statsmodels.tsa.statespace.sarimax import SARIMAXfrom statsmodels.tsa.stattools import acf, adfuller
traffic = pd.read_csv("data/web_traffic.csv", parse_dates=["date"], index_col="date")traffic = traffic.asfreq("D")visits = traffic["visits"].ffill() # only past values fill a gaplog_v = np.log(visits)weekly = visits.resample("W-SUN").sum() # visits are a flow, so weeks sum themprint( f"{len(weekly)} weekly totals (2 partial), busiest week ends " f"{weekly.idxmax():%Y-%m-%d} with {weekly.max():,.0f} visits")stl = STL(log_v, period=7, robust=True).fit()
def strength(part: pd.Series) -> float: """1 - var(remainder) / var(part + remainder), floored at 0.""" return max(0.0, 1 - stl.resid.var() / (part + stl.resid).var())
print( f"STL strength: trend {strength(stl.trend):.2f}, " f"weekly season {strength(stl.seasonal):.2f}")diff = log_v.diff().dropna()print( f"ADF p-value: log visits {adfuller(log_v, result_object=True).pvalue:.3f}, " f"difference {adfuller(diff, result_object=True).pvalue:.1e}")print( "ACF of the difference at lags 1, 7, 14:", acf(diff, nlags=14)[[1, 7, 14]].round(2))
H = 14 # forecast 14 days ahead, every 2 weeksfeats = pd.DataFrame({f"lag_{k}": log_v.shift(k) for k in (14, 21, 28)})feats["mean_lag_14_20"] = log_v.shift(14).rolling(7).mean()feats["day_of_week"] = log_v.index.day_of_weekfeats["month"] = log_v.index.month
def forecast( name: str, train: pd.DatetimeIndex, horizon: pd.DatetimeIndex) -> np.ndarray: if name == "seasonal naive": return np.resize(visits.loc[train[-7:]].to_numpy(), len(horizon)) if name == "SARIMA": history = log_v.loc[train[0] : train[-1]] # a slice keeps the daily frequency fit = SARIMAX(history, order=(1, 1, 1), seasonal_order=(1, 0, 1, 7)).fit( disp=False, maxiter=200 ) assert fit.mle_retvals["converged"] return np.exp(fit.forecast(len(horizon)).to_numpy()) rows = feats.loc[train].dropna() gbm = HistGradientBoostingRegressor( max_iter=200, learning_rate=0.05, random_state=42 ) gbm.fit(rows, log_v.loc[rows.index]) return np.exp(gbm.predict(feats.loc[horizon]))
def mase(train: pd.DatetimeIndex, horizon: pd.DatetimeIndex, pred: np.ndarray) -> float: history = visits.loc[train] scale = (history - history.shift(7)).abs().mean() # in-sample seasonal naive return mean_absolute_error(visits.loc[horizon], pred) / scale
def backtest(name: str, index: pd.DatetimeIndex, n_splits: int) -> np.ndarray: splitter = TimeSeriesSplit(n_splits=n_splits, test_size=H) return np.array( [ mase(index[tr], index[te], forecast(name, index[tr], index[te])) for tr, te in splitter.split(index) ] )
dev = log_v.index[:-56] # the last 8 weeks stay untouched until the endresults = {}for name in ["seasonal naive", "SARIMA", "boosting"]: results[name] = backtest(name, dev, n_splits=5) print( f"{name:14} backtest MASE {results[name].mean():.3f} " f"± {results[name].std():.3f} folds {results[name].round(2)}" )best = min(results, key=lambda n: results[n].mean())final = backtest(best, log_v.index, n_splits=4) # 4 origins inside the last 8 weeksnaive = backtest("seasonal naive", log_v.index, n_splits=4)print( f"chosen {best}: test MASE {final.mean():.3f} (seasonal naive {naive.mean():.3f})")assert best == "SARIMA"assert final.mean() > naive.mean() # an honest, disappointing result158 weekly totals (2 partial), busiest week ends 2024-04-14 with 71,954 visitsSTL strength: trend 0.76, weekly season 0.35ADF p-value: log visits 0.306, difference 1.2e-16ACF of the difference at lags 1, 7, 14: [0.08 0.36 0.4 ]seasonal naive backtest MASE 1.942 ± 1.638 folds [0.53 4.6 3.12 0.55 0.92]SARIMA backtest MASE 1.402 ± 1.594 folds [0.38 4.56 0.46 0.58 1.03]boosting backtest MASE 1.594 ± 1.600 folds [0.57 4.78 0.85 0.96 0.81]chosen SARIMA: test MASE 1.384 (seasonal naive 1.268)How it works:
- Visits are a flow, so the weekly resample sums them; the first and last weeks are partial and should not be compared with full weeks. The busiest week holds the campaign of 2024-04-08. STL gives a strong trend (0.76) and a moderate weekly season (0.35) on top of noisy days. The ADF test cannot reject a unit root for log visits (p = 0.306), and it clearly rejects it for the first difference. That supports d = 1 in SARIMA. The ACF of the difference peaks at lags 7 and 14: the weekly cycle that the seasonal part (period 7) models (module 40).
- The boosting features use only values that are at least 14 days old, so no forecast sees the future. Every forecaster returns visits, and MASE compares them on one scale: a MASE of 1 means “as good as the one-week-old value, on average”.
- The backtest picks SARIMA (mean MASE 1.402), but look at the folds. The second fold is above 4.5 for every model: the campaign of 2024-09-16 started in that window, and no model can forecast a campaign from past visits. The spread (± 1.5) is as large as the differences between the models, so the choice is weak (module 37).
- On the last 8 weeks, read once, SARIMA scores 1.384 and the seasonal naive forecast 1.268. The chosen model loses to the baseline on the test set. Report the loss as it is, and apply the rule of P5-06: do not ship SARIMA, because it did not beat the naive forecast. Keep the seasonal naive forecast, the plan the team already has, until a better backtest selects a model that beats it. Do not pick a new model on these 8 weeks either, or you lose your honest estimate.
- What the result teaches: the test window is November and December, the yearly peak. The backtest windows did not contain a comparable period, and neither forecaster models a yearly season. The next step is a better backtest (more origins, including past Novembers) and features that know the campaigns and the season, such as the planned marketing spend (module 40). Boosting (module 38) would also need a target without the trend, such as the change from the same day last week, because trees cannot extrapolate growth.
P5-13 · Choose and justify: voting or stacking?
Section titled “P5-13 · Choose and justify: voting or stacking?”Choose a model and justify it: the house team wants to combine models for log price in data/houses.csv (all columns except house_id, sold_date and price; train_test_split(test_size=0.25, random_state=42)). Should it average them (voting) or learn how to weigh them (stacking)? Compare six candidates on the same 5 shuffled folds, track each one as an MLflow run, and decide.
linear: one-hotneighborhood, median impute, scale,LinearRegression().knn: the same preprocessing,KNeighborsRegressor(10, weights="distance").forest: one-hot plus median impute,RandomForestRegressor(n_estimators=100, max_features=0.5, min_samples_leaf=2, oob_score=True, random_state=42).boosting: one-hot plus median impute,HistGradientBoostingRegressor(learning_rate=0.1, max_iter=300, early_stopping=True, n_iter_no_change=20, random_state=42).voting: aVotingRegressorthat averageslinear,knnandboostingwith equal weights.stack: aStackingRegressorof the same three models with aRidge()meta-model andcv=3.
- Log each candidate’s CV MAE (mean and standard deviation, on log price) to MLflow with a SQLite tracking URI, then rank the runs with
mlflow.search_runs. - Print the paired gain of the stack over
boostingand overvoting, fold by fold. - Print the forest’s out-of-bag R².
- Fit the best run’s model on all training rows, print the stack’s meta-model weights, and score the test set once, in log units and in USD.
Then justify your choice: why does voting beat its best member, why does stacking beat voting, and is the gain worth the cost?
tags.mlflow.runName metrics.cv_mae_log metrics.cv_mae_log_std stack 0.1193 0.0040 voting 0.1230 0.0036 boosting 0.1261 0.0050 forest 0.1316 0.0032 linear 0.1317 0.0047 knn 0.1485 0.0079stack beats boosting on 5/5 folds, by 0.0068 ± 0.0015stack beats voting on 5/5 folds, by 0.0037 ± 0.0016forest OOB R² 0.890 (log price, from the training rows)meta-model weights: {'linear': 0.39, 'knn': 0.08, 'boosting': 0.54}stack on the test set: MAE log 0.1177, MAE 57,195 USDAcceptance criteria:
- Your output matches the Expected output.
- Your justification uses the paired gains, not only the means, explains the meta-model weights and names one cost of the stack.
import logging
import mlflowfrom sklearn.ensemble import RandomForestRegressor, StackingRegressor, VotingRegressorfrom sklearn.linear_model import LinearRegressionfrom sklearn.neighbors import KNeighborsRegressor
logging.getLogger("mlflow").setLevel(logging.WARNING) # hide the INFO lines
houses = pd.read_csv("data/houses.csv")X = houses.drop(columns=["house_id", "sold_date", "price"])y = np.log(houses["price"])X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=42)# TODO: four base pipelines, then VotingRegressor and StackingRegressor of threemlflow.set_tracking_uri("sqlite:///mlflow.db")mlflow.set_experiment("p5-houses")# TODO: one KFold for all; cross_validate each candidate; one MLflow run each# TODO: search_runs ordered by CV MAE; paired gains; OOB score; test the best onceHint 1
Pass the same KFold(5, shuffle=True, random_state=42) object to every cross_validate call. Then the fold scores line up, and fold_mae["boosting"] - fold_mae["stack"] is a paired difference.
Hint 2
Inside with mlflow.start_run(run_name=name):, call mlflow.log_params and mlflow.log_metrics. mlflow.search_runs(order_by=["metrics.cv_mae_log ASC"]) returns a DataFrame; the run name is in the column tags.mlflow.runName. Delete mlflow.db before you rerun the script, or the runs pile up. A fitted stack keeps its meta-model in final_estimator_.
Solution
import logging
import mlflowfrom sklearn.ensemble import RandomForestRegressor, StackingRegressor, VotingRegressorfrom sklearn.linear_model import LinearRegressionfrom sklearn.neighbors import KNeighborsRegressor
logging.getLogger("mlflow").setLevel(logging.WARNING) # hide the INFO lines
houses = pd.read_csv("data/houses.csv")X = houses.drop(columns=["house_id", "sold_date", "price"])y = np.log(houses["price"])X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=42)
def encoder(scale: bool) -> ColumnTransformer: num = ( make_pipeline(SimpleImputer(strategy="median"), StandardScaler()) if scale else SimpleImputer(strategy="median") ) return ColumnTransformer( [ ( "cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["neighborhood"], ) ], remainder=num, )
linear = make_pipeline(encoder(scale=True), LinearRegression())knn = make_pipeline(encoder(scale=True), KNeighborsRegressor(10, weights="distance"))forest = make_pipeline( encoder(scale=False), RandomForestRegressor( n_estimators=100, max_features=0.5, min_samples_leaf=2, oob_score=True, random_state=42, ),)boosting = make_pipeline( encoder(scale=False), HistGradientBoostingRegressor( learning_rate=0.1, max_iter=300, early_stopping=True, n_iter_no_change=20, random_state=42, ),)base_models = [("linear", linear), ("knn", knn), ("boosting", boosting)]voting = VotingRegressor(base_models)stack = StackingRegressor(base_models, final_estimator=Ridge(), cv=3)candidates = { "linear": linear, "knn": knn, "forest": forest, "boosting": boosting, "voting": voting, "stack": stack,}
mlflow.set_tracking_uri("sqlite:///mlflow.db")mlflow.set_experiment("p5-houses")cv = KFold(5, shuffle=True, random_state=42) # the same folds for every modelfold_mae = {}for name, model in candidates.items(): scores = cross_validate(model, X_tr, y_tr, cv=cv, scoring="neg_mean_absolute_error") fold_mae[name] = -scores["test_score"] with mlflow.start_run(run_name=name): mlflow.log_params({"model": name, "cv_folds": 5}) mlflow.log_metrics( { "cv_mae_log": fold_mae[name].mean(), "cv_mae_log_std": fold_mae[name].std(), } )
runs = mlflow.search_runs(order_by=["metrics.cv_mae_log ASC"])print( runs[ ["tags.mlflow.runName", "metrics.cv_mae_log", "metrics.cv_mae_log_std"] ].to_string(index=False, float_format="{:.4f}".format))for other in ["boosting", "voting"]: gain = fold_mae[other] - fold_mae["stack"] print( f"stack beats {other:8} on {(gain > 0).sum()}/5 folds, " f"by {gain.mean():.4f} ± {gain.std():.4f}" )
forest.fit(X_tr, y_tr)print(f"forest OOB R² {forest[-1].oob_score_:.3f} (log price, from the training rows)")best = runs["tags.mlflow.runName"].iloc[0]final = candidates[best].fit(X_tr, y_tr)weights = dict( zip( ["linear", "knn", "boosting"], final.final_estimator_.coef_.round(2), strict=True, ))print("meta-model weights:", {k: float(v) for k, v in weights.items()})pred = np.exp(final.predict(X_te))print( f"{best} on the test set: MAE log {mean_absolute_error(y_te, np.log(pred)):.4f}, " f"MAE {mean_absolute_error(np.exp(y_te), pred):,.0f} USD")assert best == "stack"assert (fold_mae["boosting"] - fold_mae["stack"] > 0).all()tags.mlflow.runName metrics.cv_mae_log metrics.cv_mae_log_std stack 0.1193 0.0040 voting 0.1230 0.0036 boosting 0.1261 0.0050 forest 0.1316 0.0032 linear 0.1317 0.0047 knn 0.1485 0.0079stack beats boosting on 5/5 folds, by 0.0068 ± 0.0015stack beats voting on 5/5 folds, by 0.0037 ± 0.0016forest OOB R² 0.890 (log price, from the training rows)meta-model weights: {'linear': 0.39, 'knn': 0.08, 'boosting': 0.54}stack on the test set: MAE log 0.1177, MAE 57,195 USDHow it works:
- An MAE of 0.119 on log price means a typical error of about 12% of the price. Alone, boosting is the best model, linear regression and the forest tie, and KNN is clearly the weakest (module 38).
- Voting beats its best member (0.1230 against 0.1261 for boosting), even though it gives the weak KNN a full third of the vote. The three models make different errors: linear regression fits smooth additive effects, boosting fits thresholds and interactions, KNN copies similar houses. Averaging different errors cancels part of them.
- Stacking beats voting on all 5 folds, by 0.0037 ± 0.0016, and boosting by 0.0068 ± 0.0015. The paired standard deviations are much smaller than the gains, so the gains are real; the unpaired standard deviations (0.004 to 0.005) would hide this, because some folds are harder for every model (module 37).
- The meta-model weights explain why. Ridge learned 0.54 for boosting, 0.39 for linear regression and only 0.08 for KNN: it trusts each model as much as it earns, where voting gave each a third. It learns these weights from out-of-fold predictions;
cv=3keeps it from learning on predictions for rows that the base models saw. - The cost: the stack fits each base model 4 times (3 folds for the out-of-fold predictions, then once on all rows), so it trains several times slower than one model, and it has three models to monitor and explain. A gain of about 0.4 percentage points of typical error over voting is worth that for a pricing tool used on every listing; for a one-off analysis, voting or boosting alone would do.
- The forest’s OOB R² (0.890) comes for free from the rows each tree did not see, with no CV loop. MLflow keeps the parameters and metrics of every run in
mlflow.db, so the choice is documented and can be repeated (module 44). The test set, read once for the stack, gives MAE 0.1177 (USD 57,195), in line with its CV estimate.
P5-14 · Write the code: ship the churn model and watch the next batch
Section titled “P5-14 · Write the code: ship the churn model and watch the next batch”Write the code: take a churn model from training to a tested API, then check the first batch of new customers the way a monitoring job would. Split data/customers.csv by time: the reference set is every customer who signed up before 2024-07-01, and the batch is everyone who signed up later. In real life the batch’s churn labels arrive a month after scoring; here you may read them at the very end.
- Train: a pipeline (one-hot the text columns; median impute and scale the numbers;
LogisticRegression(max_iter=1000)) on the reference set. Print its 5-fold stratified CV ROC-AUC. - Save: write a joblib bundle with metadata (model version
1.0.0, scikit-learn version, a hash of the training data, the feature list, the CV score and a threshold of 0.3 agreed with the retention team) and a JSON sidecar with the bundle’s SHA-256. The loader refuses a file whose hash or library version does not match. Show that it refuses a damaged copy. - Serve: a FastAPI app that loads the bundle once in its lifespan and offers
GET /healthandPOST /predict. The request model usesLiteralcategories,Fieldranges,extra="forbid"and no inf or NaN. Test it withTestClient: a risky customer, a loyal customer and a request with two invalid fields. - Monitor: for four numeric features, compute the population stability index (PSI, 10 bins from reference quantiles) and the KS test between the reference and the batch; alert when PSI is above 0.25. Print the tenure range of both sets. Check how many batch rows two row-level detectors flag when they are fitted on the reference usage columns with
contamination=0.01: anIsolationForest(random_state=42)and aLocalOutlierFactor(n_neighbors=20, novelty=True)after aStandardScaler. - Labels arrive: compare the batch’s predicted and actual churn rates and its ROC-AUC.
Finally, say in which folder of a project layout (module 44) each piece of your script belongs, and what the team should do before the next batch.
reference rows 4044, churn 0.125, CV ROC-AUC 0.767bundle loads: 1.0.0refused: churn.joblib changed since it was saved{'status': 'ok', 'model_version': '1.0.0'}risky {'churn_probability': 0.816, 'contact': True, 'model_version': '1.0.0'}loyal {'churn_probability': 0.046, 'contact': False, 'model_version': '1.0.0'}422 ['contract', 'tenure_months'] PSI KS p alertfeaturetenure_months 8.770 0.000 Truesupport_tickets 0.247 0.000 Falsemonthly_charges 0.021 0.059 Falselogins_last_30d 0.014 0.616 Falsereference tenure range 6-72, batch 0-5IsolationForest flags 1.7% of the batch (1% of the reference by design)LOF (novelty) flags 4.3% of the batch (1% of the reference by design)batch of 956: predicted churn 0.273, actual 0.479, ROC-AUC 0.723Acceptance criteria:
- Your output matches the Expected output.
- Your API rejects the invalid request with a 422 that names both fields, and the risky customer scores higher than the loyal one.
- Your conclusion explains why the batch’s scores are too low and what to change.
import hashlibimport jsonfrom collections.abc import AsyncIteratorfrom contextlib import asynccontextmanagerfrom pathlib import Pathfrom typing import Literal
import joblibimport sklearnfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.testclient import TestClientfrom pydantic import BaseModel, ConfigDict, Fieldfrom scipy import statsfrom sklearn.ensemble import IsolationForestfrom sklearn.neighbors import LocalOutlierFactor
FEATURES = CHURN_CAT + CHURN_NUMcustomers = pd.read_csv("data/customers.csv")reference = customers[customers["signup_date"] < "2024-07-01"]batch = customers[customers["signup_date"] >= "2024-07-01"]# TODO: 1. pipeline, CV ROC-AUC, fit on the reference set# TODO: 2. save_bundle / load_bundle with a SHA-256 sidecar; refuse a damaged file# TODO: 3. Customer request model, Prediction response model, lifespan, two endpoints# TODO: TestClient: /health, two customers, one invalid request# TODO: 4. PSI and KS per feature, tenure ranges, IsolationForest and LOF shares# TODO: 5. predicted vs actual churn rate and ROC-AUC on the batchHint 1
Write the sidecar after joblib.dump, because the hash must describe the finished file. In load_bundle, compare the hash and the version before you call joblib.load, so a damaged file, or one that does not match its recorded hash, never gets unpickled. The sidecar protects against accidents, not against an attacker who can write to the folder: such a person can replace both files.
Hint 2
The JSON body has has_autopay as true/false, but the model learned 0/1: convert it in the endpoint. A 422 response lists one error per invalid field in response.json()["detail"]; the field name is the last item of each error’s loc.
Hint 3
For PSI, take the bin edges from the reference quantiles (np.unique drops repeated edges of a discrete column), open the outer edges to infinity, and clip empty bins to a small share such as 0.0001 before the log.
Solution
import hashlibimport jsonfrom collections.abc import AsyncIteratorfrom contextlib import asynccontextmanagerfrom pathlib import Pathfrom typing import Literal
import joblibimport sklearnfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.testclient import TestClientfrom pydantic import BaseModel, ConfigDict, Fieldfrom scipy import statsfrom sklearn.ensemble import IsolationForestfrom sklearn.neighbors import LocalOutlierFactor
FEATURES = CHURN_CAT + CHURN_NUMcustomers = pd.read_csv("data/customers.csv")reference = customers[customers["signup_date"] < "2024-07-01"]batch = customers[customers["signup_date"] >= "2024-07-01"]
# 1. train on the reference customers and estimate the score with CVpre = ColumnTransformer( [ ("cat", OneHotEncoder(handle_unknown="ignore"), CHURN_CAT), ( "num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), CHURN_NUM, ), ])pipeline = make_pipeline(pre, LogisticRegression(max_iter=1000))cv = StratifiedKFold(5, shuffle=True, random_state=42)cv_auc = cross_val_score( pipeline, reference[FEATURES], reference["churned"], cv=cv, scoring="roc_auc").mean()pipeline.fit(reference[FEATURES], reference["churned"])print( f"reference rows {len(reference)}, churn {reference['churned'].mean():.3f}, " f"CV ROC-AUC {cv_auc:.3f}")
# 2. save the bundle with a sidecar that records its hashdef sha256(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest()
def save_bundle(model, metadata: dict, path: Path) -> None: path.parent.mkdir(exist_ok=True) joblib.dump({"pipeline": model, "metadata": metadata}, path) sidecar = metadata | {"sha256": sha256(path)} path.with_suffix(".json").write_text(json.dumps(sidecar, indent=2))
def load_bundle(path: Path) -> dict: sidecar = json.loads(path.with_suffix(".json").read_text()) if sha256(path) != sidecar["sha256"]: raise ValueError(f"{path.name} changed since it was saved") if sidecar["sklearn"] != sklearn.__version__: raise ValueError("saved with another scikit-learn version") return joblib.load(path)
data_hash = hashlib.sha256( pd.util.hash_pandas_object( reference[FEATURES + ["churned"]], index=False ).to_numpy()).hexdigest()[:12]metadata = { "model_version": "1.0.0", "sklearn": sklearn.__version__, "data_sha256": data_hash, "features": FEATURES, "cv_roc_auc": round(cv_auc, 3), "threshold": 0.3,}save_bundle(pipeline, metadata, Path("models/churn.joblib"))print( "bundle loads:", load_bundle(Path("models/churn.joblib"))["metadata"]["model_version"],)with Path("models/churn.joblib").open("ab") as f: f.write(b"\x00") # a damaged copytry: load_bundle(Path("models/churn.joblib"))except ValueError as err: print("refused:", err)save_bundle(pipeline, metadata, Path("models/churn.joblib"))
# 3. serve itclass Customer(BaseModel): model_config = ConfigDict(extra="forbid", allow_inf_nan=False) age: int = Field(ge=18, le=100) region: Literal["East", "North", "South", "West"] plan: Literal["basic", "standard", "premium"] contract: Literal["month-to-month", "one-year", "two-year"] payment_method: Literal[ "electronic_check", "credit_card", "bank_transfer", "paypal" ] has_autopay: bool tenure_months: int = Field(ge=0, le=120) monthly_charges: float = Field(gt=0, le=1000) total_charges: float | None = Field(default=None, ge=0, le=120_000) support_tickets: int = Field(ge=0, le=100) logins_last_30d: int = Field(ge=0, le=1000) avg_session_minutes: float = Field(ge=0, le=1440)
class Prediction(BaseModel): churn_probability: float contact: bool model_version: str
bundles: dict[str, dict] = {}
@asynccontextmanagerasync def lifespan(app: FastAPI) -> AsyncIterator[None]: bundles["churn"] = load_bundle(Path("models/churn.joblib")) yield bundles.clear()
app = FastAPI(lifespan=lifespan)
@app.get("/health")def health() -> dict[str, str]: if "churn" not in bundles: raise HTTPException(status_code=503, detail="model not loaded") return { "status": "ok", "model_version": bundles["churn"]["metadata"]["model_version"], }
@app.post("/predict")def predict(customer: Customer) -> Prediction: bundle = bundles.get("churn") if bundle is None: raise HTTPException(status_code=503, detail="model not loaded") row = pd.DataFrame([customer.model_dump()], columns=FEATURES) row["has_autopay"] = row["has_autopay"].astype(int) p = float(bundle["pipeline"].predict_proba(row)[0, 1]) meta = bundle["metadata"] return Prediction( churn_probability=round(p, 3), contact=p >= meta["threshold"], model_version=meta["model_version"], )
new_customer = { "age": 29, "region": "South", "plan": "premium", "contract": "month-to-month", "payment_method": "electronic_check", "has_autopay": False, "tenure_months": 2, "monthly_charges": 104.0, "total_charges": 208.0, "support_tickets": 3, "logins_last_30d": 4, "avg_session_minutes": 7.5,}loyal = new_customer | { "contract": "two-year", "payment_method": "credit_card", "has_autopay": True, "tenure_months": 48, "total_charges": 4990.0, "support_tickets": 0,}bad = new_customer | {"contract": "monthly", "tenure_months": -1}with TestClient(app) as client: print(client.get("/health").json()) risky_out = client.post("/predict", json=new_customer).json() loyal_out = client.post("/predict", json=loyal).json() print("risky", risky_out) print("loyal", loyal_out) response = client.post("/predict", json=bad) print(response.status_code, [e["loc"][-1] for e in response.json()["detail"]])
# 4. monitor the batch of new customersdef psi(ref: pd.Series, new: pd.Series, bins: int = 10) -> float: edges = np.unique(np.quantile(ref, np.linspace(0, 1, bins + 1))) edges[0], edges[-1] = -np.inf, np.inf r = np.histogram(ref, edges)[0] / len(ref) n = np.histogram(new, edges)[0] / len(new) r, n = np.clip(r, 1e-4, None), np.clip(n, 1e-4, None) return float(np.sum((n - r) * np.log(n / r)))
rows = []for col in ["tenure_months", "support_tickets", "monthly_charges", "logins_last_30d"]: ref_col, new_col = reference[col].dropna(), batch[col].dropna() rows.append( { "feature": col, "PSI": psi(ref_col, new_col), "KS p": stats.ks_2samp(ref_col, new_col).pvalue, } )drift = pd.DataFrame(rows).set_index("feature")drift["alert"] = drift["PSI"] > 0.25print(drift.round(3))print( f"reference tenure range {reference['tenure_months'].min()}-" f"{reference['tenure_months'].max()}, batch " f"{batch['tenure_months'].min()}-{batch['tenure_months'].max()}")usage = [ "tenure_months", "monthly_charges", "support_tickets", "logins_last_30d", "avg_session_minutes", "age",]detectors = { "IsolationForest": IsolationForest(contamination=0.01, random_state=42), "LOF (novelty)": make_pipeline( StandardScaler(), LocalOutlierFactor(n_neighbors=20, novelty=True, contamination=0.01), ),}for name, detector in detectors.items(): flagged = (detector.fit(reference[usage]).predict(batch[usage]) == -1).mean() print(f"{name} flags {flagged:.1%} of the batch (1% of the reference by design)")
p_batch = pipeline.predict_proba(batch[FEATURES])[:, 1]print( f"batch of {len(batch)}: predicted churn {p_batch.mean():.3f}, actual " f"{batch['churned'].mean():.3f}, " f"ROC-AUC {roc_auc_score(batch['churned'], p_batch):.3f}")assert risky_out["churn_probability"] > loyal_out["churn_probability"]assert response.status_code == 422reference rows 4044, churn 0.125, CV ROC-AUC 0.767bundle loads: 1.0.0refused: churn.joblib changed since it was saved{'status': 'ok', 'model_version': '1.0.0'}risky {'churn_probability': 0.816, 'contact': True, 'model_version': '1.0.0'}loyal {'churn_probability': 0.046, 'contact': False, 'model_version': '1.0.0'}422 ['contract', 'tenure_months'] PSI KS p alertfeaturetenure_months 8.770 0.000 Truesupport_tickets 0.247 0.000 Falsemonthly_charges 0.021 0.059 Falselogins_last_30d 0.014 0.616 Falsereference tenure range 6-72, batch 0-5IsolationForest flags 1.7% of the batch (1% of the reference by design)LOF (novelty) flags 4.3% of the batch (1% of the reference by design)batch of 956: predicted churn 0.273, actual 0.479, ROC-AUC 0.723How it works:
- The bundle is checked before it is loaded. One extra byte changes the SHA-256, so the loader refuses the damaged file without unpickling it. This proves integrity against accidents, not authenticity: anyone who can replace the bundle can also replace the sidecar. Against an attacker, keep the expected hash where they cannot write (a model registry or a signed manifest), and load only files that you trust. The data hash and the library version in the metadata let you trace which data and which code made the model (module 44).
- The API rejects what the model cannot handle.
LiteralandFieldreject the unknown contract"monthly"and the negative tenure, and the 422 response names both fields. Remember P5-01: without the check, an unknown category becomes a row of zeros and the model scores it silently. The risky customer scores 0.816 and is marked for a call; the loyal one scores 0.046. - Tenure drifts completely. Every reference customer has 6 to 72 months of tenure, because they all signed up at least 6 months before the snapshot. Every batch customer has 0 to 5. The PSI of 8.77 is far above the alert level of 0.25. Support tickets shift moderately (PSI 0.247, just under the alert level, with a tiny KS p-value); charges and logins do not.
- Row-level anomaly detection misses most of it. The Isolation Forest flags 1.7% of the batch and LOF 4.3%, against 1% of the reference by design. LOF does better because it compares local densities, and short-tenure customers sit at the thin edge of the reference cloud. Still, at most 1 in 20 new customers looks unusual on its own, while all of them are outside the training range of tenure. Monitor distributions, not only single rows (module 39).
- The labels confirm the risk. The model predicts a churn rate of 0.273 for the batch, but 0.479 churn. It never saw customers in their first months, when churn is highest (data dictionary: 44.4% at 1–6 months), so it extrapolates the tenure effect. It still ranks reasonably (ROC-AUC 0.723 against a CV estimate of 0.767), but its probabilities are far too low, so the threshold of 0.3 misses many churners (module 36).
- Project layout:
pre,save_bundleandload_bundlego insrc/(one module shared by training and serving), the training run in a script, the bundle and its sidecar inmodels/, the app insrc/or anapp.pynext to it, theTestClientchecks intests/, and the threshold and the drift limits inconfig/. - Before the next batch: retrain on data that contains new customers (a random split of all customers, as in the data dictionary’s reference scores), recalibrate the probabilities, and keep the PSI alert on tenure in the monitoring job.
P5-15 · Fix the method: a house-price report with five mistakes
Section titled “P5-15 · Fix the method: a house-price report with five mistakes”Fix the method: an analyst sends this report on data/houses.csv: “Our random forest predicts prices with 90.6% accuracy. Square footage, school rating and bedrooms drive prices; neighborhood barely matters.” The code runs without an error, and every number in the report comes from it, but the method has five mistakes:
from sklearn.ensemble import RandomForestRegressorfrom sklearn.metrics import r2_score
houses = pd.read_csv("data/houses.csv")X = houses.drop(columns=["price", "sold_date"])X["house_id"] = X["house_id"].str[1:].astype(int)X = pd.get_dummies(X, columns=["neighborhood"])X = X.fillna(X.median())y = houses["price"]X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=42)best = Nonefor leaf in [1, 5, 20]: forest = RandomForestRegressor( n_estimators=60, max_features=0.5, min_samples_leaf=leaf, random_state=42 ).fit(X_tr, y_tr) score = r2_score(y_te, forest.predict(X_te)) if best is None or score > best[0]: best = (score, leaf, forest)score, leaf, forest = bestprint(f"min_samples_leaf={leaf}: accuracy {score:.1%}")importance = pd.Series(forest.feature_importances_, index=X.columns)print(importance.nlargest(4).round(3).to_dict())rank = importance.rank(ascending=False)["house_id"]share = importance["house_id"]print(f"house_id: importance {share:.3f}, rank {rank:.0f} of {len(importance)}")min_samples_leaf=1: accuracy 90.6%{'sqft': 0.39, 'school_rating': 0.152, 'bedrooms': 0.084, 'distance_to_center_km': 0.079}house_id: importance 0.019, rank 11 of 19Rewrite the analysis so that every number in the report is honest:
- Keep
train_test_split(test_size=0.25, random_state=42)on the raw columns. - Put all preprocessing in one pipeline: a
TargetEncoderforneighborhood(target_type="continuous",cv=KFold(5, shuffle=True, random_state=42)), the median imputer for the numbers, and an honest time feature,years_since_2022, computed fromsold_dateinside the pipeline instead ofhouse_id. - Tune
min_samples_leaf(integers from 1 to 29) andmax_features(0.3 to 0.8) withRandomizedSearchCV(n_iter=4, 3 shuffled folds, R²,random_state=42) on a forest withn_estimators=60, random_state=42. - Estimate the whole tuning procedure with nested CV: the search inside 3 outer folds (
KFold(3, shuffle=True, random_state=0)). - Score the test set once, with R², MAE and RMSE in USD.
- Check the residuals on the test rows: plot them against the predictions and by neighborhood, and print the neighborhoods with the lowest and highest median residual.
- Rank the features with permutation importance on the test rows (3 repeats, R²), on the raw columns.
nested CV R² 0.867 ± 0.017chosen min_samples_leaf=7, max_features=0.60; inner CV R² 0.870test R² 0.890, MAE 64,679, RMSE 107,131 USDmedian residual (log ratio) per neighborhood: Oak Hill -0.043 ... Lakeview +0.055{'neighborhood': 0.471, 'sqft': 0.447, 'condition': 0.025, 'year_built': 0.021}Acceptance criteria:
- Your output matches the Expected output, and your figure shows the two residual plots.
- You name each of the five mistakes, the line that makes it and the fix.
- You rewrite the report’s two sentences with honest numbers.
import matplotlib.pyplot as pltfrom scipy.stats import randint, uniformfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.inspection import permutation_importancefrom sklearn.metrics import r2_score, root_mean_squared_errorfrom sklearn.model_selection import RandomizedSearchCVfrom sklearn.preprocessing import FunctionTransformer, TargetEncoder
houses = pd.read_csv("data/houses.csv")X = houses.drop(columns=["house_id", "price"])y = houses["price"]X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=42)
def sale_time(df: pd.DataFrame) -> pd.DataFrame: # TODO: replace sold_date with years_since_2022 ...
# TODO: pipeline: FunctionTransformer -> TargetEncoder + median impute -> forest# TODO: RandomizedSearchCV with randint and uniform; nested CV around the search# TODO: fit the search, test R², MAE and RMSE once; residuals by neighborhood# TODO: permutation importance on the test rows; two residual plotsHint 1
Ask four questions of the buggy script. Which lines see the test rows before the split? Which column names a row instead of describing the house? Where is a choice made, and on which rows? What does each printed number really measure?
Hint 2
The five mistakes: preprocessing before the split, house_id as a feature, tuning on the test set, R² called “accuracy”, and impurity importances on training data with neighborhood split over 8 dummy columns. house_id increases with the sale date, because the file is sorted by sold_date.
Hint 3
cross_val_score(search, X_tr, y_tr, cv=outer) runs the whole search inside each outer training fold and scores the chosen model on the outer test fold: that is nested CV. search.best_score_ is the best of several candidates on the same folds, so it is optimistic.
Solution
import matplotlib.pyplot as pltfrom scipy.stats import randint, uniformfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.inspection import permutation_importancefrom sklearn.metrics import r2_score, root_mean_squared_errorfrom sklearn.model_selection import RandomizedSearchCVfrom sklearn.preprocessing import FunctionTransformer, TargetEncoder
houses = pd.read_csv("data/houses.csv")X = houses.drop(columns=["house_id", "price"])y = houses["price"]X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=42)
def sale_time(df: pd.DataFrame) -> pd.DataFrame: out = df.copy() sold = pd.to_datetime(out.pop("sold_date")) out["years_since_2022"] = (sold - pd.Timestamp("2022-01-01")).dt.days / 365.25 return out
pre = ColumnTransformer( [ ( "hood", TargetEncoder( target_type="continuous", cv=KFold(5, shuffle=True, random_state=42) ), ["neighborhood"], ) ], remainder=SimpleImputer(strategy="median"),)forest = make_pipeline( FunctionTransformer(sale_time), pre, RandomForestRegressor(n_estimators=60, random_state=42),)space = { "randomforestregressor__min_samples_leaf": randint(1, 30), "randomforestregressor__max_features": uniform(0.3, 0.5),}search = RandomizedSearchCV( forest, space, n_iter=4, scoring="r2", random_state=42, cv=KFold(3, shuffle=True, random_state=42),)
# nested CV: the score of the whole tuning procedure, not of its best candidateouter = cross_val_score( search, X_tr, y_tr, scoring="r2", cv=KFold(3, shuffle=True, random_state=0))print(f"nested CV R² {outer.mean():.3f} ± {outer.std():.3f}")search.fit(X_tr, y_tr)leaf = search.best_params_["randomforestregressor__min_samples_leaf"]share = search.best_params_["randomforestregressor__max_features"]print( f"chosen min_samples_leaf={leaf}, max_features={share:.2f}; " f"inner CV R² {search.best_score_:.3f}")
pred = search.predict(X_te)print( f"test R² {r2_score(y_te, pred):.3f}, MAE {mean_absolute_error(y_te, pred):,.0f}, " f"RMSE {root_mean_squared_error(y_te, pred):,.0f} USD")residual = pd.Series(np.log(y_te / pred), index=X_te.index) # log ratio, about %by_hood = residual.groupby(X_te["neighborhood"]).median().sort_values()print( "median residual (log ratio) per neighborhood:", f"{by_hood.index[0]} {by_hood.iloc[0]:+.3f} ... {by_hood.index[-1]} " f"{by_hood.iloc[-1]:+.3f}",)perm = permutation_importance( search.best_estimator_, X_te, y_te, scoring="r2", n_repeats=3, random_state=42)importance = pd.Series(perm.importances_mean, index=X_te.columns)print(importance.nlargest(4).round(3).to_dict())
fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout="constrained")axes[0].scatter(pred / 1000, residual, s=6, alpha=0.5)axes[0].axhline(0, color="black", lw=1)axes[0].set( xscale="log", xlabel="Predicted price (thousand USD, log scale)", ylabel="log(actual / predicted)", title="Residuals against predictions",)axes[0].set_xticks([200, 400, 1000, 2000], labels=["200", "400", "1,000", "2,000"])axes[0].minorticks_off()order = by_hood.index.tolist()axes[1].boxplot( [residual[X_te["neighborhood"] == n] for n in order], tick_labels=order, orientation="horizontal",)axes[1].axvline(0, color="black", lw=1)axes[1].set(xlabel="log(actual / predicted)", title="Residuals by neighborhood")assert "house_id" not in X_tr.columnsassert abs(residual.median()) < 0.05plt.show()nested CV R² 0.867 ± 0.017chosen min_samples_leaf=7, max_features=0.60; inner CV R² 0.870test R² 0.890, MAE 64,679, RMSE 107,131 USDmedian residual (log ratio) per neighborhood: Oak Hill -0.043 ... Lakeview +0.055{'neighborhood': 0.471, 'sqft': 0.447, 'condition': 0.025, 'year_built': 0.021}
The five mistakes and their fixes:
- Preprocessing before the split.
get_dummiesandfillna(X.median())ran on all 3,000 rows, so the test rows shaped the medians that fill the training blanks. The pipeline now learns the medians and the target encoding inside each fit;TargetEncodereven cross-fits within the training rows, so a house never sees its own price in its encoded neighborhood (module 33). - An identifier as a feature.
house_idgets 1.9% of the impurity importance (rank 11 of 19) because ids follow the sale date. It is a date in disguise, and it would not extrapolate to new ids. The honest version of that signal isyears_since_2022(module 33). - Tuning on the test set. The loop kept the best of three test scores, so 0.906 was a best case, not an estimate.
RandomizedSearchCVnow chooses on training folds, nested CV estimates the whole procedure (0.867 ± 0.017), and the test set is read once (module 37). - The wrong metric name. R² is the share of price variance explained, not an accuracy, and “90.6%” invites the reading “right 90.6% of the time”. Report R² with the MAE (USD 64,679 per house) and the RMSE (USD 107,131). RMSE is much larger than MAE because a few expensive houses get large errors (module 35).
- Biased importances. Impurity importance comes from the training data, favors continuous columns and splits
neighborhoodover 8 dummy columns, so each piece looks small. Permutation importance on the test rows shuffles the raw column: neighborhood (0.471) is as important as square footage (0.447). With neighborhood in one target-encoded column, the school rating and bedrooms add little beyond it and size (module 43).
Residuals: the points scatter around 0 with no curve and no funnel on the log scale, and every neighborhood’s median residual lies within about ±6% (log ratios of −0.043 for Oak Hill and +0.055 for Lakeview). The model has no large bias for any neighborhood (module 35).
The honest report: “Our random forest explains about 87–89% of the price variance on houses it never saw (nested CV R² 0.867; test R² 0.890), with an average error of USD 64,700 per house. Neighborhood and square footage drive prices.” The test R² is above the nested CV estimate for two reasons: the final model trains on all 2,250 training rows while each inner fit sees only 1,000 of them (P5-07 showed that tree ensembles still gain from more rows), and 750 test houses with a few extreme prices carry noise. The nested CV estimate is the safer number to plan with.
P5-16 · Refactor: a PyTorch network as a scikit-learn estimator
Section titled “P5-16 · Refactor: a PyTorch network as a scikit-learn estimator”Refactor, then choose a model and justify it: a teammate trains a churn MLP with the procedural script in the starter below. It works, but it cannot sit in a Pipeline, it fits its scaler by hand and it stops early on the same validation rows that later judge it. The teammate also claims that the network beats gradient boosting. Refactor the network into an estimator, then settle the claim fairly.
- Write
TorchMLPClassifier(ClassifierMixin, BaseEstimator). Its__init__only stores the hyperparameters (hidden=32, dropout=0.2, lr=1e-2, weight_decay=1e-2, max_epochs=60, patience=5, random_state=0). Itsfitholds out 20% of the training rows it receives (stratified) for early stopping on ROC-AUC, trains withAdamW,BCEWithLogitsLossand batches of 128, restores the best epoch and setsclasses_,model_andn_epochs_. Addpredict_probaandpredict. - Split
data/customers.csvinto 60% train, 20% validation and 20% test (stratified,random_state=42). Preprocess inside the pipeline: anOrdinalEncoderforcontractin its natural order, one-hot for the other text columns, median impute and scale for the numbers. - Fit the MLP pipeline with seeds 0, 1 and 2, and print each one’s stopping epoch and validation ROC-AUC.
- Tune LightGBM (
n_estimators=100,n_jobs=1) with 8 Optuna trials (TPE sampler withseed=42) overlearning_rate(0.02 to 0.2, log scale) andnum_leaves(4 to 31), scored by 3-fold stratified CV on the training rows only. Score the tuned model on the validation rows. - Bootstrap the validation rows 1,000 times (paired: the same rows for both models) and print a 95% interval for the ROC-AUC gap between LightGBM and the best MLP.
- Save the best MLP’s
state_dictwith its hyperparameters, rebuild it from the file withweights_only=Trueand check that it gives the same probabilities. Then score only the chosen model on the test set.
MLP epochs [7, 15, 21] | valid ROC-AUC [0.834 0.828 0.828]LightGBM lr 0.029, num_leaves 8 | valid ROC-AUC 0.848LightGBM - MLP: +0.014, 95% bootstrap interval -0.002 to +0.033restored MLP gives the same probabilities: Truechosen: LightGBM | test ROC-AUC 0.832Acceptance criteria:
- Your output matches the Expected output, and your class passes through
make_pipelineandclonewithout changes. - Your justification compares the gap with the seed spread and with the sampling noise of the validation set, and gives a reason for the choice that does not depend on a gap inside the noise.
import optunaimport torchfrom sklearn.base import BaseEstimator, ClassifierMixinfrom sklearn.preprocessing import OrdinalEncoderfrom torch import nnfrom torch.utils.data import DataLoader, TensorDataset
torch.set_num_threads(1) # small networks train faster on one thread, and repeat exactly
# the teammate's procedural version, to refactor:# scaler = StandardScaler().fit(X_train_numbers) # by hand, outside a pipeline# T_tr = torch.tensor(scaler.transform(...), dtype=torch.float32)# torch.manual_seed(seed); model = nn.Sequential(nn.Linear(n_in, 32), nn.ReLU(),# nn.Dropout(0.2), nn.Linear(32, 1))# for epoch in range(60):# model.train(); for xb, yb in loader: zero_grad(); backward(); step()# auc = roc_auc_score(y_va, ...) # stops on the judging rows# if auc > best: best_state = copy.deepcopy(model.state_dict()) else: patience ...
class TorchMLPClassifier(ClassifierMixin, BaseEstimator): def __init__(self, hidden: int = 32, dropout: float = 0.2, lr: float = 1e-2, weight_decay: float = 1e-2, max_epochs: int = 60, patience: int = 5, random_state: int = 0) -> None: # TODO: store every argument unchanged ...
def fit(self, X, y) -> "TorchMLPClassifier": # TODO: classes_, an internal 20% stopping split, the training loop ...
def predict_proba(self, X) -> np.ndarray: # TODO: eval mode, no_grad, sigmoid; return two columns ...
# TODO: data split; pre() with OrdinalEncoder + OneHotEncoder + scaled numbers# TODO: three MLP pipelines; Optuna for LightGBM; paired bootstrap; save, reload, test onceHint 1
The estimator rules from module 34: __init__ stores its arguments under the same names and does nothing else; everything learned ends with _ and is set in fit; fit returns self. Then clone(), make_pipeline and CV work with your class like with any scikit-learn model.
Hint 2
Early stopping inside fit must use rows from the data that fit receives. Split them with train_test_split(X, y, test_size=0.2, stratify=y, random_state=self.random_state). Keep the best weights with {k: v.clone() for k, v in self.model_.state_dict().items()}, because state_dict() returns live references.
Hint 3
For the bootstrap, draw row indices with rng.integers(0, n, n) and compute both ROC-AUCs on the same indices, then take the 2.5th and 97.5th percentiles of the 1,000 gaps. Seeds measure training noise only; the bootstrap measures how much the score would move on other customers.
Solution
from pathlib import Path
import optunaimport torchfrom lightgbm import LGBMClassifierfrom sklearn.base import BaseEstimator, ClassifierMixinfrom sklearn.preprocessing import OrdinalEncoderfrom sklearn.utils.validation import check_is_fittedfrom torch import nnfrom torch.utils.data import DataLoader, TensorDataset
torch.set_num_threads( 1) # small networks train faster on one thread, and repeat exactlyoptuna.logging.set_verbosity(optuna.logging.WARNING)
class TorchMLPClassifier(ClassifierMixin, BaseEstimator): """A one-hidden-layer MLP with early stopping, usable in a scikit-learn Pipeline."""
def __init__( self, hidden: int = 32, dropout: float = 0.2, lr: float = 1e-2, weight_decay: float = 1e-2, max_epochs: int = 60, patience: int = 5, random_state: int = 0, ) -> None: self.hidden = hidden self.dropout = dropout self.lr = lr self.weight_decay = weight_decay self.max_epochs = max_epochs self.patience = patience self.random_state = random_state
def _build(self, n_in: int) -> nn.Module: return nn.Sequential( nn.Linear(n_in, self.hidden), nn.ReLU(), nn.Dropout(self.dropout), nn.Linear(self.hidden, 1), )
def _proba(self, X: np.ndarray) -> np.ndarray: self.model_.eval() with torch.no_grad(): logits = self.model_(torch.tensor(X, dtype=torch.float32)).squeeze(1) return torch.sigmoid(logits).numpy()
def fit(self, X, y) -> "TorchMLPClassifier": X, y = np.asarray(X, dtype=np.float32), np.asarray(y) self.classes_ = np.unique(y) # early stopping on 20% of the training rows, never on outside data X_fit, X_stop, y_fit, y_stop = train_test_split( X, y, test_size=0.2, stratify=y, random_state=self.random_state ) torch.manual_seed(self.random_state) self.model_ = self._build(X.shape[1]) opt = torch.optim.AdamW( self.model_.parameters(), lr=self.lr, weight_decay=self.weight_decay ) loss_fn = nn.BCEWithLogitsLoss() data = TensorDataset( torch.tensor(X_fit), torch.tensor(y_fit, dtype=torch.float32) ) loader = DataLoader(data, batch_size=128, shuffle=True) best, waited = -1.0, 0 for epoch in range(1, self.max_epochs + 1): self.model_.train() for xb, yb in loader: opt.zero_grad() loss_fn(self.model_(xb).squeeze(1), yb).backward() opt.step() auc = roc_auc_score(y_stop, self._proba(X_stop)) if auc > best: best, waited, self.n_epochs_ = auc, 0, epoch state = {k: v.clone() for k, v in self.model_.state_dict().items()} else: waited += 1 if waited >= self.patience: break self.model_.load_state_dict(state) return self
def predict_proba(self, X) -> np.ndarray: check_is_fitted(self) p = self._proba(np.asarray(X, dtype=np.float32)) return np.column_stack([1 - p, p])
def predict(self, X) -> np.ndarray: return self.classes_[(self.predict_proba(X)[:, 1] >= 0.5).astype(int)]
customers = pd.read_csv("data/customers.csv")X = customers[CHURN_CAT + CHURN_NUM]y = customers["churned"]X_rest, X_te, y_rest, y_te = train_test_split( X, y, test_size=0.2, stratify=y, random_state=42)X_tr, X_va, y_tr, y_va = train_test_split( X_rest, y_rest, test_size=0.25, stratify=y_rest, random_state=42)
def pre() -> ColumnTransformer: order = [["month-to-month", "one-year", "two-year"]] return ColumnTransformer( [ ("contract", OrdinalEncoder(categories=order), ["contract"]), ( "cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["region", "plan", "payment_method"], ), ( "num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), CHURN_NUM, ), ] )
# 1. the MLP as a pipeline step, with three seedsmlps = [ make_pipeline(pre(), TorchMLPClassifier(random_state=s)).fit(X_tr, y_tr) for s in (0, 1, 2)]mlp_auc = np.array([roc_auc_score(y_va, m.predict_proba(X_va)[:, 1]) for m in mlps])print( "MLP epochs", [m[-1].n_epochs_ for m in mlps], "| valid ROC-AUC", mlp_auc.round(3))
# 2. LightGBM tuned with Optuna on CV of the training rows onlydef objective(trial: optuna.Trial) -> float: model = make_pipeline( pre(), LGBMClassifier( n_estimators=100, learning_rate=trial.suggest_float("lr", 0.02, 0.2, log=True), num_leaves=trial.suggest_int("num_leaves", 4, 31), random_state=42, n_jobs=1, verbose=-1, ), ) cv = StratifiedKFold(3, shuffle=True, random_state=42) return cross_val_score(model, X_tr, y_tr, cv=cv, scoring="roc_auc").mean()
study = optuna.create_study( direction="maximize", sampler=optuna.samplers.TPESampler(seed=42))study.optimize(objective, n_trials=8)params = study.best_paramsgbm = make_pipeline( pre(), LGBMClassifier( n_estimators=100, learning_rate=params["lr"], num_leaves=params["num_leaves"], random_state=42, n_jobs=1, verbose=-1, ),).fit(X_tr, y_tr)p_gbm = gbm.predict_proba(X_va)[:, 1]print( f"LightGBM lr {params['lr']:.3f}, num_leaves {params['num_leaves']} " f"| valid ROC-AUC {roc_auc_score(y_va, p_gbm):.3f}")
# 3. paired bootstrap of the validation rows: is the gap larger than the noise?best_mlp = mlps[int(np.argmax(mlp_auc))]p_mlp = best_mlp.predict_proba(X_va)[:, 1]rng = np.random.default_rng(42)y_arr = y_va.to_numpy()gaps = []for _ in range(1000): i = rng.integers(0, len(y_arr), len(y_arr)) gaps.append(roc_auc_score(y_arr[i], p_gbm[i]) - roc_auc_score(y_arr[i], p_mlp[i]))low, high = np.percentile(gaps, [2.5, 97.5])print( f"LightGBM - MLP: {roc_auc_score(y_va, p_gbm) - mlp_auc.max():+.3f}, " f"95% bootstrap interval {low:+.3f} to {high:+.3f}")
# 4. save the MLP's weights, rebuild it, and check the probabilitiesnet = best_mlp[-1]Path("models").mkdir(exist_ok=True)n_in = net.model_[0].in_featurestorch.save( {"params": net.get_params(), "n_in": n_in, "state_dict": net.model_.state_dict()}, "models/mlp.pt",)saved = torch.load("models/mlp.pt", weights_only=True)restored = TorchMLPClassifier(**saved["params"])restored.model_, restored.classes_ = restored._build(saved["n_in"]), net.classes_restored.model_.load_state_dict(saved["state_dict"])Z_va = best_mlp[0].transform(X_va)same = np.allclose(restored.predict_proba(Z_va), net.predict_proba(Z_va))print("restored MLP gives the same probabilities:", same)
# 5. choose, then read the test set oncetest_auc = roc_auc_score(y_te, gbm.predict_proba(X_te)[:, 1])print(f"chosen: LightGBM | test ROC-AUC {test_auc:.3f}")assert sameassert low < 0 < high or roc_auc_score(y_va, p_gbm) > mlp_auc.max()MLP epochs [7, 15, 21] | valid ROC-AUC [0.834 0.828 0.828]LightGBM lr 0.029, num_leaves 8 | valid ROC-AUC 0.848LightGBM - MLP: +0.014, 95% bootstrap interval -0.002 to +0.033restored MLP gives the same probabilities: Truechosen: LightGBM | test ROC-AUC 0.832How it works:
- The refactor fixes two method problems. The scaler now sits in the pipeline, so it learns from training rows only, also inside any CV loop. Early stopping now uses rows inside the training data, so the validation rows judge both models fairly; before, the MLP’s validation score was picked over up to 60 epochs on those very rows (modules 34 and 42).
- The seed matters a little: the three MLPs stop after 7, 15 and 21 epochs and score 0.828 to 0.834. Each fit stops on a different 20% of its rows, so seeds change the data split as well as the starting weights (module 44).
- The gap is inside the noise. LightGBM leads the best MLP by 0.014, but the paired bootstrap interval runs from −0.002 to +0.033: on other samples of 1,000 customers, the gap could vanish. The seed spread (0.006) is smaller than the gap, but it measures only training noise, not the noise of the validation sample (module 37).
- The choice: LightGBM, but not because of the gap. At worst the interval gives the MLP an edge of 0.002, so the MLP is not clearly better either. Between two models that tie, keep the one that is simpler to run: LightGBM needs no scaling, no custom class and no PyTorch in production, and it has fewer settings to monitor. Optuna chose a small, slow model (8 leaves, learning rate 0.029) on CV of the training rows, without touching the validation rows (module 38).
- Reloading checks the save.
torch.load(..., weights_only=True)reads tensors and plain values, not arbitrary pickled code. Saving the hyperparameters with the weights lets_build()rebuild the same network, and the probabilities match (module 42). - The test set, read once for LightGBM, gives 0.832, below its validation score of 0.848. The validation score was a selection among models, and 1,000 test customers carry noise; report 0.832. On tabular data like this, gradient boosting is the usual winner. A neural network earns its place on images, text and other raw signals, as the CNN of module 42 (and the shapes of P5-01) shows.
Self-assessment rubric
Section titled “Self-assessment rubric”Rate yourself on each skill after you finish the exercises. Base the rating on what you did without the solution.
| Skill area | Not yet | Getting there | Ready |
|---|---|---|---|
| 32. Math for ML | You call fit() without knowing what it minimizes. |
You can write a dot product and a gradient, but shapes or the chain rule trip you up. | You predict matrix shapes, write the log-loss gradient, check it against autograd, solve ridge with np.linalg.solve, and use expected values and Bayes’ rule to set and check a threshold. |
| 33. Feature engineering | You transform the whole table before the split. | You build features, but keep ones that do not help or let an identifier in. | You build date, curve, log and binned features in a custom transformer, compare wrapper, filter and embedded selection, use one-hot, ordinal and target encoding where each fits, and spot leaks from preprocessing and identifiers, and preprocessing that destroys the signal (stop words). |
| 34. The scikit-learn workflow | You preprocess with pandas by hand. | You use pipelines, but compare models on different folds or forget a baseline. | You build ColumnTransformer pipelines, read fitted state and feature names, write transformers and classifiers that follow the estimator rules, compare with dummy baselines and cross-validate on the training rows only. |
| 35. Regression | You report one R² and call it accuracy. | You report MAE and R², but on the log scale or without a baseline. | You model log price with TransformedTargetRegressor, tune RidgeCV and LassoCV, compare linear, KNN and tree models, report MAE, RMSE, MAPE and R² in USD, and read residual plots. |
| 36. Classification | You report accuracy on imbalanced data. | You use ROC-AUC, but compute it from labels or trust uncalibrated probabilities. | You read odds ratios, compare logistic regression, naive Bayes, KNN, SVM, forests and LightGBM, choose ROC-AUC, AP, macro F1, log loss or Brier by the question, calibrate probabilities, and turn costs into a threshold and a confusion matrix. |
| 37. Evaluation and tuning | You tune on the test set. | You cross-validate, but shuffle time series or compare only the means. | You read learning and validation curves, match the split to the use (stratified, group, time series), tune with randomized search and Optuna, estimate tuning with nested CV, know what resampling does to probabilities, compare models with paired folds or a paired bootstrap, and read the test set once. |
| 38. Ensembles | You pick the most complex model by default. | You use forests and boosting, but cannot say why a stack wins. | You use early stopping and the OOB score, compare voting with a leak-free stack, read its meta-model weights, and weigh a consistent gain against its cost in fit time and maintenance. |
| 39. Unsupervised learning | You present k-means clusters as natural types. | You choose k, but read silhouette or BIC in isolation. | You test for structure with silhouette and BIC and read PCA variance, compare k-means with Ward and DBSCAN, read t-SNE and UMAP maps without reading gaps as distances, profile segments, learn clusters inside a pipeline, and know what Isolation Forest and LOF can and cannot detect. |
| 40. Time series | You shuffle time series. | You use TimeSeriesSplit, but build lag features that peek at the future. |
You resample flows, read STL, ADF and ACF results, build lags of at least the horizon, compare SARIMA and boosting with naive baselines by MASE on a backtest, keep a final hold-out and ship only a model that beats the baseline. |
| 41. NLP fundamentals | You feed raw text to a model. | You vectorize text, but drop negations or fit the vectorizer on all rows. | You clean text inside the vectorizer, choose stop words and n-grams by the task, validate with groups, build LSA embeddings and NMF and LDA topics, search by cosine similarity and read what text clusters really follow. |
| 42. Deep learning with PyTorch | Your training loop fails on shapes or dtypes. | You train a network, but evaluate in train mode or save it in a fragile way. | You predict CNN shapes, wrap a training loop with early stopping and restored weights in a scikit-learn estimator, switch train and eval mode, and save and reload a state_dict safely. |
| 43. Interpretability | You read impurity importances as the truth. | You compute SHAP or permutation importance, but not on held-out rows. | You read partial dependence, ICE curves and SHAP values together, find interactions and impossible rows, rank features with permutation importance on held-out rows, and refuse causal claims. |
| 44. ML in production | Your model exists only in a notebook. | You save a model, but load it without checks or never watch its inputs. | You save a hashed bundle with metadata, serve it with FastAPI and pydantic, test it with TestClient, track runs with MLflow, and measure drift with PSI and the KS test. |
You are ready for the capstones when you can:
- Solve at least 11 of the 16 exercises without opening the solution, including one challenge.
- Predict the shapes, feature names and fitted state of a small pipeline (P5-01).
- Find the leaks in a text or tabular script and rebuild it as one pipeline with cross-validation on the training rows (P5-02, P5-15).
- State the baseline of a task and its metric before you build any model (P5-03).
- Derive a log-loss gradient, check it with autograd and reproduce scikit-learn’s coefficients with gradient descent and PyTorch (P5-04).
- Keep a new feature only when it lowers the CV error by a margin you set in advance (P5-05).
- Choose a model type, a metric and a validation split for a request, and show with a backtest why shuffled CV misleads on time series (P5-06, P5-12).
- Diagnose bias and variance from learning and validation curves, and say what to try next (P5-07).
- Choose a classifier by the quality of its probabilities, calibrate one, and apply a cost threshold with a confusion matrix and Bayes’ rule (P5-08).
- Test whether clusters exist before you name them, with several clusterers, maps and topic models (P5-09, P5-11).
- Check a claim about a feature with partial dependence, ICE and SHAP, and spot an interaction and impossible rows (P5-10).
- Compare models on the same folds with paired differences, and weigh the gain against the cost (P5-11, P5-13).
- Turn a procedural training loop into a scikit-learn estimator, and judge a model gap with a paired bootstrap (P5-16).
- Ship a model as a checked bundle behind a validated API, and detect a population shift with PSI (P5-14).
- Report a test result that disappoints, and say what it teaches instead of changing the model to fit it (P5-12).
Rated “Not yet” in a row? Review that module’s lesson and cheat sheet, redo two of its core exercises, then try the matching checkpoint exercise again. When every row reads “Getting there” or “Ready”, move on to the capstones. Each capstone is a complete project that uses the same skills as this checkpoint: features and pipelines, honest model choice, one test, explanations and deployment.