Skip to content
Visual explainer 8h to learn 5 steps

ML capstone: train, compare and report by slice

Compare several estimators with task-appropriate metrics and thresholds, report errors by slice and save a reproducible pipeline.

By Invicly Tech, , in AI and Machine Learning with Python. About 13 minutes to read.

Topic 33 of 34

In short

The second milestone trains several candidate models on the same folds and compares them with the baseline in one table. You pick metrics and a decision threshold that match how the predictions will be used, then break the errors down by slice to find where the model fails. Everything is saved as one reproducible pipeline with its data version, code version and settings.

Think of it like this: It is like a fair taste test: every dish gets the same judges, the same plates and the same score sheet, and you note which guests disliked which dish.

Explained simply

Now you train real models and compare them fairly with the baseline. Fair means every model sees the same training rows, the same folds and the same scoring code. If one model gets an easier test, the comparison is worthless.

Pick a few candidates that work in different ways: a logistic regression (a straight-line model that is easy to explain), a random forest (many decision trees voting) and a gradient boosting model (trees built one after another to fix earlier mistakes). Put the results in one table with the baseline as the first row.

Then decide how predictions turn into action. A model gives a probability, but the team needs a yes or no. The threshold is the cut-off probability. Choose it from a real limit, such as how many tickets the team can review each day, using validation data only.

Overall scores hide problems. A slice report scores the model separately for each group, such as each channel or priority. Finally, save everything needed to reproduce the winner: the whole pipeline, its settings, the data and split version and the code version.

Press Play on a diagram to walk through it one step at a time.

CompareThree questions, three kinds of metric
Does it rank well?
  • PR AUC (average precision)
  • ROC AUC
  • Threshold-free
  • Best for comparing models
Is the decision right?
  • Precision and recall at a threshold
  • Confusion matrix
  • Flag rate per day
  • Depends on the threshold
Can you trust the probability?
  • Brier score
  • Calibration curve
  • Matters when people read the score
  • Fix with CalibratedClassifierCV
CycleThe experiment loop
  1. 1
    Change one thing

    Model, feature or setting

  2. 2
    Run the same folds

    Fixed seed and split version

  3. 3
    Log the run

    Params, metrics, artifacts

  4. 4
    Compare to baseline

    Table row with mean and spread

  5. 5
    Keep or drop

    Write down why

  6. Back to step 1
MapWhat a reproducible run records
One tracked run
  • Data
    • Raw file checksum
    • split_v1 and its hash
  • Code
    • Git commit
    • Pinned requirements
  • Config
    • Model and parameters
    • Seed
    • Threshold
  • Results
    • CV mean and spread
    • Validation metrics
    • Slice report
  • Artifacts
    • model.joblib
    • config.json

In depth

Choosing candidates on purpose

Each candidate should test a different idea. Logistic regression checks whether a simple, mostly linear relationship is enough; if it nearly matches the others, prefer it, because it is easier to explain and monitor. A random forest captures interactions with little tuning. HistGradientBoostingClassifier is usually the strongest choice for tabular data, trains fast on a CPU and handles missing values on its own.

Keep tuning small and honest: a handful of settings per model, searched inside cross-validation on the training data. Fix random_state everywhere so reruns match. Deep learning is optional here; on a few thousand tabular rows it rarely beats boosted trees and costs more time. Record fit time too, since a model that is 0.005 better but 20 times slower may not be worth it.

  • Logistic regression: simple, explainable reference
  • Random forest: interactions, little tuning
  • Histogram gradient boosting: strong tabular default
  • Fix random_state; record fit time

The baseline-vs-candidate table

One table tells the story. Rows are models, starting with the naive baseline and the hand rule. Columns are the cross-validated primary metric as mean plus or minus standard deviation, the validation score, the Brier score, fit time and a short note. Highlight the chosen model and say why in a sentence.

An illustrative table for the synthetic ticket data (not measured values) might read: baseline PR AUC 0.09, urgent rule 0.15, logistic regression 0.31 plus or minus 0.03, random forest 0.29 plus or minus 0.04, gradient boosting 0.33 plus or minus 0.03. Here logistic regression and boosting overlap within one standard deviation, so the simpler model is a defensible pick. Your own report must use numbers from your own runs and label anything else as illustrative.

  • Baseline rows first
  • Mean plus or minus spread across folds
  • Validation score and Brier score
  • Fit time and a one-line note
  • Label illustrative numbers clearly

Metrics and thresholds that match the decision

