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 · Worked example · 20 min · revision 2

Worked Example: Is Model B Really Better Than Model A?

Compare two classifiers scored on the same test rows: see why two overlapping confidence intervals mislead, run a paired bootstrap of the F1 difference and a paired permutation test, read an interval that includes zero, and turn the numbers into a switching decision.

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. The problem

Your team runs model A, a logistic regression that flags customer accounts likely to leave. A colleague has built model B: the same model with two extra features from a new usage-data feed. Keeping that feed running costs engineering time every month, so before anyone looked at results the team agreed on a rule: switch to B only if its F1 gain is real, meaning not explainable by test-set noise, and at least 0.01.

Both models were scored on the same 3,000 test rows. The colleague computed a 95% bootstrap interval for each model, saw that the two intervals overlap, and concluded that there is no evidence B is better. Your job is to check that conclusion and make the call.

The data is synthetic and seeded so you can reproduce every number. Tested with Python 3.12, NumPy 2.5 and scikit-learn 1.9; install with python -m pip install numpy scikit-learn and run the scripts in one folder in the order shown.

02. Step 1: Score both models on the same rows

The script trains both models on the same 5,000 rows, predicts the same 3,000 test rows and saves the labels and both sets of predictions. It also counts where the models agree, because that turns out to be the key to the whole comparison.

Python · models.py
"""Step 1: train the current model A and the candidate B, score both on one test set."""
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score

X, y = make_classification(n_samples=8_000, n_features=10, n_informative=5,
                           weights=[0.8], class_sep=1.5, flip_y=0.02,
                           random_state=1)
X_train, y_train, X_test, y_test = X[:5_000], y[:5_000], X[5_000:], y[5_000:]

old = slice(0, 8)  # model A uses the 8 columns we already have
model_a = LogisticRegression(max_iter=1_000).fit(X_train[:, old], y_train)
model_b = LogisticRegression(max_iter=1_000).fit(X_train, y_train)  # all 10
pred_a, pred_b = model_a.predict(X_test[:, old]), model_b.predict(X_test)
np.savez("preds_ab.npz", y_true=y_test, pred_a=pred_a, pred_b=pred_b)

print(f"test rows {len(y_test)}, positives {y_test.sum()}")
print(f"F1  A {f1_score(y_test, pred_a):.3f}   B {f1_score(y_test, pred_b):.3f}")
right_a, right_b = pred_a == y_test, pred_b == y_test
print(f"rows where A and B predict the same label: {(pred_a == pred_b).sum()}")
print(f"only A right: {(right_a & ~right_b).sum()}   "
      f"only B right: {(right_b & ~right_a).sum()}")
Expected output
test rows 3000, positives 597
F1  A 0.847   B 0.864
rows where A and B predict the same label: 2961
only A right: 13   only B right: 26

B leads by 0.017 F1. The models predict the same label on 2,961 of 3,000 rows. On the 39 rows where they disagree, B is right 26 times and A 13 times. Every other row is either easy for both or hard for both, so the two F1 scores share most of their luck.

03. Step 2: Reproduce the separate intervals

First reproduce the colleague's analysis. pairboot.py holds three small helpers: F1 for many resamples at once, a matrix of row numbers drawn with replacement, and the 2.5th and 97.5th percentiles. separate.py then bootstraps each model on its own, with its own random row draws, as two independent reports would.

Python · pairboot.py
"""F1 for many resamples at once, and a bootstrap that can share row indices."""
import numpy as np


def f1_rows(y_true, y_pred):
    """F1 along the last axis: one value per resample row."""
    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)
    return 2 * tp / np.maximum(2 * tp + fp + fn, 1)


def resample_index(n, n_resamples=5_000, seed=0):
    rng = np.random.default_rng(seed)
    return rng.integers(0, n, size=(n_resamples, n))  # rows drawn with replacement


def ci95(values):
    return np.percentile(values, [2.5, 97.5])
Python · separate.py
"""Step 2: one 95% interval per model, each from its own resamples."""
import numpy as np

from pairboot import ci95, f1_rows, resample_index

d = np.load("preds_ab.npz")
y = d["y_true"]
for name, seed in [("a", 1), ("b", 2)]:  # separate draws, as two reports would do
    pred = d[f"pred_{name}"]
    idx = resample_index(len(y), seed=seed)
    low, high = ci95(f1_rows(y[idx], pred[idx]))
    print(f"model {name.upper()}: F1 {f1_rows(y, pred):.3f}  "
          f"95% CI [{low:.3f}, {high:.3f}]")
