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 4 of 6 · Lab · 30 min · revision 2

Lab: Bootstrap a Confidence Interval for a Model Metric

Train a classifier, write a percentile bootstrap for its test F1 with NumPy's default_rng, check it against scipy.stats.bootstrap, measure how the interval narrows as the test set grows, and test whether a 95% interval really covers the target about 95% of the time.

Contentsand lesson path

What you will learn

  • Quantify uncertainty in a metric with a bootstrap confidence interval and judge whether a difference between two models is meaningful.

01. Goal and setup

A test-set metric is an estimate. Your test set is one sample of the data the model will meet; another sample of the same size would give a different F1. A confidence interval puts a range around the estimate that reflects this sampling noise. For a mean there are textbook formulas, but for F1, ROC-AUC or most other model metrics there is no simple one.

The bootstrap gets around this by simulation. It treats the test set as a stand-in for the whole population, draws many new test sets from it, recomputes the metric on each, and reads the spread of those values. In this lab you write the bootstrap yourself with NumPy, check it against SciPy, see how the interval width depends on the number of test rows, and check that a "95%" interval earns its name.

You need: Python 3.12 with NumPy, SciPy and scikit-learn (tested with NumPy 2.5, SciPy 1.18 and scikit-learn 1.9). Everything runs on a laptop CPU in a few seconds per step. The data is synthetic and seeded, so your numbers will match the ones below.

Project layout at the end of the lab
bootstrap-lab/
├── train.py         step 1: trains a model, writes preds.npz
├── preds.npz        labels and predictions for 10,000 held-out rows
├── boot.py          step 2: F1 and the percentile bootstrap
├── ci.py            step 2: the interval for the 1,000-row test set
├── stability.py     step 3
├── scipy_check.py   step 4
├── size.py          step 5
└── coverage.py      step 6
Terminal
mkdir bootstrap-lab && cd bootstrap-lab
python3.12 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install numpy scipy scikit-learn

02. Step 1: Train a model and save its predictions

The script creates 12,000 rows with about 20% positives, trains a logistic regression on 2,000 of them and saves its predictions for the other 10,000. In real work you would have only a test set, here the first 1,000 of those rows. The remaining rows act as a large "future" sample, so that steps 5 and 6 can check the method against something close to the truth.

Python · train.py
"""Train a classifier on seeded synthetic data and save its test predictions."""
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score
from sklearn.model_selection import train_test_split

X, y = make_classification(n_samples=12_000, n_features=10, n_informative=5,
                           weights=[0.8], class_sep=1.5, flip_y=0.02,
                           random_state=42)  # about 20% positives
X_train, X_pool, y_train, y_pool = train_test_split(
    X, y, train_size=2_000, stratify=y, random_state=0)

model = LogisticRegression(max_iter=1_000).fit(X_train, y_train)
pred_pool = model.predict(X_pool)
np.savez("preds.npz", y_true=y_pool, y_pred=pred_pool)

test = slice(0, 1_000)  # the test set you would really have: 1,000 rows
print(f"train rows {len(y_train)}, held-out pool {len(y_pool)}, "
      f"positives in pool {y_pool.mean():.1%}")
print(f"F1 on the 1,000-row test set:  {f1_score(y_pool[test], pred_pool[test]):.3f}")
print(f"F1 on all {len(y_pool)} pool rows: {f1_score(y_pool, pred_pool):.3f}")
Terminal
python train.py
Expected output
train rows 2000, held-out pool 10000, positives in pool 20.5%
F1 on the 1,000-row test set:  0.605
F1 on all 10000 pool rows: 0.635

The same model scores 0.605 on the 1,000-row test set and 0.635 on all 10,000 rows. Nothing is wrong: 1,000 rows with about 200 positives is a small sample, and that gap is the sampling noise the interval should capture.

03. Step 2: Write the percentile bootstrap