With rare positives, PR AUC (average_precision) compares how well models rank risky tickets; ROC AUC can look good even when precision is poor. If people will read the probability itself, check calibration with the Brier score and a calibration curve, and wrap the model in CalibratedClassifierCV if needed.

The threshold comes from the brief. If the team can review 40 tickets a day, pick the threshold that flags about 40 a day on validation data. If the brief demands recall of at least 0.70, pick the highest threshold that still meets it. scikit-learn 1.5 and later also offer TunedThresholdClassifierCV, which tunes the cut-off with cross-validation. Freeze the threshold, then score the test set once.

FlowChoosing a threshold without touching the test set
  1. 1
    State the constraint

    Review capacity or minimum recall

  2. 2
    Score validation rows

    Probabilities from the trained pipeline

  3. 3
    Sweep thresholds

    precision_recall_curve

  4. 4
    Pick and freeze

    Write it to config.json

  5. 5
    Test once

    Report, do not retune

Slice reports that mean something

Choose slices from the brief and from risk: channel, priority, queue size bands and any group where errors would hurt people unfairly. For each slice report the row count, positive count, recall, precision and the gap to the overall figure. Sort by the worst gap.

Small slices are noisy. A slice with 15 positives can swing by 0.2 recall from two errors. Add a bootstrap confidence interval, resampling the slice rows a few hundred times, or mark the slice as too small to judge. When a slice is clearly worse, look at its errors by hand before changing the model: often the cause is missing data, a rare category or a label problem, not the algorithm.

  • Count and positives beside every metric
  • Sort by gap to overall
  • Bootstrap intervals for small slices
  • Read the errors before fixing

Saving a reproducible pipeline

Save the fitted Pipeline, preprocessing included, with joblib. Next to it, save a config with the threshold and feature list, and a requirements file pinning exact versions of scikit-learn, pandas and NumPy, because a pickled model should be loaded with the same scikit-learn version that saved it; newer versions warn and may behave differently. Only load joblib or pickle files you trust, since loading can run code; the skops library offers a safer format.

Log each run to MLflow or a similar tracker: parameters, seed, split version, data checksum, git commit, metrics and the model file as an artifact. A local tracking store on your laptop is enough for the capstone.

Learn it in 5 short steps

About 1h 35m each. Track them with a timer in your plan.

  1. 1
    Train several candidate estimators~1h 35m
  2. 2
    Build a baseline-vs-candidate table~1h 35m
  3. 3
    Choose metrics and thresholds~1h 35m
  4. 4
    Report slice-specific errors~1h 35m
  5. 5
    Save and track the pipeline~1h 35m

Key points

  • Try a small, varied set of candidates: a linear model, a tree ensemble and one boosting model are usually enough.
  • Use the same cross-validation folds for every model, and report the spread across folds, not just the mean.
  • Pick the threshold on validation data from a real constraint, such as review capacity or a minimum recall.
  • Report errors by slice with the row count next to each number; tiny slices give noisy scores.
  • Save the whole pipeline, preprocessing included, with the library versions, seed, split version and git commit.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
from sklearn.model_selection import TimeSeriesSplit, cross_validate
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier, HistGradientBoostingClassifier
from sklearn.pipeline import make_pipeline

cv = TimeSeriesSplit(n_splits=5)  # train rows are sorted by created_at
models = {'baseline': DummyClassifier(strategy='prior'),
          'logreg': make_pipeline(prep, LogisticRegression(max_iter=1000)),
          'forest': make_pipeline(prep, RandomForestClassifier(n_estimators=300, random_state=42)),
          'hgb': make_pipeline(prep, HistGradientBoostingClassifier(random_state=42))}
for name, m in models.items():
    s = cross_validate(m, X_train, y_train, cv=cv, scoring=['average_precision', 'neg_brier_score'])
    ap = s['test_average_precision']
    print(f'{name:9s} PR AUC {ap.mean():.3f} +/- {ap.std():.3f}  Brier {-s["test_neg_brier_score"].mean():.3f}')

Every candidate, baseline included, is scored on the same time-ordered folds. prep is the ColumnTransformer from the preprocessing step.

Build a slice report for the chosen threshold

After picking the pipeline and threshold, score the validation rows and group them by channel and priority. Each row of the report shows the slice size, how many real breaches it holds and the recall and precision there. Sorting by recall puts the weakest slice at the top. Expected evidence: a small table where most slices sit near the overall recall, plus perhaps one weak slice to investigate. zero_division=0 avoids warnings in slices with no flags.

