McNemar and Paired Permutation Tests for Comparing Two Classifiers

Quick Overview

Implement McNemar's test, in exact and chi-square form, and a paired permutation test to compare two classifiers scored on the same samples. It tests why only discordant pairs carry information, continuity corrections, Monte Carlo p-values and reproducible random draws.

McNemar and Paired Permutation Tests for Comparing Two Classifiers

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Given 1-D arrays `y_true`, `pred_a` and `pred_b` (any hashable labels), implement `contingency_table`, `mcnemar_test` and `paired_permutation_test` to compare two classifiers on the same samples. Each must follow the exact conventions below. Scalars are returned as Python `float`. Conventions: ```python ca, cb = pred_a == y_true, pred_b == y_true # contingency_table -> int64 array, shape (2, 2) [[sum(ca & cb), sum(ca & ~cb)], [sum(~ca & cb), sum(~ca & ~cb)]] # mcnemar_test(y_true, pred_a, pred_b, exact=False, correction=True) # b = table[0,1], c = table[1,0], n = b + c n == 0 -> (0.0, 1.0) exact=True -> stat = min(b, c), p = min(1, 2 * binom.cdf(stat, n, 0.5)) else -> d = |b - c|, minus 1 (floored at 0) if correction stat = d**2 / n, p = chi2.sf(stat, df=1) # paired_permutation_test(y_true, pred_a, pred_b, n_permutations, rng) d = ca.astype(int) - cb.astype(int) swaps = rng.integers(0, 2, size=(n_permutations, len(d))) # single draw t_perm = (1 - 2 * swaps) @ d p = (count(|t_perm| >= |d.sum()|) + 1) / (n_permutations + 1) return (d.sum() / len(d), p) ``` Example: ```python y = np.ones(12, dtype=int) pred_a = np.r_[np.ones(10, dtype=int), np.zeros(2, dtype=int)] pred_b = 1 - pred_a contingency_table(y, pred_a, pred_b) # [[0, 10], [2, 0]], so b = 10, c = 2 mcnemar_test(y, pred_a, pred_b) # (49/12 ≈ 4.0833, chi2.sf(49/12, 1) ≈ 0.0433) mcnemar_test(y, pred_a, pred_b, correction=False) # (64/12 ≈ 5.3333, chi2.sf(64/12, 1) ≈ 0.0209) y = np.ones(6, dtype=int) pred_a = np.array([1, 0, 0, 0, 0, 0]) pred_b = 1 - pred_a # b = 1, c = 5 mcnemar_test(y, pred_a, pred_b, exact=True) # (1.0, 14/64 = 0.21875) paired_permutation_test(y, pred_a, pred_a, 99, np.random.default_rng(0)) # (0.0, 1.0) ``` In the last call both models make the same predictions, so every entry of `d` is 0, every permuted sum ties the observed sum of 0, and the p-value is `(99 + 1) / (99 + 1)`. ```hint Where the information is Swap A's and B's predictions on one example and see which cells of the 2x2 table can change. ``` ```hint Pinning the stream Run every check before calling `rng.integers`, and draw exactly the shape in the conventions. Also check what `~` does to your correctness arrays if their dtype is not `bool`. ``` ### Constraints & Assumptions - Non-1-D, empty or length-mismatched inputs raise `ValueError` (all three functions). - `n_permutations < 1` raises `ValueError`. - `rng` is a `np.random.Generator`. Results must match the single `rng.integers` call above exactly. - `numpy` and `scipy.stats` are available. ### What a Strong Answer Covers - Why both tests use only the discordant cells, and which of them is `b` and which is `c` - The exact and chi-square McNemar branches, including the continuity correction, the case with no discordant pairs and the cap at 1 - Why random sign flips give the null distribution of the permutation test, and the +1 in its p-value - Matching the pinned random draw exactly, with validation that runs before it - Time and memory cost of the permutation matrix ### Follow-up Questions - When would you prefer the exact McNemar test over the chi-square version? - Why add 1 to numerator and denominator of the permutation p-value? - How would you extend this to compare a metric like F1 instead of accuracy?