The percentile bootstrap has four steps:

  1. Draw n row numbers from 0 to n − 1 with replacement, where n is the size of the test set. Some rows appear twice or more and others not at all.
  2. Compute the metric on those rows, using the same row numbers for the labels and the predictions, so that every row keeps its label and its prediction together.
  3. Repeat B times (B is the number of resamples).
  4. The 2.5th and 97.5th percentiles of the B values are the ends of a 95% interval.

Resampling without replacement would only reorder the same n rows, so every F1 would be identical and the interval would have zero width. With replacement, each resample contains about 63.2% of the distinct rows (the limit is 1 − 1/e), which mimics the variation between real samples. boot.py draws all row numbers at once as a B × n array with rng.integers from NumPy's default_rng, and computes F1 for every resample along the last axis.

Python · boot.py
"""Percentile bootstrap for F1, written with NumPy only."""
import numpy as np


def f1_from_labels(y_true, y_pred):
    """F1 for each row of 2-D label arrays (one row per resample), or for 1-D arrays."""
    tp = np.sum((y_true == 1) & (y_pred == 1), axis=-1)
    fp = np.sum((y_true == 0) & (y_pred == 1), axis=-1)
    fn = np.sum((y_true == 1) & (y_pred == 0), axis=-1)
    denom = 2 * tp + fp + fn
    return np.where(denom > 0, 2 * tp / np.maximum(denom, 1), 0.0)


def bootstrap_f1(y_true, y_pred, n_resamples=2_000, seed=0):
    """Return n_resamples F1 values, each on n rows drawn with replacement."""
    rng = np.random.default_rng(seed)
    n = len(y_true)
    idx = rng.integers(0, n, size=(n_resamples, n))  # row numbers, repeats allowed
    return f1_from_labels(y_true[idx], y_pred[idx])  # same idx for both arrays


def percentile_ci(values, level=0.95):
    alpha = 1 - level
    return np.percentile(values, [100 * alpha / 2, 100 * (1 - alpha / 2)])
Python · ci.py
"""Step 2: a 95% percentile bootstrap interval for F1 on the 1,000-row test set."""
import numpy as np
from sklearn.metrics import f1_score

from boot import bootstrap_f1, f1_from_labels, percentile_ci

data = np.load("preds.npz")
y_true, y_pred = data["y_true"][:1_000], data["y_pred"][:1_000]

point = f1_from_labels(y_true, y_pred)
print(f"F1 point estimate {point:.3f} (scikit-learn: {f1_score(y_true, y_pred):.3f})")

rng = np.random.default_rng(1)
one = rng.integers(0, 1_000, size=1_000)
print(f"one resample uses {len(np.unique(one))} distinct rows of 1,000")

f1s = bootstrap_f1(y_true, y_pred, n_resamples=2_000, seed=0)
low, high = percentile_ci(f1s)
print(f"bootstrap: {len(f1s)} resamples, standard error {f1s.std(ddof=1):.3f}")
print(f"95% CI for F1: [{low:.3f}, {high:.3f}], width {high - low:.3f}")
Terminal
python ci.py
Expected output
F1 point estimate 0.605 (scikit-learn: 0.605)
one resample uses 632 distinct rows of 1,000
bootstrap: 2000 resamples, standard error 0.030
95% CI for F1: [0.544, 0.661], width 0.117

The hand-written F1 matches scikit-learn, and one resample uses 632 distinct rows, as predicted. The standard error, the standard deviation of the 2,000 bootstrap values, is 0.030, and the 95% interval is [0.544, 0.661]. Report it as "F1 0.605 (95% CI 0.544 to 0.661, percentile bootstrap, 2,000 resamples, n = 1,000)".

Read the interval carefully. It describes the noise from which rows ended up in the test set. It does not cover a different random seed for training, a different train split or a change in the data after deployment. And "95%" is a property of the procedure: built this way again and again, such intervals contain the true value about 95% of the time. Step 6 checks that claim.

04. Step 3: Check the effect of the seed and of B

The bootstrap is random, so its result depends on the seed and on how many resamples you draw. Run it with three seeds at three values of B.

Python · stability.py
"""Step 3: how the interval moves with the seed and the number of resamples."""
import numpy as np

