Skip to content

Commit 9f4176b

Browse files
committed
fix(metrics): count true positives for bool inputs in get_confusion_matrix
get_confusion_matrix finds true positives with (y_pred + y) == 2. For bool tensors that sum is a logical OR, which is never 2, so bool masks such as pred > 0.5 lost every true positive: a perfect prediction scored sensitivity 0 and F1 0. Cast bool inputs to float before counting; float and integer inputs are unchanged. Assisted-by: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: tritsystem <gbranaa4@gmail.com>
1 parent 6aa4abf commit 9f4176b

2 files changed

Lines changed: 19 additions & 0 deletions

File tree

‎monai/metrics/confusion_matrix.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,13 @@ class range, ignored regions are inferred from spatial locations where all label
163163
ValueError: when `y_pred` and `y` have different shapes.
164164
"""
165165

166+
# The true positive/negative counts below test `y_pred + y`; for bool tensors that sum is a logical OR,
167+
# which never equals 2, so every true positive would be lost. Count on float values instead.
168+
if y_pred.dtype == torch.bool:
169+
y_pred = y_pred.float()
170+
if y.dtype == torch.bool:
171+
y = y.float()
172+
166173
original_y = y
167174
if not include_background:
168175
y_pred, y = ignore_background(y_pred=y_pred, y=y)

‎tests/metrics/test_compute_confusion_matrix.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,18 @@ def test_precision(self, input_data, expected_value):
289289
assert_allclose(result, expected_value, atol=1e-4, rtol=1e-4)
290290
np.testing.assert_equal(result.device, input_data["y_pred"].device)
291291

292+
def test_bool_inputs_match_float_inputs(self):
293+
"""Bool masks (e.g. ``pred > 0.5``) must give the same confusion matrix as their float equivalents."""
294+
generator = torch.Generator().manual_seed(0)
295+
y_pred = torch.rand(2, 3, 8, 8, generator=generator) > 0.5
296+
y = torch.rand(2, 3, 8, 8, generator=generator) > 0.5
297+
298+
for include_background in (True, False):
299+
expected = get_confusion_matrix(y_pred.float(), y.float(), include_background=include_background)
300+
result = get_confusion_matrix(y_pred, y, include_background=include_background)
301+
assert_allclose(result, expected, type_test=False)
302+
self.assertTrue(bool((result[..., 0] > 0).all())) # true positives are counted
303+
292304

293305
if __name__ == "__main__":
294306
unittest.main()

0 commit comments

Comments
 (0)