Overview: Implement McNemar's test, in exact and chi-square form, and a paired permutation test to compare two classifiers scored on the same samples. It tests why only discordant pairs carry information, continuity corrections, Monte Carlo p-values and reproducible random draws.

General logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Given 1-D arrays y_true, pred_a and pred_b (any hashable labels), implement contingency_table, mcnemar_test and paired_permutation_test to compare two classifiers on the same samples. Each must follow the exact conventions below. Scalars are returned as Python float.

Conventions:

ca, cb = pred_a == y_true, pred_b == y_true

# contingency_table -> int64 array, shape (2, 2)
[[sum(ca & cb),  sum(ca & ~cb)],
 [sum(~ca & cb), sum(~ca & ~cb)]]

# mcnemar_test(y_true, pred_a, pred_b, exact=False, correction=True)
# b = table[0,1], c = table[1,0], n = b + c
n == 0                -> (0.0, 1.0)
exact=True            -> stat = min(b, c), p = min(1, 2 * binom.cdf(stat, n, 0.5))
else                  -> d = |b - c|, minus 1 (floored at 0) if correction
                         stat = d**2 / n, p = chi2.sf(stat, df=1)

# paired_permutation_test(y_true, pred_a, pred_b, n_permutations, rng)
d = ca.astype(int) - cb.astype(int)
swaps = rng.integers(0, 2, size=(n_permutations, len(d)))   # single draw
t_perm = (1 - 2 * swaps) @ d
p = (count(|t_perm| >= |d.sum()|) + 1) / (n_permutations + 1)
return (d.sum() / len(d), p)

Example:

y = np.ones(12, dtype=int)
pred_a = np.r_[np.ones(10, dtype=int), np.zeros(2, dtype=int)]
pred_b = 1 - pred_a
contingency_table(y, pred_a, pred_b)                # [[0, 10], [2, 0]], so b = 10, c = 2
mcnemar_test(y, pred_a, pred_b)                     # (49/12 ≈ 4.0833, chi2.sf(49/12, 1) ≈ 0.0433)
mcnemar_test(y, pred_a, pred_b, correction=False)   # (64/12 ≈ 5.3333, chi2.sf(64/12, 1) ≈ 0.0209)

y = np.ones(6, dtype=int)
pred_a = np.array([1, 0, 0, 0, 0, 0])
pred_b = 1 - pred_a                                 # b = 1, c = 5
mcnemar_test(y, pred_a, pred_b, exact=True)         # (1.0, 14/64 = 0.21875)

paired_permutation_test(y, pred_a, pred_a, 99, np.random.default_rng(0))   # (0.0, 1.0)

In the last call both models make the same predictions, so every entry of d is 0, every permuted sum ties the observed sum of 0, and the p-value is (99 + 1) / (99 + 1).

Constraints & Assumptions

  • Non-1-D, empty or length-mismatched inputs raise ValueError (all three functions).
  • n_permutations < 1 raises ValueError .
  • rng is a np.random.Generator . Results must match the single rng.integers call above exactly.
  • numpy and scipy.stats are available.

What a Strong Answer Covers Guidance

  • Why both tests use only the discordant cells, and which of them is b and which is c
  • The exact and chi-square McNemar branches, including the continuity correction, the case with no discordant pairs and the cap at 1
  • Why random sign flips give the null distribution of the permutation test, and the +1 in its p-value
  • Matching the pinned random draw exactly, with validation that runs before it
  • Time and memory cost of the permutation matrix

Follow-up Questions Guidance

  • When would you prefer the exact McNemar test over the chi-square version?
  • Why add 1 to numerator and denominator of the permutation p-value?
  • How would you extend this to compare a metric like F1 instead of accuracy?