Expected output
model A: F1 0.847  95% CI [0.823, 0.870]
model B: F1 0.864  95% CI [0.842, 0.885]

The intervals overlap from 0.842 to 0.870, so the colleague's observation is correct. The conclusion is not. Checking whether two intervals overlap answers a question about two independent estimates, and these are not independent: both F1 values come from the same rows. When a resample happens to contain many easy rows, both scores rise together. The uncertainty of the difference follows

  • Var(B − A) = Var(A) + Var(B) − 2 Cov(A, B)

where Cov is the covariance, which is large and positive when two quantities rise and fall together. The overlap check ignores that last term. Even for truly independent estimates, two 95% intervals can overlap while the difference is significant at the 5% level, so overlap is a poor test in either case.

04. Step 3: Bootstrap the difference on paired rows

A paired bootstrap draws one set of row numbers per resample and scores both models on those rows. Each resample then gives one difference F1(B) − F1(A), and the percentiles of the differences form the interval. The script also measures how strongly the two scores move together.

Python · paired.py
"""Step 3: a paired bootstrap of F1(B) - F1(A) on the same resampled rows."""
import numpy as np

from pairboot import ci95, f1_rows, resample_index

d = np.load("preds_ab.npz")
y, pred_a, pred_b = d["y_true"], d["pred_a"], d["pred_b"]

idx = resample_index(len(y), seed=0)  # ONE set of row draws, used for both models
f1_a, f1_b = f1_rows(y[idx], pred_a[idx]), f1_rows(y[idx], pred_b[idx])
diff = f1_b - f1_a

print(f"sd of F1 A {f1_a.std():.4f}   sd of F1 B {f1_b.std():.4f}")
print(f"correlation of A and B across resamples {np.corrcoef(f1_a, f1_b)[0, 1]:.3f}")
print(f"sd of the difference: paired {diff.std():.4f}   "
      f"if independent {np.hypot(f1_a.std(), f1_b.std()):.4f}")
low, high = ci95(diff)
print(f"F1(B) - F1(A) = {f1_rows(y, pred_b) - f1_rows(y, pred_a):+.3f}  "
      f"95% CI [{low:+.3f}, {high:+.3f}]")
print(f"resamples where B is not better: {(diff <= 0).mean():.1%}")
print(f"resamples with a gain below 0.01: {(diff < 0.01).mean():.1%}")
Expected output
sd of F1 A 0.0117   sd of F1 B 0.0110
correlation of A and B across resamples 0.853
sd of the difference: paired 0.0062   if independent 0.0160
F1(B) - F1(A) = +0.017  95% CI [+0.005, +0.029]
resamples where B is not better: 0.2%
resamples with a gain below 0.01: 12.1%

Across resamples the two F1 scores have a correlation of 0.853. Because of that shared luck, the standard deviation of the difference is 0.0062, while treating the models as independent would suggest 0.0160, more than twice as much. The paired 95% interval for the gain is [+0.005, +0.029]. It lies entirely above zero: on these rows, B's advantage is larger than test-set noise can explain. Only 0.2% of resamples show B not ahead.

05. Step 4: Test the null hypothesis, with enough rows and with too few

The same question can be put as a hypothesis test. The null hypothesis (H0) is that A and B are equally good, so any observed gap is noise. The p-value is the probability, if H0 were true, of a gap at least as large as the one observed. A small p-value means the data would be surprising under H0. You compare it with a significance level α (alpha) chosen in advance, usually 0.05.

A paired permutation test builds the world of H0 directly. If the models were equally good, the labels "A" and "B" on each row would be interchangeable, so the script swaps the two predictions on each row with probability one half, recomputes the gap 10,000 times, and counts how often a shuffled gap is at least as large in size as the real one. It runs the bootstrap and the test twice: on all 3,000 rows, and on only the first 400, as if the test set had been small.

Python · perm_test.py
"""Step 4: a paired permutation test, on all 3,000 rows and on the first 400 only."""
import numpy as np

from pairboot import ci95, f1_rows, resample_index

d = {k: v.astype(np.int8) for k, v in np.load("preds_ab.npz").items()}  # less memory