from boot import bootstrap_f1, percentile_ci

data = np.load("preds.npz")
y_true, y_pred = data["y_true"][:1_000], data["y_pred"][:1_000]

for n_resamples in [200, 2_000, 10_000]:
    cells = []
    for seed in [0, 1, 2]:
        low, high = percentile_ci(bootstrap_f1(y_true, y_pred, n_resamples, seed))
        cells.append(f"[{low:.3f}, {high:.3f}]")
    print(f"B = {n_resamples:>6}: " + "  ".join(cells))
Terminal
python stability.py
Expected output
B =    200: [0.536, 0.661]  [0.545, 0.664]  [0.549, 0.667]
B =   2000: [0.544, 0.661]  [0.543, 0.663]  [0.546, 0.660]
B =  10000: [0.545, 0.661]  [0.544, 0.660]  [0.545, 0.660]

With 200 resamples the lower end moves between 0.536 and 0.549 from seed to seed; with 10,000 the three intervals agree within 0.001. The width stays close to 0.12 in every row. More resamples only remove the simulation noise of the bootstrap itself; they cannot make the interval narrower, because the width comes from the test set. Use at least 2,000 resamples for a 95% interval, more for a 99% one, fix the seed, and report it.

05. Step 4: Compare with scipy.stats.bootstrap

scipy.stats.bootstrap implements the same idea. Pass the labels and predictions as one tuple with paired=True, so SciPy draws one set of row numbers for both arrays. With vectorized=True, SciPy hands the statistic all resamples at once with an axis argument; the wrapper moves that axis to the end, where f1_from_labels expects it. The script asks for the percentile method and for BCa (bias-corrected and accelerated), SciPy's default, which adjusts the percentiles when the bootstrap distribution is skewed or off-centre.

Python · scipy_check.py
"""Step 4: the same interval from scipy.stats.bootstrap, percentile and BCa."""
import numpy as np
from scipy import stats

from boot import f1_from_labels

data = np.load("preds.npz")
y_true, y_pred = data["y_true"][:1_000], data["y_pred"][:1_000]


def f1_stat(t, p, axis=-1):  # scipy passes resampled arrays, resample axis last
    return f1_from_labels(np.moveaxis(t, axis, -1), np.moveaxis(p, axis, -1))


for method in ["percentile", "BCa"]:
    res = stats.bootstrap((y_true, y_pred), f1_stat, paired=True, vectorized=True,
                          n_resamples=2_000, method=method,
                          rng=np.random.default_rng(0))
    ci = res.confidence_interval
    print(f"scipy {method:<10} [{ci.low:.3f}, {ci.high:.3f}]  "
          f"standard error {res.standard_error:.3f}")
Terminal
python scipy_check.py
Expected output
scipy percentile [0.544, 0.661]  standard error 0.030
scipy BCa        [0.544, 0.661]  standard error 0.030

The percentile interval is identical to yours, because with these versions SciPy draws the same row numbers from a generator with the same seed. Do not rely on that across versions; agreement within the seed-to-seed noise of step 3 is the real check. BCa gives the same interval here because the 2,000 F1 values are nearly symmetric around the estimate. For metrics close to 0 or 1, or with few positives, the two differ, and BCa is usually the better choice; the SciPy documentation notes that the plain percentile method is rarely used in practice.

06. Step 5: See how the width depends on test-set size

Now use the first 250, 1,000 and 4,000 held-out rows as three test sets of different sizes.

Python · size.py
"""Step 5: interval width for test sets of 250, 1,000 and 4,000 rows."""
import numpy as np

from boot import bootstrap_f1, f1_from_labels, percentile_ci

data = np.load("preds.npz")
print(f"{'rows':>5} {'positives':>9} {'F1':>6} {'95% CI':>16} {'width':>6}")
for n in [250, 1_000, 4_000]:
    y_true, y_pred = data["y_true"][:n], data["y_pred"][:n]
    low, high = percentile_ci(bootstrap_f1(y_true, y_pred, 2_000, seed=0))
    print(f"{n:>5} {y_true.sum():>9} {f1_from_labels(y_true, y_pred):>6.3f} "
          f"  [{low:.3f}, {high:.3f}] {high - low:>6.3f}")
