Skip to content

fix: return 0 for MCC when denominator is zero (align with sklearn)#3371

Open
jashshah999 wants to merge 1 commit intoLightning-AI:masterfrom
jashshah999:fix/mcc-zero-denominator
Open

fix: return 0 for MCC when denominator is zero (align with sklearn)#3371
jashshah999 wants to merge 1 commit intoLightning-AI:masterfrom
jashshah999:fix/mcc-zero-denominator

Conversation

@jashshah999
Copy link
Copy Markdown

@jashshah999 jashshah999 commented May 4, 2026

What does this PR do?

When any row or column of the confusion matrix sums to zero, the MCC denominator is zero and the metric is undefined. The previous code had complex special-casing with eps perturbations that produced inconsistent results (e.g. 1.0 when all predictions and targets are 0, while sklearn returns 0.0).

Replace with the sklearn convention: return 0 when denominator is zero.

Before (inconsistent with sklearn)

# All negatives: TorchMetrics=1.0, sklearn=0.0
preds = torch.zeros(10)
targets = torch.zeros(10)
BinaryMatthewsCorrCoef()(preds, targets)  # 1.0 (wrong)

After (matches sklearn)

BinaryMatthewsCorrCoef()(preds, targets)  # 0.0 (correct)

The fix removes ~25 lines of complex special-casing and replaces with a 1-line return.

Fixes #3355.


📚 Documentation preview 📚: https://torchmetrics--3371.org.readthedocs.build/en/3371/

When any row or column of the confusion matrix sums to zero, the MCC
denominator is zero and the metric is mathematically undefined. The
previous code had complex special-casing with eps perturbations that
produced values like 1.0 for all-TN cases, inconsistent with sklearn.

Replace with the sklearn convention: return 0 when denominator is
zero. This is simpler, consistent with the reference implementation,
and avoids producing misleading non-zero values for degenerate cases.

Fixes Lightning-AI#3355.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BinaryMatthewsCorrCoef behaves inconsistently when denominator = 0

1 participant