Compare two classifiers on the same test set with McNemar's test

Why it matters McNemar's test is the right way to compare two models on one shared test set, for example a new classifier against production on the same labelled tickets.

When two models are scored on the same examples, their errors are paired. McNemar's test looks only at the examples where they disagree.

Write mcnemar_test(y_true, pred_a, pred_b). Let b be the number of examples model A gets right and model B gets wrong, and c the number B gets right and A gets wrong. With continuity correction, stat = (|b - c| - 1)^2 / (b + c), and stat = 0.0 if b + c is 0. The p-value for a chi-square with 1 degree of freedom is math.erfc(sqrt(stat / 2)). Return (b, c, stat, p) with b and c as ints.

Signaturedef mcnemar_test(y_true, pred_a, pred_b)

Example

y_true [1, 0, 1, 1, 0, 1, 0, 1, 1, 0], pred_a [1, 0, 1, 1, 0, 1, 0, 1, 0, 0], pred_b [0, 0, 0, 1, 1, 0, 0, 0, 1, 0] gives (5, 1, 1.5, 0.220671): A alone is right 5 times, B alone once.

Understand the idea

Model A gets 90% and model B gets 85% on the same 200 test examples. Is A really better? The examples are shared, so most of them are easy for both models and tell us nothing. What matters are the disagreements.

McNemar's test counts b = examples only A gets right and c = examples only B gets right. If the models were equally good, each disagreement would be a coin flip, so b and c should be close.

Worked example: suppose b = 6 and c = 1. stat = (|6 - 1| - 1)^2 / 7 = 16 / 7 = 2.29. The chi-square tail with 1 degree of freedom gives p about 0.13, so seven disagreements are not yet enough evidence, even though A won 6 of them.

Rule: stat = (|b - c| - 1)^2 / (b + c), p = erfc(sqrt(stat / 2)).

The -1 is a continuity correction for small counts. For large b + c it hardly matters. Use this test whenever two models are scored on the same items.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplemcnemar_test([1, 0, 1, 1, 0, 1, 0, 1, 1, 0], [1, 0, 1, 1, 0, 1, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0, 1, 0])
  • Sample 2: no disagreementmcnemar_test([1, 0, 1], [1, 0, 0], [1, 0, 0])
  • Test 3: strong winnermcnemar_test([1] * 20, [1] * 18 + [0, 0], [0] * 10 + [1] * 10)
  • Test 4: balancedmcnemar_test([0, 1, 0, 1, 2, 2], [0, 1, 1, 0, 2, 0], [1, 0, 0, 1, 2, 2])