Suffolk University • Sawyer Business School

Trust, but Verify: Tuning, Explaining & Uncertainty

Cross-validation that doesn't lie, hyperparameter search with Optuna, SHAP for one customer and the whole book, conformal intervals that keep their promise, fairness slices, and the one-page model card

Session 9 of 13 · Mon Nov 16
Module: Evaluation & Optimization
150 Minutes
Mondays 5:00 PM
Hands-On Learning
01 // LEARNING OBJECTIVES

What You'll Learn Today

By the end of tonight you'll have both the concept and the working code — every objective maps to a cell you run yourself.

01

Choose a Cross-Validation Scheme That Matches Production

StratifiedKFold for rare labels, GroupKFold when the same customer appears many times, TimeSeriesSplit when tomorrow must be predicted from yesterday. The wrong splitter is the most common way a great offline score becomes a bad live one.

02

Tune Without Fooling Yourself

RandomizedSearchCV, HalvingRandomSearchCV, and a ten-line Optuna study — tuned on training folds, judged once on a test set you never touched.

03

Explain a Prediction With SHAP

TreeExplainer on the boosted hotel model: a waterfall for one booking, a beeswarm for the whole book, and the sentence you say to an executive about each.

04

Attach Honest Uncertainty and Check Fairness

Conformal prediction with MAPIE turns any model into one with 90% intervals — a promise you can keep. Then slice every metric by group, and write the model card that says what the model is for and where it fails.

02 // SESSION AGENDA

Today's Journey

A business question, a dataset, a model — and the judgment to evaluate it.

5:00 PM - 5:20 PM

Why Great Offline Scores Go Bad

20 minutes

Three true stories: a support-ticket model that memorized customers (plain KFold on repeated customers), a demand forecast that saw the future (random split on time series), and a competition team that tuned on the public leaderboard. All three had the same disease — the validation didn't match production.

  • The unit the model faces in production must be the unit that is held out: a new customer, a future week
  • GroupKFold, StratifiedGroupKFold, TimeSeriesSplit — pick the splitter before the model
5:20 PM - 5:45 PM

Hyperparameter Search: Random, Halving, Optuna

25 minutes

Grid search is exhaustive and slow; random search finds a near-best point in a tenth of the budget; successive halving spends the budget on promising configurations; Optuna learns from each trial. A ten-line Optuna objective on the hotel GBM, with the CV inside and the test set outside.

  • Tune the two or three knobs that matter (learning rate, leaves, min_samples_leaf); the rest is noise
  • Nested CV is the honest answer when the dataset is small; a single held-out test set is the practical one when it isn't
5:45 PM - 6:05 PM

SHAP I: One Booking, Explained

20 minutes

Shapley values split a prediction fairly among the features. TreeExplainer computes them exactly for boosted trees in milliseconds. A waterfall plot for booking #4,117: base rate 37% → non-refundable deposit +28 points → 200-day lead time +9 → repeat guest −6 → 68% cancellation probability.

  • Local explanation: 'why this booking?' — the sentence a hotel manager, a loan officer, or a regulator asks
  • SHAP explains the model, not the world: it attributes, it does not intervene
6:05 PM - 6:15 PM

Break

10 minutes

Stretch, coffee, project teams meet.

6:15 PM - 6:40 PM

SHAP II: The Whole Book & Partial Dependence

25 minutes

The beeswarm: every booking, every feature, colored by value — the global picture in one plot. Mean |SHAP| as the honest importance ranking. Then PartialDependenceDisplay with ICE lines: the shape of lead time's effect, and where individual bookings deviate from the average.

  • Beeswarm reading: long tails to the right are the features that push cancellations up; color tells you which direction of the feature does it
  • Dependence plots reveal interactions: lead time hurts far more for non-refundable deposits
6:40 PM - 7:10 PM

Conformal Prediction: Intervals That Keep Their Promise

30 minutes

A point forecast is a bet. Conformal prediction uses a calibration set's residuals to wrap any model in intervals with guaranteed coverage — 90% means 90%, no distributional assumptions. MAPIE's SplitConformalRegressor on Ames prices, SplitConformalClassifier on hotel cancellations (prediction sets: {cancel}, {stay}, or {both} when the model is unsure).

  • Coverage is a promise about the long run, valid for GBDTs, neural nets, anything — given exchangeable data
  • A set-valued prediction of {both} is the model saying 'send this one to a human'
7:10 PM - 7:30 PM

Fairness Slices, the Model Card & Milestone 3

20 minutes