Terminal
python size.py
Expected output
 rows positives     F1           95% CI  width
  250        46  0.524   [0.394, 0.644]  0.249
 1000       208  0.605   [0.544, 0.661]  0.117
 4000       819  0.641   [0.613, 0.669]  0.056

Each time the test set grows four times, the width roughly halves: 0.249, 0.117, 0.056. Standard errors shrink with the square root of the sample size, so halving the width costs four times the data. For F1 the count that matters most is the number of positives (46, 208, 819), because F1 ignores the true negatives. Notice also that the 250-row estimate, 0.524, is 0.11 below the 4,000-row one, yet still inside its own wide interval: a small test set can be far off without anything looking wrong.

07. Step 6: Check that 95% means 95%

Treat the F1 on all 10,000 held-out rows as the target value. Draw 200 different 500-row test sets, build a 95% interval from each, and count how many intervals contain the target.

Python · coverage.py
"""Step 6: how often does a 95% interval from 500 rows contain the pool F1?"""
import numpy as np

from boot import bootstrap_f1, f1_from_labels, percentile_ci

data = np.load("preds.npz")
y_all, p_all = data["y_true"], data["y_pred"]
target = f1_from_labels(y_all, p_all)  # stand-in for the F1 on all future data

rng = np.random.default_rng(7)
hits = 0
for i in range(200):  # 200 different test sets of 500 rows each
    rows = rng.choice(len(y_all), size=500, replace=False)
    low, high = percentile_ci(bootstrap_f1(y_all[rows], p_all[rows], 1_000, seed=i))
    hits += low <= target <= high
print(f"pool F1 {target:.3f}")
print(f"intervals that contain it: {hits} of 200 ({hits / 200:.1%})")
Terminal
python coverage.py
Expected output
pool F1 0.635
intervals that contain it: 189 of 200 (94.5%)

189 of 200 intervals contain the target, 94.5%, close to the promised 95%. This is what the confidence level means: not a 95% chance for one particular interval, but the long-run hit rate of the method. With very small test sets or very few positives, percentile intervals tend to cover somewhat less than promised, which is one more reason to prefer BCa there.

08. Check your understanding

Practice check · 3 questions

Reading and debugging bootstrap intervals

Use what you built in this lab. Each question has one best answer.

Q1. A teammate writes this loop body for a bootstrap of F1. What goes wrong? idx_t = rng.integers(0, n, size=n) idx_p = rng.integers(0, n, size=n) scores.append(f1_score(y_true[idx_t], y_pred[idx_p]))
Q2. A 95% bootstrap interval for recall, from a test set with 120 positives, is 0.16 wide. Roughly how many positives would you need for an interval about 0.08 wide?
Q3. You report F1 0.81 with a 95% bootstrap interval of [0.77, 0.85]. A colleague retrains the same model with another random seed and gets 0.74 on the same test set. What is the best explanation?
Practice only: not graded, not saved, not evidence.

09. Apply it: stretch tasks

  1. The practice task. Load the predictions of your two classifiers and report each model's F1 with a 95% interval, once with your boot.py and once with scipy.stats.bootstrap and BCa.
  2. Another metric. Bootstrap ROC-AUC from predicted probabilities with roc_auc_score. Resamples that contain only one class have no AUC: count them and skip them.
  3. Batches. Rewrite bootstrap_f1 to draw 500 resamples at a time, so that B = 10,000 on 100,000 rows fits in a few hundred megabytes.
  4. Training noise. Retrain the model with five different seeds of train_test_split and compare the spread of their F1 values with the width of the bootstrap interval.

10. Review prompt

Without looking back:

  1. List the four steps of the percentile bootstrap. Why must the rows be drawn with replacement, and why with one index array?
  2. What changes when you raise the number of resamples, and what changes when you quadruple the test set?
  3. What does "95%" in a 95% confidence interval promise, and which sources of variation does this interval leave out?

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