Skip to content

Commit ba59ee7

Browse files
committed
fix(metrics): count true positives for bool inputs in get_f_beta_score
get_f_beta_score has the same (y_pred + y) == 2 true-positive test as get_confusion_matrix; both lost their float casts in #7187. For bool masks the sum is a logical OR, so every true positive was dropped and a perfect prediction scored F-beta 0. Cast bool inputs to float before counting, as in the previous commit; float and integer inputs are unchanged. Assisted-by: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: tritsystem <gbranaa4@gmail.com>
1 parent 9f4176b commit ba59ee7

2 files changed

Lines changed: 24 additions & 0 deletions

File tree

‎monai/metrics/f_beta_score.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,13 @@ def aggregate(
6161

6262

6363
def get_f_beta_score(y_pred: torch.Tensor, y: torch.Tensor, include_background: bool = True) -> torch.Tensor:
64+
# The true positive/negative counts below test `y_pred + y`; for bool tensors that sum is a logical OR,
65+
# which never equals 2, so every true positive would be lost. Count on float values instead.
66+
if y_pred.dtype == torch.bool:
67+
y_pred = y_pred.float()
68+
if y.dtype == torch.bool:
69+
y = y.float()
70+
6471
if not include_background:
6572
y_pred, y = ignore_background(y_pred=y_pred, y=y)
6673

‎tests/metrics/test_compute_f_beta.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
from parameterized import parameterized
1919

2020
from monai.metrics import FBetaScore
21+
from monai.metrics.f_beta_score import get_f_beta_score
2122
from tests.test_utils import assert_allclose
2223

2324
_device = "cuda:0" if torch.cuda.is_available() else "cpu"
@@ -75,6 +76,22 @@ def test_prediction_and_result_have_different_shape(self):
7576
with self.assertRaises(ValueError):
7677
metric(y_pred=torch.Tensor([[1, 1, 1], [1, 1, 1]]), y=torch.Tensor([1, 1, 1]))
7778

79+
def test_bool_inputs_match_float_inputs(self):
80+
"""Bool masks (e.g. ``pred > 0.5``) must give the same counts and score as their float equivalents."""
81+
generator = torch.Generator().manual_seed(0)
82+
y_pred = torch.rand(2, 3, 8, 8, generator=generator) > 0.5
83+
y = torch.rand(2, 3, 8, 8, generator=generator) > 0.5
84+
85+
for include_background in (True, False):
86+
expected = get_f_beta_score(y_pred.float(), y.float(), include_background=include_background)
87+
result = get_f_beta_score(y_pred, y, include_background=include_background)
88+
assert_allclose(result, expected, type_test=False)
89+
self.assertTrue(bool((result[..., 0] > 0).all())) # true positives are counted
90+
91+
metric = FBetaScore()
92+
metric(y_pred=y, y=y)
93+
assert_allclose(metric.aggregate()[0], torch.Tensor([1.0]), atol=1e-7, rtol=1e-7)
94+
7895

7996
if __name__ == "__main__":
8097
unittest.main()

0 commit comments

Comments
 (0)