Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 30 min · revision 2

Lab: Honest Tuning and Slice-Based Error Analysis

Split off a test set with a manifest, tune a gradient-boosted fraud model with a randomised search on the development rows only, slice its out-of-fold errors by channel and country with bootstrap intervals, trace the worst slice to a logging change, fix it, and score the test set once.

Contentsand lesson path

What you will learn

  • Design a validation scheme (stratified, grouped or time-based cross-validation plus an untouched test set) that mirrors deployment, and tune hyperparameters inside it without contaminating the test set.
  • Perform error analysis by slicing errors across segments and use it to prioritize the next data or modeling change.

Prerequisites: Machine Learning Fundamentals

01. Goal and setup

An average score hides where a model fails. Error analysis looks at the mistakes themselves: which groups of rows they come from, what those rows have in common, and which change would remove the most of them. A slice is a subset of rows defined by one attribute, such as the payment channel or the country.

In this lab you work on a fraud model for online card payments. The fraud team reviews every payment with a predicted probability of at least 0.3, and the metric they care about is recall: the share of frauds that reach them. You will tune the model without touching the test set, find the slice where it fails, trace that failure to its cause, fix it, and only then score the test set, once.

You need: Python 3.12, scikit-learn 1.9, pandas 3 and SciPy (installed with scikit-learn). The whole lab takes about two minutes; tune.py is the slowest step.

Project layout at the end of the lab
slice-lab/
├── make_data.py   step 1: writes payments.csv
├── split.py       step 1: test split and split_manifest.json
├── common.py      shared loading code and the model
├── tune.py        step 2: randomised search, writes best_params.json
├── slices.py      step 3: out-of-fold recall per slice
├── errors.py      step 4: read the misses of the worst slice
├── compare.py     step 5: before and after the fix
└── final.py       step 6: the single test-set evaluation
Terminal
mkdir slice-lab && cd slice-lab
python3.12 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install "scikit-learn==1.9.*" "pandas==3.1.*"

02. Step 1: Generate the data and split off the test set

The generator simulates 120 days of payments. Fraud depends on a device risk score from a separate risk service, on new payees, on the amount and on account age. It also plants a realistic bug: on day 61 the web client started writing the device score to a new field, and the feature pipeline still reads only the old one. You know this because you can read the generator; the lab is about finding it from the errors.

The test set is split off first, before any modelling, and its payment IDs go into a split manifest together with the seed, the rule and a hash of the data file. Every later script reads the manifest, so no script can accidentally train or tune on a test row.

Two design choices need a word, because they differ from the validation lesson. The payment day stays in the table for analysis but is not a model feature: a real model would meet only future days, outside its training range. And the test set is a random 20%, not the last days, because this lab needs the period after the day-61 release on both sides of the split, and the generator has no drift over time. For a real fraud model, which always scores future payments, hold out the latest weeks as the test set and use time-ordered folds, as lesson 3 shows.

Python · make_data.py
"""Writes payments.csv: card-not-present payments over 120 days. Label: fraud."""
import numpy as np
import pandas as pd

rng = np.random.default_rng(7)
n = 20_000
day = rng.integers(1, 121, n)
channel = rng.choice(["app", "web", "phone"], n, p=[0.6, 0.3, 0.1])
country = rng.choice(["GB", "IE", "FR", "MT"], n, p=[0.72, 0.15, 0.12, 0.01])
account_days = rng.gamma(2.0, 200.0, n).round()
amount = rng.lognormal(3.5, 1.0, n).round(2)
new_payee = (rng.random(n) < 0.25).astype(int)
risk = rng.normal(size=n)                    # device risk, measured by the risk service
device_score = (50 + 15 * risk + rng.normal(0, 4, n)).round(1)
logit = (-3.6 + 1.6 * risk + 0.9 * new_payee + 0.35 * np.log(amount)
         - 0.002 * account_days)
fraud = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)

df = pd.DataFrame({"payment_id": np.arange(n), "day": day, "channel": channel,
                   "country": country, "account_days": account_days, "amount": amount,
                   "new_payee": new_payee, "device_score": device_score,
                   "fraud": fraud})
# Since the web release on day 61, the web client logs the score in a new field,
# and the feature pipeline only reads the old one.
moved = (df.channel == "web") & (df.day >= 61)
df["web_device_score"] = np.where(moved, df.device_score, np.nan)
df.loc[moved, "device_score"] = np.nan
df.to_csv("payments.csv", index=False)
print(f"{len(df)} payments, fraud rate {df.fraud.mean():.3f}, "
      f"device_score missing in {df.device_score.isna().mean():.1%} of rows")
