Mini Project: A Leakage-Free Preprocessing Pipeline
In this project you build the preprocessing for a realistic, messy customer table and predict which customers will cancel their subscription (churn). The table mixes numbers stored as text, inconsistent category spellings, impossible values, missing values, duplicated rows, a block of uninformative survey answers, and a rare positive class. You will prepare it twice:
- the naive way that many first projects use: clean, impute, scale, encode, select features and oversample on the whole table, then cross-validate;
- the leakage-free way: fixed cleaning rules first, a held-out test set, and every learned step inside one pipeline that cross-validation refits per fold.
Then you compare both estimates with the score on the held-out test set, the number that tells you how the model would do on new customers. Finally you choose a decision threshold without touching the test set, save the fitted pipeline with joblib, reload it, and write up the results with the template at the end.
You will use: cleaning and the cleaning log, imputation with missing indicators, scaling, one-hot encoding, filter feature selection, SMOTE, threshold adjustment, stratified splits and pipelines. Each step is a complete program; later steps repeat the pieces they need, so any of them runs on its own.
Step 1: The messy table
The generator plants known problems, so you can check that the cleaning finds every one of them. The data is synthetic; a real churn table would come from a billing system and a CRM, and it would contain personal data, so access, retention and consent rules apply (Privacy, Consent, Licensing).
import numpy as np
import pandas as pd
def make_messy(n=1200, seed=7):
rng = np.random.default_rng(seed)
age = rng.integers(18, 80, n)
income = rng.lognormal(10.6, 0.5, n)
minutes = rng.gamma(2.0, 150.0, n)
calls = rng.poisson(1.5, n)
tenure = rng.integers(1, 72, n)
plan = rng.choice(["basic", "pro", "team"], n, p=[0.6, 0.3, 0.1])
logit = (-2.6 + 0.7 * calls - 0.06 * tenure + 1.2 * (plan == "basic")
- 1.2 * (np.log(income) - 10.6) - 0.003 * (minutes - 300))
churn = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
df = pd.DataFrame({"customer_id": np.arange(10001, 10001 + n), "age": age.astype(str),
"income": [f"{v:,.0f}" for v in income], "minutes": minutes.round(1),
"support_calls": calls, "tenure_months": tenure, "plan": plan})
for j in range(40): # survey answers 1-5, unrelated to churn
df[f"q{j + 1:02d}"] = rng.integers(1, 6, n)
df["churn"] = churn
df.loc[rng.random(n) < 0.05, "age"] = "unknown"
df.loc[rng.random(n) < 0.01, "age"] = "230"
dollar = rng.random(n) < 0.3
df.loc[dollar, "income"] = "quot; + df.loc[dollar, "income"]
df.loc[rng.random(n) < 0.08, "income"] = "n/a"
df.loc[rng.random(n) < 0.15, "minutes"] = np.nan
variants = {"basic": ["Basic", " basic", "BASIC"], "pro": ["Pro", "PRO "], "team": ["Team", "team "]}
messy = rng.random(n) < 0.25
df.loc[messy, "plan"] = [variants[p][rng.integers(len(variants[p]))] for p in df.loc[messy, "plan"]]
dup = df.sample(80, random_state=1) # 80 rows exported twice
return pd.concat([df, dup]).sample(frac=1, random_state=2).reset_index(drop=True)
raw = make_messy()
print(raw.shape, "churn rate:", round(raw["churn"].mean(), 3))
print(raw.iloc[:5, :8].to_string())
print("dtypes:", raw[["age", "income", "minutes", "plan"]].dtypes.astype(str).to_dict())
print("plan spellings:", sorted(raw["plan"].unique()))
print("exact duplicate rows:", int(raw.duplicated().sum()))(1280, 48) churn rate: 0.13
customer_id age income minutes support_calls tenure_months plan q01
0 10913 24 $21,826 61.0 0 33 team 4
1 10580 73 41,061 557.3 4 5 basic 1
2 10375 44 15,107 39.0 1 36 basic 2
3 10712 28 36,315 391.3 1 63 basic 3
4 10489 54 37,993 162.1 1 17 Basic 4
dtypes: {'age': 'object', 'income': 'object', 'minutes': 'float64', 'plan': 'object'}
plan spellings: [' basic', 'BASIC', 'Basic', 'PRO ', 'Pro', 'Team', 'basic', 'pro', 'team', 'team ']
exact duplicate rows: 80
The table has 1,280 rows and 48 columns; about one customer in eight churns (13%). age and income are text, plan has 10 spellings of three plans, and 80 rows are exact duplicates.
Step 2: Cleaning with fixed rules and a log
Cleaning uses only rules decided in advance (types, ranges, spellings, deduplication). None of them learns from the data, so it is safe to run them on the whole table before the split. Everything that learns (medians, scales, categories, selected features, synthetic samples) comes later, inside the pipeline.
import numpy as np
import pandas as pd
def make_messy(n=1200, seed=7):
rng = np.random.default_rng(seed)
age = rng.integers(18, 80, n)
income = rng.lognormal(10.6, 0.5, n)
minutes = rng.gamma(2.0, 150.0, n)
calls = rng.poisson(1.5, n)
tenure = rng.integers(1, 72, n)
plan = rng.choice(["basic", "pro", "team"], n, p=[0.6, 0.3, 0.1])
logit = (-2.6 + 0.7 * calls - 0.06 * tenure + 1.2 * (plan == "basic")
- 1.2 * (np.log(income) - 10.6) - 0.003 * (minutes - 300))
churn = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
df = pd.DataFrame({"customer_id": np.arange(10001, 10001 + n), "age": age.astype(str),
"income": [f"{v:,.0f}" for v in income], "minutes": minutes.round(1),
"support_calls": calls, "tenure_months": tenure, "plan": plan})
for j in range(40):
df[f"q{j + 1:02d}"] = rng.integers(1, 6, n)
df["churn"] = churn
df.loc[rng.random(n) < 0.05, "age"] = "unknown"
df.loc[rng.random(n) < 0.01, "age"] = "230"
dollar = rng.random(n) < 0.3
df.loc[dollar, "income"] = "quot; + df.loc[dollar, "income"]
df.loc[rng.random(n) < 0.08, "income"] = "n/a"
df.loc[rng.random(n) < 0.15, "minutes"] = np.nan
variants = {"basic": ["Basic", " basic", "BASIC"], "pro": ["Pro", "PRO "], "team": ["Team", "team "]}
messy = rng.random(n) < 0.25
df.loc[messy, "plan"] = [variants[p][rng.integers(len(variants[p]))] for p in df.loc[messy, "plan"]]
dup = df.sample(80, random_state=1)
return pd.concat([df, dup]).sample(frac=1, random_state=2).reset_index(drop=True)
def clean(df, log):
def note(step, rule, before, after, changed):
log.append(f"{step:10s} {rule:46s} rows {before}->{after}, values changed {changed}")
n0 = len(df)
out = df.drop_duplicates().copy()
note("dedup", "drop exact duplicate rows", n0, len(out), 0)
age = pd.to_numeric(out["age"], errors="coerce")
bad = age.notna() & ~age.between(0, 120)
note("age", "to number; 'unknown' and outside [0, 120] -> NaN", len(out), len(out),
int(age.isna().sum() + bad.sum()))
out["age"] = age.where(~bad)
inc_text = out["income"].str.replace(r"[$,]", "", regex=True)
out["income"] = pd.to_numeric(inc_text, errors="coerce")
note("income", "strip $ and thousands commas; 'n/a' -> NaN", len(out), len(out),
int(out["income"].isna().sum()))
allowed = {"basic", "pro", "team"}
plan = out["plan"].str.strip().str.lower()
assert set(plan) <= allowed, f"unknown plans: {set(plan) - allowed}"
note("plan", "strip and lower-case, check against allowed", len(out), len(out),
int((plan != out["plan"]).sum()))
out["plan"] = plan
return out
log = []
data = clean(make_messy(), log)
print("\n".join(log))
print(data[["age", "income", "minutes", "plan"]].dtypes.astype(str).to_dict())
print("missing values:", data[["age", "income", "minutes"]].isna().sum().to_dict())
print("rows:", len(data), " churners:", int(data["churn"].sum()), f"({data['churn'].mean():.1%})")dedup drop exact duplicate rows rows 1280->1200, values changed 0
age to number; 'unknown' and outside [0, 120] -> NaN rows 1200->1200, values changed 66
income strip $ and thousands commas; 'n/a' -> NaN rows 1200->1200, values changed 105
plan strip and lower-case, check against allowed rows 1200->1200, values changed 293
{'age': 'float64', 'income': 'float64', 'minutes': 'float64', 'plan': 'object'}
missing values: {'age': 66, 'income': 105, 'minutes': 169}
rows: 1200 churners: 157 (13.1%)
Every planted problem is accounted for in the log: 80 duplicates removed, the text columns converted, impossible ages and placeholders turned into missing values, and the plan spellings unified (the assert would stop the script if a new spelling appeared). The cleaned table has 1,200 customers, 157 of whom (13.1%) churned. The missing values are left in place: filling them is a learned step and belongs in the pipeline.
Step 3: Naive vs leakage-free evaluation
Both versions use the same steps: median imputation with missing indicators, standardisation, one-hot encoding, keeping the 10 features with the highest ANOVA F-score, SMOTE, and logistic regression. The metric is average precision (area under the precision-recall curve), which suits a rare positive class; a model that ranks at random scores about the churn rate.
- Naive: skips deduplication (so copies of a customer can sit in training and validation folds), fits every step on all rows, oversamples all rows with SMOTE, then cross-validates the model alone.
- Leakage-free: deduplicates, holds out a stratified 25% test set, and cross-validates an
imblearnpipeline on the training part only.imblearn.pipeline.Pipelineapplies SMOTE duringfitonly, so validation folds and the test set are never resampled.
import numpy as np
import pandas as pd
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import make_pipeline as make_imb_pipeline
from sklearn.compose import ColumnTransformer
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
def make_messy(n=1200, seed=7):
rng = np.random.default_rng(seed)
age = rng.integers(18, 80, n)
income = rng.lognormal(10.6, 0.5, n)
minutes = rng.gamma(2.0, 150.0, n)
calls = rng.poisson(1.5, n)
tenure = rng.integers(1, 72, n)
plan = rng.choice(["basic", "pro", "team"], n, p=[0.6, 0.3, 0.1])
logit = (-2.6 + 0.7 * calls - 0.06 * tenure + 1.2 * (plan == "basic")
- 1.2 * (np.log(income) - 10.6) - 0.003 * (minutes - 300))
churn = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
df = pd.DataFrame({"customer_id": np.arange(10001, 10001 + n), "age": age.astype(str),
"income": [f"{v:,.0f}" for v in income], "minutes": minutes.round(1),
"support_calls": calls, "tenure_months": tenure, "plan": plan})
for j in range(40):
df[f"q{j + 1:02d}"] = rng.integers(1, 6, n)
df["churn"] = churn
df.loc[rng.random(n) < 0.05, "age"] = "unknown"
df.loc[rng.random(n) < 0.01, "age"] = "230"
dollar = rng.random(n) < 0.3
df.loc[dollar, "income"] = "quot; + df.loc[dollar, "income"]
df.loc[rng.random(n) < 0.08, "income"] = "n/a"
df.loc[rng.random(n) < 0.15, "minutes"] = np.nan
variants = {"basic": ["Basic", " basic", "BASIC"], "pro": ["Pro", "PRO "], "team": ["Team", "team "]}
messy = rng.random(n) < 0.25
df.loc[messy, "plan"] = [variants[p][rng.integers(len(variants[p]))] for p in df.loc[messy, "plan"]]
dup = df.sample(80, random_state=1)
return pd.concat([df, dup]).sample(frac=1, random_state=2).reset_index(drop=True)
def clean(df, dedup=True):
out = (df.drop_duplicates() if dedup else df).copy()
age = pd.to_numeric(out["age"], errors="coerce")
out["age"] = age.where(age.between(0, 120))
out["income"] = pd.to_numeric(out["income"].str.replace(r"[$,]", "", regex=True), errors="coerce")
out["plan"] = out["plan"].str.strip().str.lower()
return out
NUM = ["age", "income", "minutes", "support_calls", "tenure_months"] + [f"q{j + 1:02d}" for j in range(40)]
CAT = ["plan"]
def preprocessor():
return ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median", add_indicator=True), StandardScaler()), NUM),
("cat", OneHotEncoder(handle_unknown="ignore"), CAT),
])
raw = make_messy()
cv = StratifiedKFold(5, shuffle=True, random_state=0)
# Naive: no dedup, every step fitted on all rows, SMOTE before cross-validation.
naive = clean(raw, dedup=False)
y_all = naive["churn"].to_numpy()
X_all = preprocessor().fit_transform(naive[NUM + CAT])
X_all = SelectKBest(f_classif, k=10).fit_transform(X_all, y_all)
X_res, y_res = SMOTE(random_state=0).fit_resample(X_all, y_all)
naive_cv = cross_val_score(LogisticRegression(max_iter=1000), X_res, y_res, cv=cv,
scoring="average_precision").mean()
# Leakage-free: dedup, hold out a test set, all learned steps inside one pipeline.
data = clean(raw)
X_train, X_test, y_train, y_test = train_test_split(
data[NUM + CAT], data["churn"], test_size=0.25, stratify=data["churn"], random_state=0)
pipe = make_imb_pipeline(preprocessor(), SelectKBest(f_classif, k=10), SMOTE(random_state=0),
LogisticRegression(max_iter=1000))
honest_cv = cross_val_score(pipe, X_train, y_train, cv=cv, scoring="average_precision").mean()
pipe.fit(X_train, y_train)
test_ap = average_precision_score(y_test, pipe.predict_proba(X_test)[:, 1])
print(f"train {len(X_train)} rows, test {len(X_test)} rows, test churn rate {y_test.mean():.3f}")
print(f"naive CV estimate AP {naive_cv:.3f}")
print(f"leakage-free CV estimate AP {honest_cv:.3f}")
print(f"held-out test set AP {test_ap:.3f}")
names = pipe[0].get_feature_names_out()[pipe[1].get_support()]
print("features kept:", [n.split("__")[1] for n in names])train 900 rows, test 300 rows, test churn rate 0.130
naive CV estimate AP 0.875
leakage-free CV estimate AP 0.497
held-out test set AP 0.494
features kept: ['age', 'income', 'minutes', 'support_calls', 'tenure_months', 'q04', 'q10', 'plan_basic', 'plan_pro', 'plan_team']
The naive estimate is 0.875, the leakage-free one 0.497, and the held-out test set gives 0.494 (a random ranking would score about 0.13, the churn rate). The naive number is not a slightly optimistic estimate; it is a different quantity. SMOTE before cross-validation creates synthetic churners by interpolating between real ones, so most validation-fold churners have near-copies in the training folds, and the "duplicates across folds" add exact copies on top. The leakage-free estimate, made only from training data, lands close to the test score, which is what an estimate is for. The selected features show that the pipeline found the planted signals (support calls, tenure, income, minutes, plan) and ignored 38 of the 40 survey columns. Three kept features carry no real signal (age, q04, q10): with 900 training rows, a filter by F-score lets a little noise through, which is one reason to tune k with cross-validation.
Note: Of the three leaks in the naive version, SMOTE before the split is by far the largest here. Try removing the leaks one at a time (add
dedup=True; move SMOTE after the split; moveSelectKBestinto the CV) and watch the naive estimate fall towards the honest one.
Step 4: Threshold, final report, saving and reloading
A probability of churn becomes a decision ("call this customer") only with a threshold. Choose it on the training data, from out-of-fold predictions (cross_val_predict), never on the test set. Here the business asks for a recall of at least 0.7 (catch 70% of churners); we take the highest threshold that achieves it, so that as few loyal customers as possible get a call. Then the test set is used once, and the fitted pipeline is saved with joblib, reloaded and checked.
import io
import joblib
import numpy as np
import pandas as pd
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import make_pipeline as make_imb_pipeline
from sklearn.compose import ColumnTransformer
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, precision_score, recall_score
from sklearn.model_selection import StratifiedKFold, cross_val_predict, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
def make_messy(n=1200, seed=7):
rng = np.random.default_rng(seed)
age = rng.integers(18, 80, n)
income = rng.lognormal(10.6, 0.5, n)
minutes = rng.gamma(2.0, 150.0, n)
calls = rng.poisson(1.5, n)
tenure = rng.integers(1, 72, n)
plan = rng.choice(["basic", "pro", "team"], n, p=[0.6, 0.3, 0.1])
logit = (-2.6 + 0.7 * calls - 0.06 * tenure + 1.2 * (plan == "basic")
- 1.2 * (np.log(income) - 10.6) - 0.003 * (minutes - 300))
churn = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
df = pd.DataFrame({"customer_id": np.arange(10001, 10001 + n), "age": age.astype(str),
"income": [f"{v:,.0f}" for v in income], "minutes": minutes.round(1),
"support_calls": calls, "tenure_months": tenure, "plan": plan})
for j in range(40):
df[f"q{j + 1:02d}"] = rng.integers(1, 6, n)
df["churn"] = churn
df.loc[rng.random(n) < 0.05, "age"] = "unknown"
df.loc[rng.random(n) < 0.01, "age"] = "230"
dollar = rng.random(n) < 0.3
df.loc[dollar, "income"] = "quot; + df.loc[dollar, "income"]
df.loc[rng.random(n) < 0.08, "income"] = "n/a"
df.loc[rng.random(n) < 0.15, "minutes"] = np.nan
variants = {"basic": ["Basic", " basic", "BASIC"], "pro": ["Pro", "PRO "], "team": ["Team", "team "]}
messy = rng.random(n) < 0.25
df.loc[messy, "plan"] = [variants[p][rng.integers(len(variants[p]))] for p in df.loc[messy, "plan"]]
dup = df.sample(80, random_state=1)
return pd.concat([df, dup]).sample(frac=1, random_state=2).reset_index(drop=True)
def clean(df):
out = df.drop_duplicates().copy()
age = pd.to_numeric(out["age"], errors="coerce")
out["age"] = age.where(age.between(0, 120))
out["income"] = pd.to_numeric(out["income"].str.replace(r"[$,]", "", regex=True), errors="coerce")
out["plan"] = out["plan"].str.strip().str.lower()
return out
NUM = ["age", "income", "minutes", "support_calls", "tenure_months"] + [f"q{j + 1:02d}" for j in range(40)]
CAT = ["plan"]
pre = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median", add_indicator=True), StandardScaler()), NUM),
("cat", OneHotEncoder(handle_unknown="ignore"), CAT),
])
pipe = make_imb_pipeline(pre, SelectKBest(f_classif, k=10), SMOTE(random_state=0),
LogisticRegression(max_iter=1000))
data = clean(make_messy())
X_train, X_test, y_train, y_test = train_test_split(
data[NUM + CAT], data["churn"], test_size=0.25, stratify=data["churn"], random_state=0)
# 1. Threshold from out-of-fold predictions on the training part only.
cv = StratifiedKFold(5, shuffle=True, random_state=0)
oof = cross_val_predict(pipe, X_train, y_train, cv=cv, method="predict_proba")[:, 1]
candidates = np.round(np.arange(0.05, 0.96, 0.01), 2)
ok = [t for t in candidates if recall_score(y_train, oof >= t) >= 0.7]
threshold = max(ok)
print(f"chosen threshold {threshold:.2f}: out-of-fold recall {recall_score(y_train, oof >= threshold):.3f}, "
f"precision {precision_score(y_train, oof >= threshold):.3f}")
# 2. Fit on all training rows, evaluate once on the test set.
pipe.fit(X_train, y_train)
pred = pipe.predict_proba(X_test)[:, 1] >= threshold
tn, fp, fn, tp = confusion_matrix(y_test, pred).ravel().tolist()
print(f"test: recall {recall_score(y_test, pred):.3f}, precision {precision_score(y_test, pred):.3f}, "
f"TP {tp} FN {fn} FP {fp} TN {tn}")
# 3. Save the fitted pipeline together with its threshold, reload, check.
buffer = io.BytesIO()
joblib.dump({"pipeline": pipe, "threshold": threshold, "features": NUM + CAT}, buffer)
size_kb = buffer.tell() / 1024
buffer.seek(0)
bundle = joblib.load(buffer)
new_customers = pd.DataFrame({"age": [np.nan, 61], "income": [23000, 98000], "minutes": [120.5, np.nan],
"support_calls": [5, 0], "tenure_months": [3, 60], "plan": ["basic", "Team"],
**{f"q{j + 1:02d}": [3, 3] for j in range(40)}})
new_customers["plan"] = new_customers["plan"].str.strip().str.lower() # same cleaning rules
p = bundle["pipeline"].predict_proba(new_customers[bundle["features"]])[:, 1]
same = np.allclose(bundle["pipeline"].predict_proba(X_test)[:, 1], pipe.predict_proba(X_test)[:, 1])
print(f"saved {size_kb:.0f} KiB; reloaded pipeline gives identical test probabilities: {same}")
print("new customers:", np.round(p, 3).tolist(), "-> call:", (p >= bundle["threshold"]).tolist())chosen threshold 0.57: out-of-fold recall 0.703, precision 0.361
test: recall 0.641, precision 0.342, TP 25 FN 14 FP 48 TN 213
saved 29 KiB; reloaded pipeline gives identical test probabilities: True
new customers: [0.998, 0.0] -> call: [True, False]
The threshold of 0.57 was chosen without looking at the test set and gives an out-of-fold recall of 0.703 on the training part. On the test set, used once, the recall is 0.641 with a precision of 0.342: the model catches 25 of the 39 test churners, at the cost of 48 calls to customers who would have stayed. The recall falls a little short of the 0.7 target, and that is an honest result, not a reason to move the threshold on the test set: with only 39 churners in the test set, one churner more or less moves recall by 0.026. Report it as it is, and tune more conservatively (for example aim for 0.75 out-of-fold) if the target is strict. The saved bundle contains the whole fitted pipeline (imputation medians, scaling statistics, categories, the selected features, the model) and the threshold, so the first new customer (no age, low income, many support calls, three months in, basic plan) is scored exactly as in training: a missing age is filled with the training median and flagged.
Warning:
joblib.load(likepickle) can run arbitrary code from the file. Only load model files you created or trust, and pin the scikit-learn version: a pipeline saved with one version is not guaranteed to load in another. Saving & Loading Models has more.
Extensions
- Group split: customers sometimes appear under two IDs (a re-signup). Add a
household_idand useStratifiedGroupKFoldso one household never sits on both sides (K-Fold, Stratified K-Fold and Leave-One-Group-Out). - Compare remedies: replace SMOTE with
class_weight="balanced"or with no rebalancing plus the tuned threshold. Which gives the best test precision at recall 0.7? - Tune inside: wrap the pipeline in
GridSearchCVoverselectkbest__kand the regularisationC, and estimate its performance with nested cross-validation. - A different model: swap in
HistGradientBoostingClassifier. Which steps can you drop (scaling, imputation)? - Make the cleaning reusable: turn
cleaninto aFunctionTransformerat the front of the pipeline, so production data gets exactly the same rules.
Write-up template
# Churn model: preprocessing and evaluation report
Data: <source, extract date, rows before/after cleaning> Owner: <team>
Label: churn within <period>; positive rate <x.x%> (train) / <x.x%> (test)
## Cleaning (fixed rules, before the split)
| Step | Rule | Rows/values affected |
|---|---|---|
| dedup | exact duplicates dropped | <n> |
| ... | ... | ... |
## Split
<random stratified 75/25 | group | time>, seed <n>. Why this split matches how the model will be used: <...>
## Learned preprocessing (inside the pipeline, fitted on training folds only)
- numeric: <imputer + indicator>, <scaler>
- categorical: <encoder, unknown handling>
- selection: <method, k>
- imbalance: <SMOTE / weights / none>
## Results
| Estimate | Metric | Value |
|---|---|---|
| naive (leaky) CV | AP | <...> |
| leakage-free CV (train only) | AP | <...> |
| held-out test (used once) | AP | <...> |
Threshold <t> chosen on out-of-fold predictions for recall >= <target>.
Test: recall <...>, precision <...>, confusion matrix <...>.
## Risks and next steps
- <drift in plan mix, new categories, missingness process changes, ...>
## Artefacts
model file <name>, scikit-learn <version>, imbalanced-learn <version>, code commit <hash>Checklist
- Every planted problem in Step 1 is handled and appears in the cleaning log.
- Nothing that learns from data is fitted before the split or outside the pipeline.
- The test set was used exactly once, after all choices (features, threshold) were made.
- The leakage-free CV estimate is close to the test score; the naive one is not, and you can say why.
- The saved file contains the pipeline and the threshold, and reloading gives identical predictions.
- The write-up states the split, the metric, the number of rows, and the versions.