Equal accuracy can hide unequal harm: compute false-negative and false-positive rates by group (customer type, market segment, country) and look for gaps. Then the one-page model card — intended use, data, metrics by slice, known failure modes, owner. Milestone 3 of the final project is assigned in full — tonight is where your tuned model and error analysis come from.

  • Credit scoring and hiring are 'high-risk' uses under the EU AI Act; explanation and human review are the direction of travel everywhere
  • Milestone 2 (baseline + metric) due Mon Nov 23; Milestone 3 (tuned model + error analysis) due Mon Nov 30 — both pass/fail
FEATURED VIDEO

StatQuest — Cross Validation

Why one split is a coin flip and five splits are a measurement.

03 // INTERACTIVE RESOURCES

Tools & Learning Materials

Notebooks, readings, explorers, and the stories behind the methods.

Hands-On

Session 9 Notebook — Tuning, Explaining & Uncertainty

GroupKFold and TimeSeriesSplit demos, an Optuna study on the hotel GBM, SHAP waterfall and beeswarm, partial dependence with ICE, MAPIE conformal intervals and prediction sets, fairness slices, and a model-card template.

Open in Colab
Play

The Conformal Explorer

Set a coverage target, watch the calibration residuals size the band, then draw new cases a hundred times and check the promise. Underfit the model, shrink the calibration set, or shift the data to see what breaks it.

Open the explorer
Interactive

MLU-Explain — Cross-Validation

K-fold, animated: watch the folds rotate and the estimate stabilize.

Open the explainer
Reading

Angelopoulos & Bates — A Gentle Introduction to Conformal Prediction

The self-contained tutorial that made conformal prediction mainstream: the split-conformal recipe, coverage guarantees, and extensions to classification, time series, and distribution shift.

Read the paper
Interactive

Google PAIR — Measuring Fairness

An explorable on why equal accuracy can hide unequal error rates, and the trade-offs between fairness definitions. Do this before the fairness-slicing lab.

Open the explainer
Interactive

MLU-Explain — Equality of Odds

A fairness criterion you can drag: equalize true- and false-positive rates across groups and see what it costs.

Open the explainer
Go Deeper

Molnar — Interpretable Machine Learning (free book)

The reference for SHAP, partial dependence, ICE, permutation importance, and counterfactuals — with the honest caveats for each.

Read online
Tool

Fairlearn

Microsoft's open-source toolkit for assessing and mitigating fairness issues: MetricFrame for sliced metrics is the one-liner behind tonight's fairness section.

Open the docs
Reading

scikit-learn User Guide — Cross-Validation: Evaluating Estimator Performance

Every splitter with a picture: KFold, StratifiedKFold, GroupKFold, StratifiedGroupKFold, TimeSeriesSplit. The visualization section alone is worth the visit.

Open the guide
Reading

SHAP Documentation — An Introduction to Explainable AI With Shapley Values

The canonical walkthrough from the library's authors: what Shapley values are, why they are the fair attribution, and how to read every plot type we use tonight.

Read the introduction
Tool

MAPIE — Model-Agnostic Prediction Interval Estimator

scikit-learn-contrib's conformal prediction library. The 1.x API (SplitConformalRegressor, CrossConformalRegressor, SplitConformalClassifier) is what we use; the theory pages are short and readable.

Open the docs
Tool

Optuna — Hyperparameter Optimization Framework

Define an objective, call study.optimize, read study.best_params. The tutorial's first example is the ten lines we write in class.

Open the site
Go Deeper

Kaggle Learn — Machine Learning Explainability

Permutation importance, partial dependence, and SHAP values in four short lessons with exercises. The fastest path to fluency before Milestone 3.

Start the course
Story

Story: A Readmission Model Rebuilt for Equity at ZSFG

Zuckerberg San Francisco General replaced a vendor readmission model with an in-house gradient-boosted tree that includes social-determinants data — and reports lower readmissions and narrower equity gaps. Explanation, slicing, and monitoring in a real hospital.

Read the story
Reading

Mitchell et al. (2019) — Model Cards for Model Reporting

The paper that defined the one-page model card: intended use, factors, metrics, evaluation data, ethical considerations, caveats. Your final project includes one.

Read the paper
Refresher

Refresher: Müller & Guido, Ch. 5 — Cross-Validation & Grid Search (official notebook)

k-fold, stratified, leave-one-out, shuffle-split, and grouped cross-validation, then grid search with nested CV. The slow version of tonight's first hour.

Open in Colab
04 // HANDS-ON ACTIVITIES

Learning by Doing

Open the notebook and build it with us.

Activity 1

Explain It, Bound It, Slice It

Take the early-stopped hotel GBM from Session 8. Explain ten bookings with SHAP, wrap the model in 90% conformal prediction sets, and check whether the error rates differ between city and resort guests.

1

Explain

shap.TreeExplainer(gbm) → shap_values on the test set. Waterfall for one booking, beeswarm for all. Write one sentence for each.

2

Bound