Python · split.py
import hashlib
import json

import pandas as pd
from sklearn.model_selection import train_test_split

df = pd.read_csv("payments.csv")
dev, test = train_test_split(df, test_size=0.2, stratify=df["fraud"], random_state=0)
manifest = {
    "data_sha256": hashlib.sha256(open("payments.csv", "rb").read()).hexdigest(),
    "seed": 0, "rule": "stratified random 20% test, split before any modelling",
    "test_ids": sorted(test["payment_id"].tolist()),
}
json.dump(manifest, open("split_manifest.json", "w"))
print(f"dev {len(dev)} rows ({dev.fraud.sum()} frauds), "
      f"test {len(test)} rows ({test.fraud.sum()} frauds)")
Python · common.py
import json

import pandas as pd
from sklearn.ensemble import HistGradientBoostingClassifier

FEATURES = ["channel", "country", "account_days", "amount", "new_payee",
            "device_score"]


def load(part, fixed=False):
    """part = 'dev' or 'test', as recorded in split_manifest.json."""
    df = pd.read_csv("payments.csv")
    if fixed:  # read the score from whichever field the client wrote it to
        df["device_score"] = df["device_score"].fillna(df["web_device_score"])
    test_ids = set(json.load(open("split_manifest.json"))["test_ids"])
    in_test = df["payment_id"].isin(test_ids)
    df = df[in_test] if part == "test" else df[~in_test]
    X = df[FEATURES].astype({"channel": "category", "country": "category"})
    return X, df["fraud"].to_numpy(), df


def model(**params):
    return HistGradientBoostingClassifier(categorical_features="from_dtype",
                                          random_state=0, **params)
Terminal
python make_data.py
python split.py
Expected output
20000 payments, fraud rate 0.116, device_score missing in 15.4% of rows
dev 16000 rows (1855 frauds), test 4000 rows (464 frauds)

03. Step 2: Tune on the development rows only

RandomizedSearchCV draws a fixed number of settings from distributions you give it and scores each with cross-validation. With four hyperparameters, a grid of only three values each already needs 81 settings, while 12 random draws try 12 different values of every hyperparameter. When only one or two of them really matter, which is common, random search explores those more finely for the same budget. The search scores average precision because the team works from a ranked queue. Note that load("dev") is the only data the script sees.

Python · tune.py
import json

from scipy.stats import loguniform, randint
from sklearn.model_selection import RandomizedSearchCV, StratifiedKFold

from common import load, model

X, y, _ = load("dev")                         # the test rows are never loaded here
space = {"learning_rate": loguniform(0.02, 0.3),
         "max_leaf_nodes": randint(8, 64),
         "min_samples_leaf": randint(10, 200),
         "l2_regularization": loguniform(1e-3, 10)}
search = RandomizedSearchCV(model(), space, n_iter=12, scoring="average_precision",
                            cv=StratifiedKFold(5, shuffle=True, random_state=0),
                            random_state=0)
search.fit(X, y)
best = {k: (int(v) if float(v).is_integer() else round(float(v), 4))
        for k, v in search.best_params_.items()}
json.dump(best, open("best_params.json", "w"))
print(f"best CV average precision: {search.best_score_:.3f}")
for name, value in best.items():
    print(f"  {name:<18} {value}")
Terminal
python tune.py
Expected output
best CV average precision: 0.442
  l2_regularization  0.0668
  learning_rate      0.0932
  max_leaf_nodes     8
  min_samples_leaf   174

The search prefers small trees: 8 leaves, each holding at least 174 rows. Do not report 0.442 as the model's expected performance: it is the best of 12 cross-validated scores, so it carries the selection bias you met in the validation lesson. The honest figure comes from the test set at the end.

04. Step 3: Slice the out-of-fold errors

