From abcef76f39ca5e43f3b77781f938cc3873639c1c Mon Sep 17 00:00:00 2001 From: WatchTree-19 <119982314+WatchTree-19@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:47:53 +0000 Subject: [PATCH] McNemar: exact test for few disagreements, and no crash when there are none The comparison always used the chi-square approximation, which is unreliable when the two models disagree on few examples. In the module's own example they disagree on one example, and it reported p = 0.317; the exact binomial test gives p = 1.0. When the models never disagree, b + c = 0 and the statistic raised ZeroDivisionError. With fewer than 25 discordant pairs, p now comes from the exact binomial test on those pairs; above that the chi-square test is unchanged. With no discordant pairs the comparison returns stat 0 and p 1. p is returned as a plain float, so the docstring example also passes on numpy 2. --- comparisons/mcnemar/README.md | 4 ++-- comparisons/mcnemar/mcnemar.py | 21 +++++++++++++++++---- tests/test_mcnemar.py | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 6 deletions(-) create mode 100644 tests/test_mcnemar.py diff --git a/comparisons/mcnemar/README.md b/comparisons/mcnemar/README.md index 1ceaaee21..624270e01 100644 --- a/comparisons/mcnemar/README.md +++ b/comparisons/mcnemar/README.md @@ -53,7 +53,7 @@ The McNemar comparison outputs two things: `stat`: The McNemar statistic. -`p`: The p value. +`p`: The p value. When the models disagree on fewer than 25 examples, it comes from the exact binomial test on those examples, since the chi-square approximation is unreliable there. When they never disagree, `stat` is 0 and `p` is 1. ## Examples @@ -63,7 +63,7 @@ Example comparison: mcnemar = evaluate.load("mcnemar") results = mcnemar.compute(references=[1, 0, 1], predictions1=[1, 1, 1], predictions2=[1, 0, 1]) print(results) -{'stat': 1.0, 'p': 0.31731050786291115} +{'stat': 1.0, 'p': 1.0} ``` ## Limitations and bias diff --git a/comparisons/mcnemar/mcnemar.py b/comparisons/mcnemar/mcnemar.py index 86b85b5e3..540da63f5 100644 --- a/comparisons/mcnemar/mcnemar.py +++ b/comparisons/mcnemar/mcnemar.py @@ -14,7 +14,7 @@ """McNemar test for model comparison.""" import datasets -from scipy.stats import chi2 +from scipy.stats import binomtest, chi2 import evaluate @@ -37,12 +37,14 @@ Returns: stat (`float`): McNemar test score. p (`float`): The p value. Minimum possible value is 0. Maximum possible value is 1.0. A lower p value means a more significant difference. + With fewer than 25 examples on which the two models disagree, the chi-square approximation is unreliable, + so `p` comes from the exact binomial test on those examples. If the models never disagree, `stat` is 0 and `p` is 1. Examples: >>> mcnemar = evaluate.load("mcnemar") >>> results = mcnemar.compute(references=[1, 0, 1], predictions1=[1, 1, 1], predictions2=[1, 0, 1]) >>> print(results) - {'stat': 1.0, 'p': 0.31731050786291115} + {'stat': 1.0, 'p': 1.0} """ @@ -60,6 +62,11 @@ """ +# Below this many discordant pairs the chi-square approximation is unreliable +# and the exact binomial test is used. +_EXACT_BELOW = 25 + + @evaluate.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION) class McNemar(evaluate.Comparison): def _info(self): @@ -92,7 +99,13 @@ def _compute(self, predictions1, predictions2, references): # compute statistic b, c = tbl[0][1], tbl[1][0] + if b + c == 0: + # the models never disagree, so there is no evidence of a difference + return {"stat": 0.0, "p": 1.0} statistic = abs(b - c) ** 2 / (1.0 * (b + c)) - df = 1 - pvalue = chi2.sf(statistic, df) + if b + c < _EXACT_BELOW: + pvalue = float(binomtest(b, b + c, 0.5).pvalue) + else: + df = 1 + pvalue = float(chi2.sf(statistic, df)) return {"stat": statistic, "p": pvalue} diff --git a/tests/test_mcnemar.py b/tests/test_mcnemar.py new file mode 100644 index 000000000..dd3b16579 --- /dev/null +++ b/tests/test_mcnemar.py @@ -0,0 +1,34 @@ +import os + +import pytest + +import evaluate + + +@pytest.fixture(scope="module") +def mcnemar(): + return evaluate.load(os.path.join(os.path.dirname(__file__), "..", "comparisons", "mcnemar")) + + +def test_models_that_never_disagree(mcnemar): + results = mcnemar.compute(references=[1, 0, 1], predictions1=[1, 0, 0], predictions2=[1, 0, 0]) + assert results == {"stat": 0.0, "p": 1.0} + + +def test_few_discordant_pairs_use_the_exact_test(mcnemar): + # Model 1 is right on 3 examples model 2 gets wrong, and never the other way. + # The exact two-sided binomial p is 2 * 0.5**3 = 0.25; the chi-square + # approximation would give 0.083. + references = [1, 1, 1, 0, 0] + results = mcnemar.compute(references=references, predictions1=[1, 1, 1, 0, 0], predictions2=[0, 0, 0, 0, 0]) + assert results["stat"] == pytest.approx(3.0) + assert results["p"] == pytest.approx(0.25) + + +def test_many_discordant_pairs_keep_the_chi_square_test(mcnemar): + references = [1] * 40 + predictions1 = [1] * 30 + [0] * 10 + predictions2 = [0] * 30 + [1] * 10 + results = mcnemar.compute(references=references, predictions1=predictions1, predictions2=predictions2) + assert results["stat"] == pytest.approx(10.0) + assert results["p"] == pytest.approx(0.0015654022580025018)