Split the training data into fit and calibration halves. MAPIE SplitConformalClassifier with confidence_level=0.9. Count how many test bookings get a two-label set — those are the ones to route to a human.

3

Slice

False-negative rate and false-positive rate at your chosen threshold, by hotel type and by customer_type. Any gap above 5 points gets a sentence in the model card.

4

Document

Fill the model-card template: intended use, training data, metrics overall and by slice, known failure modes, owner, review date.

python
import shap, numpy as np, pandas as pd
from mapie.classification import SplitConformalClassifier
from sklearn.model_selection import train_test_split

# gbm, X_tr, X_te, y_tr, y_te: the early-stopped HistGradientBoosting model and split from Session 8
explainer = shap.TreeExplainer(gbm)
sv = explainer(X_te.iloc[:2000])
shap.plots.waterfall(sv[0])          # one booking: base rate → each feature's push → prediction
shap.plots.beeswarm(sv, max_display=12)   # the whole book

# Conformal prediction sets: fit on one half, calibrate on the other, 90% coverage
X_fit, X_cal, y_fit, y_cal = train_test_split(X_tr, y_tr, test_size=0.3, stratify=y_tr, random_state=835)
cp = SplitConformalClassifier(estimator=gbm, confidence_level=0.9, prefit=True)
cp.conformalize(X_cal, y_cal)
y_pred, y_sets = cp.predict_set(X_te)
n_labels = y_sets[:, :, 0].sum(axis=1)
print(f'coverage: {np.mean(y_sets[np.arange(len(y_te)), y_te.values, 0]):.3f}   '
      f'singletons: {np.mean(n_labels == 1):.1%}   ambiguous {{both}}: {np.mean(n_labels == 2):.1%}')

# Fairness slice: error rates by hotel type at threshold 0.5
pred = gbm.predict(X_te)
for grp, idx in X_te.groupby('hotel', observed=True).groups.items():
    yt, yp = y_te.loc[idx], pd.Series(pred, index=X_te.index).loc[idx]
    fnr = ((yt == 1) & (yp == 0)).sum() / (yt == 1).sum(); fpr = ((yt == 0) & (yp == 1)).sum() / (yt == 0).sum()
    print(f'{grp:13s} FNR {fnr:.3f}   FPR {fpr:.3f}')

Three questions an executive will ask, three tools. Why did it say that? — the SHAP waterfall. How sure is it? — the conformal set; the bookings labeled {both} are exactly the ones a human should look at. Is it fair? — the sliced error rates. A model that can answer all three is one you can defend in front of a regulator, a customer, or a board. The model card is where the answers live.

05 // KEY TAKEAWAYS

What to Remember

Match the splitter to production: GroupKFold when units repeat, TimeSeriesSplit when time matters, stratify when labels are rare. Tune on the training folds; touch the test set once.

SHAP answers 'why this prediction?' locally and 'what drives the model?' globally. It attributes the model's output; it does not tell you what happens if you change the input.

Conformal prediction turns any model into one with guaranteed coverage, and sliced error rates turn 'is it fair?' into a table. Together with a model card, that is what 'trustworthy' means in practice.

06 // HOMEWORK

Before Next Session

Complete these before next Monday — they are the practice that makes the next session land.

Project Milestones 2 & 3 Milestone 2, due Mon Nov 23, 11:59 PM, on Canvas: your project data loaded, split before anything is fitted, the naive baseline computed, and a first model scored with the metric your decision needs. Milestone 3, due Mon Nov 30, 11:59 PM: a tuned model (two or three hyperparameters inside cross-validation), a calibration plot if you classify, SHAP for three cases a decision-maker would recognize, error rates by the slices that matter, and a half-page model card. Both are pass/fail: run top to bottom, split before fit, and the pieces present. Practice, ungraded: tonight's hotel notebook has every piece — early-stopped boosting, Optuna, SHAP waterfalls and beeswarm, MAPIE prediction sets — run it end to end on the hotel data before you try it on your own.
07 // PRACTICE

Test Yourself

Exam-style questions for the ideas in this session — Trust & Structure. Every wrong answer names the misconception behind it.

Q31 6,000 customers, 80,000 tickets, plain KFold. Why 0.91 is a mirage. Q32 Read a SHAP waterfall the way a loan officer must. Q33 A 90% conformal interval. What exactly is being promised? Q34 RFM clustering on raw dollars. Guess which column wins. Q35 Equal accuracy, unequal false negatives. Is the model fair? Q36 4% MAPE offline, 14% live. The split that saw the future.

All of Trust →

Coming Next

Session 10: Segments, Structure & Anomalies

Learning without labels: RFM segmentation with k-means, choosing k, hierarchical clustering and DBSCAN, PCA and UMAP for seeing high-dimensional data, and Isolation Forest for finding the transactions that don't belong.

ClusteringPCAAnomaly Detection