Error analysis needs predictions for rows the model did not train on, or the errors look rarer than they are. cross_val_predict gives exactly that: each development row is predicted by the fold model that held it out. The script then computes recall per slice with a bootstrap interval (resample the slice's frauds 1,000 times and take the middle 95% of the recalls), and an impact column: the slice's share of all frauds times its recall gap, which is how many points of overall recall the slice costs.

Python · slices.py
import json
import sys

import numpy as np
from sklearn.model_selection import StratifiedKFold, cross_val_predict

from common import load, model

fixed = "--fixed" in sys.argv
X, y, df = load("dev", fixed=fixed)
cv = StratifiedKFold(5, shuffle=True, random_state=1)
p = cross_val_predict(model(**json.load(open("best_params.json"))), X, y, cv=cv,
                      method="predict_proba")[:, 1]
df = df.assign(p=p, flagged=p >= 0.3)
df.to_csv("oof_fixed.csv" if fixed else "oof.csv", index=False)

rng = np.random.default_rng(0)


def recall_ci(caught):
    """Recall of one slice and a 95% bootstrap interval over its frauds."""
    boot = [rng.choice(caught, caught.size).mean() for _ in range(1000)]
    return caught.mean(), *np.percentile(boot, [2.5, 97.5])


frauds = df[df.fraud == 1]
overall = frauds.flagged.mean()
print(f"overall recall at threshold 0.3: {overall:.3f}  "
      f"(precision {df[df.flagged].fraud.mean():.3f})")
print(f"{'slice':<14} {'frauds':>6} {'recall':>7} {'95% interval':>14} {'impact':>7}")
for col in ["channel", "country"]:
    for value, part in frauds.groupby(col):
        r, lo, hi = recall_ci(part.flagged.to_numpy())
        impact = len(part) / len(frauds) * (overall - r)  # recall points lost overall
        print(f"{col + '=' + value:<14} {len(part):6d} {r:7.3f} "
              f"   {lo:.2f} to {hi:.2f} {impact:+7.3f}")
Terminal
python slices.py
Expected output
overall recall at threshold 0.3: 0.401  (precision 0.466)
slice          frauds  recall   95% interval  impact
channel=app      1138   0.467    0.44 to 0.49  -0.040
channel=phone     195   0.451    0.38 to 0.52  -0.005
channel=web       522   0.239    0.20 to 0.28  +0.045
country=FR        218   0.404    0.33 to 0.47  -0.000
country=GB       1346   0.396    0.37 to 0.42  +0.004
country=IE        268   0.422    0.36 to 0.49  -0.003
country=MT         23   0.435    0.26 to 0.65  -0.000

The web slice stands out on both counts: recall 0.239 against 0.467 for the app, an interval (0.20 to 0.28) that does not overlap those of the other channels, and the largest impact, 4.5 points of overall recall. The countries look alike. Malta is the reminder to read intervals: with 23 frauds, its interval runs from 0.26 to 0.65, so a gap there, in either direction, would tell you little until more data arrives. Rank slices by impact and by how sure you are, not by the lowest recall alone.

05. Step 4: Read the misses of the worst slice

A slice tells you where; the rows tell you why. Sample a manageable number of missed web frauds and look at them. When something stands out, check how common it is among the cases the model gets right too: a trait that is just as common there cannot explain the misses.

Python · errors.py
import pandas as pd

df = pd.read_csv("oof.csv")
web_frauds = df[(df.channel == "web") & (df.fraud == 1)]
missed = web_frauds[~web_frauds.flagged]
caught = web_frauds[web_frauds.flagged]

sample = missed.sample(40, random_state=0)       # read 40 misses by hand
print("40 missed web frauds, a few of them:")
cols = ["day", "amount", "new_payee", "device_score"]
print(sample[cols].head(6).to_string(index=False))
print(f"\ndevice_score missing: {sample.device_score.isna().mean():.0%} of sampled "
      f"misses, {caught.device_score.isna().mean():.0%} of caught web frauds")
for name, part in [("before day 61", web_frauds[web_frauds.day < 61]),
                   ("from day 61", web_frauds[web_frauds.day >= 61])]:
    print(f"web recall {name}: {part.flagged.mean():.3f} ({len(part)} frauds)")
Terminal
python errors.py
Expected output
40 missed web frauds, a few of them:
 day  amount  new_payee  device_score
 117   31.96          1           NaN
   9   56.42          0          45.2
  73   42.57          0           NaN
  68   89.07          0           NaN
  86   34.30          0           NaN
  84   35.19          0           NaN

device_score missing: 68% of sampled misses, 12% of caught web frauds
web recall before day 61: 0.445 (247 frauds)
web recall from day 61: 0.055 (275 frauds)

The device score is missing in 68% of the sampled misses but in only 12% of the caught web frauds, and web recall collapses from 0.445 to 0.055 on day 61. That points to a data problem, not a modelling one. Asking the web team confirms the field rename. This sample also gives a ceiling for the fix: if a cause explains a share s of the errors, removing it completely cuts the error rate by at most that share, from e to e × (1 − s). Here about 68% of web misses have the missing score, so even a perfect fix leaves the other 32% of web misses, and a cause seen in only 5% of errors could never be worth more than 5% of them.

06. Step 5: Fix the cause and re-measure on the same folds

The fix is in the data: read the score from whichever field the client used (fixed=True in common.py). Re-run the same out-of-fold analysis with the same folds and settings, so that the comparison changes one thing only.

Python · compare.py
import pandas as pd

old, new = pd.read_csv("oof.csv"), pd.read_csv("oof_fixed.csv")
print(f"{'out-of-fold recall':<20} {'before fix':>10} {'after fix':>10}")
for name, mask in [("all frauds", old.fraud == 1),
                   ("web frauds", (old.fraud == 1) & (old.channel == "web")),
                   ("app frauds", (old.fraud == 1) & (old.channel == "app"))]:
    before, after = old[mask].flagged.mean(), new[mask].flagged.mean()
    print(f"{name:<20} {before:10.3f} {after:10.3f}")
print(f"{'precision':<20} {old[old.flagged].fraud.mean():10.3f} "
      f"{new[new.flagged].fraud.mean():10.3f}")
Terminal
python slices.py --fixed > /dev/null
python compare.py
Expected output
out-of-fold recall   before fix  after fix
all frauds                0.401      0.463
web frauds                0.239      0.427
app frauds                0.467      0.482
precision                 0.466      0.460

Web recall rises from 0.239 to 0.427, close to the 0.445 the web slice had before the release, and overall recall from 0.401 to 0.463 at almost the same precision. The app slice barely moves, as it should. Because the hyperparameters were tuned on the broken data, you could re-run tune.py with the fix; a fair comparison then needs the search repeated for both versions.

07. Step 6: Score the test set once

Every decision is made: settings, threshold, data fix. Fit on all development rows and evaluate the test rows for the first and only time, with bootstrap intervals over test rows.

Python · final.py
import json

import numpy as np

from common import load, model

X_dev, y_dev, _ = load("dev", fixed=True)
X_test, y_test, _ = load("test", fixed=True)    # first and only use of the test rows
fitted = model(**json.load(open("best_params.json"))).fit(X_dev, y_dev)
flagged = fitted.predict_proba(X_test)[:, 1] >= 0.3

rng = np.random.default_rng(0)
idx = [rng.integers(0, len(y_test), len(y_test)) for _ in range(2000)]
recall = [flagged[i][y_test[i] == 1].mean() for i in idx]
precision = [y_test[i][flagged[i]].mean() for i in idx]
for name, value, boot in [("recall", flagged[y_test == 1].mean(), recall),
                          ("precision", y_test[flagged].mean(), precision)]:
    lo, hi = np.percentile(boot, [2.5, 97.5])
    print(f"test {name:<9} {value:.3f}  (95% bootstrap interval {lo:.3f} to {hi:.3f})")
Terminal
python final.py
Expected output
test recall    0.442  (95% bootstrap interval 0.394 to 0.488)
test precision 0.473  (95% bootstrap interval 0.426 to 0.522)

Test recall is 0.442 (0.394 to 0.488), consistent with the out-of-fold 0.463. This is the number to report, with its interval and the manifest that defines the test rows. If it had been far below the development estimate, the right response would be to investigate the difference, not to tune again on the test set.

08. Check your understanding

Practice check · 3 questions

Tuning and slicing

Answer from the scripts and outputs of the lab.

Q1. Why does `slices.py` analyse predictions from `cross_val_predict` instead of predictions from one model fitted on all development rows?
Q2. In `errors.py`, 68% of the sampled web misses have no device score. Why does the script also measure that share among the web frauds the model caught?
Q3. `tune.py` tries 12 random settings of four hyperparameters instead of a grid. Why can that work better on the same budget?
Practice only: not graded, not saved, not evidence.

09. Apply it

In the practice project, after fixing the leaks, finish with the same routine.

  1. Write the split manifest first, then tune inside the development rows with a search whose budget you state.
  2. Build a slice table from out-of-fold predictions with counts, bootstrap intervals and an impact column, and pick the three slices that cost the most.
  3. For each, read a sample of its errors, compare the suspected cause with the rows the model gets right, and write a hypothesis and the change you would try first.

10. Review prompt

Without looking back, explain why the test set is split off before tuning and what the manifest records; why error analysis uses out-of-fold predictions; how the impact of a slice is computed and why a slice with few positives needs an interval; what check showed that the missing device score explained the web misses; and why the best search score is not the number you report.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check