python
import pandas as pd
from sklearn.metrics import precision_score, recall_score
val = val.assign(p=pipe.predict_proba(val[X_cols])[:, 1])
val['flag'] = val.p >= THRESHOLD
rows = []
for col in ['channel', 'priority']:
    for level, g in val.groupby(col):
        rows.append({'slice': f'{col}={level}', 'n': len(g),
                     'positives': int(g.breached.sum()),
                     'recall': recall_score(g.breached, g.flag, zero_division=0),
                     'precision': precision_score(g.breached, g.flag, zero_division=0)})
report = pd.DataFrame(rows).round(3).sort_values('recall')
print(report.to_string(index=False))

Pick a threshold for recall of at least 0.70 and log the run

precision_recall_curve returns thresholds in increasing order, with recall falling as the threshold rises. The code keeps the thresholds whose recall is still at least 0.70 and takes the highest, which flags the fewest tickets. It then saves the pipeline and logs parameters, metrics and the model file to MLflow. Prerequisites: pip install mlflow; runs go to a local store by default, and mlflow ui shows them at http://127.0.0.1:5000.

python
import numpy as np, joblib, json, mlflow, sklearn
from sklearn.metrics import precision_recall_curve, average_precision_score
p_val = pipe.predict_proba(X_val)[:, 1]
prec, rec, thr = precision_recall_curve(y_val, p_val)
ok = np.where(rec[:-1] >= 0.70)[0]
THRESHOLD = float(thr[ok[-1]])  # highest threshold that keeps recall >= 0.70
joblib.dump(pipe, 'model/model.joblib')
json.dump({'threshold': THRESHOLD, 'features': X_cols}, open('model/config.json', 'w'))
with mlflow.start_run(run_name='hgb-split_v1'):
    mlflow.log_params({'model': 'hgb', 'split': 'split_v1', 'seed': 42, 'sklearn': sklearn.__version__})
    mlflow.log_metrics({'val_pr_auc': average_precision_score(y_val, p_val), 'threshold': THRESHOLD})
    mlflow.log_artifact('model/model.joblib')
    mlflow.log_artifact('model/config.json')

Quick reference

  • Same folds, same seed, same scoring code for every model, baseline included.
  • Rare positives: compare models with average_precision (PR AUC), not accuracy.
  • Report mean plus or minus standard deviation across folds; overlapping ranges mean no clear winner.
  • Threshold from the brief: review capacity or minimum recall, chosen on validation data.
  • TunedThresholdClassifierCV (scikit-learn 1.5+) tunes the cut-off inside cross-validation.
  • Slice report columns: slice, n, positives, recall, precision, gap to overall.
  • Save the full Pipeline plus config.json plus pinned requirements; load only trusted pickles.

Common mistakes

  • Tuning the threshold or choosing the winner on the test set, then reporting that same test score as unbiased.
  • Comparing models on different folds or different random seeds, so the gaps are partly noise.
  • Saving only the model and rebuilding the preprocessing by hand at serving time.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Logistic regression scores 0.31 plus or minus 0.03 PR AUC and gradient boosting 0.33 plus or minus 0.03. What is a reasonable conclusion?

Question 2

2The team can review about 40 tickets a day. How should you set the threshold?

Question 3

3Why save the whole Pipeline rather than just the fitted estimator?

Question 4

4A slice has 15 positives and its recall is 0.53 against 0.71 overall. What is the best next step?

Question 5

5Which metric tells you whether predicted probabilities can be read at face value?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Build the baseline-vs-candidate table for at least three candidates plus the baseline, using cross_validate on the same folds.

  2. Exercise 2medium

    Find the threshold that flags at most 10 percent of validation tickets, and report the recall and precision it gives.

  3. Exercise 3hard

    Add a bootstrap 90 percent confidence interval for recall in each slice, and mark slices whose interval is wider than 0.3 as too small to judge.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

How many models should I compare in the capstone?
Three or four candidates plus the baselines is plenty. More models mainly add noise to the comparison and time to the project.
Should I use the test set to choose between the top two models?
No. Choose with cross-validation and the validation split. The test set gives one final, honest number after every choice is frozen.
Do I need MLflow, or is a spreadsheet enough?
Any tracker works if it records parameters, data and split versions, code version, metrics and the model file for every run. MLflow does this for free on a laptop and is widely used.

Go deeper

ShareXLinkedInWhatsApp