Macro F1 score calculation for binary classification not working as expected #2549
Replies: 2 comments
|
I think you are referring o tis reported issue/question #2320 |
|
Good catch. This is a known gotcha with binary classification and What's happening: you're using The fix — use from torchmetrics.classification import BinaryF1Score
# For binary segmentation, treat it as binary — not 2-class multiclass
f1 = BinaryF1Score()
# preds should be probabilities or logits for the positive class only
# target should be 0/1
f1(preds, target)If you truly need the macro F1 across both classes (background + foreground), use from torchmetrics.classification import MulticlassF1Score
f1_per_class = MulticlassF1Score(num_classes=2, average="none")
scores = f1_per_class(preds, target) # tensor([f1_class0, f1_class1])
macro_f1 = scores.mean() # this is the true macro averageWhy the built-in macro was wrong in your case: in torchmetrics Docs: BinaryF1Score |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Hi all, I am encountering a discrepancy in the macro F1 score calculation when using torchmetrics for binary classification. The macro F1 score calculated using torchmetrics is identical to the F1 score of class 1, rather than the average of the F1 scores for both classes. I am not sure if this is expected behavior or a potential issue. I was not able to calculate the F1 score for separate classes with BinaryF1Score, so I opted to use the multiclass setting.
I am encountering this error with a CNN for semantic segmentation on satellite images, but I get the same discrepancy with a mock dataset and model.
Here is the code:
I would expect to obtain a macro F1 score that is the average of the F1 scores of both classes with torchmetrics, but this is the result:
As you can see, the macro F1 score calculated with torchmetrics equals the F1 score of class 1.
Some details of my environment:
All reactions