def paired_test(y, pred_a, pred_b, n_perm=10_000, seed=0):
    observed = f1_rows(y, pred_b) - f1_rows(y, pred_a)
    rng = np.random.default_rng(seed)
    swap = rng.random((n_perm, len(y))) < 0.5  # under H0, A and B are exchangeable
    perm_a = np.where(swap, pred_b, pred_a)
    perm_b = np.where(swap, pred_a, pred_b)
    null = f1_rows(y, perm_b) - f1_rows(y, perm_a)
    p_value = (np.sum(np.abs(null) >= abs(observed)) + 1) / (n_perm + 1)
    return observed, p_value


for n in [3_000, 400]:
    y, a, b = d["y_true"][:n], d["pred_a"][:n], d["pred_b"][:n]
    idx = resample_index(n, seed=0)
    low, high = ci95(f1_rows(y[idx], b[idx]) - f1_rows(y[idx], a[idx]))
    observed, p_value = paired_test(y, a, b)
    print(f"{n:>5} rows: difference {observed:+.3f}  95% CI [{low:+.3f}, {high:+.3f}]  "
          f"p = {p_value:.4f}")
Expected output
 3000 rows: difference +0.017  95% CI [+0.005, +0.029]  p = 0.0052
  400 rows: difference +0.019  95% CI [-0.011, +0.055]  p = 0.2480

With 3,000 rows, p = 0.0052: if the models were equally good, a gap this large would appear in about 1 shuffle in 200. That is below α = 0.05, so you reject H0, in agreement with the interval. SciPy's permutation_test with permutation_type='samples' runs the same test; on these predictions it also returned p = 0.0052 in our run.

With 400 rows the gap is about the same (+0.019), but the interval is [−0.011, +0.055] and p = 0.248. An interval that contains zero means that "no difference" is consistent with the data. It does not show that the models are equal; the interval also allows a gain of 0.05. It means this test set is too small to tell. The fix is more labelled rows, not a different statistic. A 95% paired interval that excludes zero and a two-sided p-value below 0.05 usually agree, as they do here, because they come from the same paired comparison.

06. Step 5: Make the decision

Now apply the rule the team set before seeing the data. Is the gain real? Yes: the paired interval [+0.005, +0.029] excludes zero and p = 0.005. Is it at least 0.01? The estimate, +0.017, clears the bar, but 12.1% of resamples show a gain below 0.01, so a smaller gain is possible. That is a statistical answer (a gain exists) and a practical one (it probably, not certainly, meets the bar); both matter.

The written recommendation:

  • On the same 3,000 test rows, model B has F1 0.864 and model A 0.847; the paired 95% bootstrap interval for the gain is +0.005 to +0.029 (p = 0.005, paired permutation test), so the improvement is not test-set noise.
  • The estimated gain of 0.017 is above the 0.01 we agreed the feed must earn, although gains slightly below 0.01 remain plausible.
  • We recommend switching to B, and re-checking its F1 on the first month of live labels, because this interval only covers test-set sampling, not drift in the data after launch.

07. Check your understanding

Practice check · 3 questions

Comparing models fairly

Apply the paired reasoning to new numbers. Each question has one best answer.

Q1. On the same 2,000 rows, the bootstrap standard deviation of F1 is 0.012 for model A and 0.012 for model B, and the paired bootstrap values have a correlation of 0.75. About how large is the standard deviation of F1(B) − F1(A)?
Q2. A paired 95% interval for F1(B) − F1(A) is [+0.002, +0.006]. Moving to B requires a re-certification that the team agreed is worth it only for a gain of at least 0.02. What do you recommend?
Q3. You compare 20 candidate feature sets against the current model with a paired test at α = 0.05. Nineteen give p above 0.2, and one gives p = 0.04. What is the soundest reading?
Practice only: not graded, not saved, not evidence.

08. Apply it

Complete the practice task for this skill with your own two classifiers:

  1. Save the true labels and both models' predictions for the same test rows.
  2. Report each model's F1 with a 95% bootstrap interval, then the paired 95% interval and the permutation p-value for the difference.
  3. Before you look at the result, write down the smallest gain that would justify switching. Then write a three-sentence recommendation like the one in step 5: the evidence, the comparison with your margin, and the decision with what to monitor.

09. Review prompt

Without looking back:

  1. Why can two overlapping intervals hide a clear difference between two models scored on the same rows?
  2. What exactly is shared between the two models in a paired bootstrap, and what does the percentile interval describe?
  3. State the null hypothesis of the paired permutation test and what its p-value measures.
  4. How do you read an interval for the difference that contains zero, and how do you combine a significant gain with a practical margin?

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