-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
fix: validate tensor shapes in get_stats for multiclass mode #1284
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lapertor
wants to merge
3
commits into
qubvel-org:main
Choose a base branch
from
lapertor:fix/get-stats-multiclass-shape-validation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -139,11 +139,27 @@ def get_stats( | |||||
| ) | ||||||
|
|
||||||
| if output.shape != target.shape: | ||||||
| # Check if user accidentally passed a one-hot / logits tensor in multiclass mode | ||||||
| if mode == "multiclass" and output.ndim == target.ndim + 1: | ||||||
| raise ValueError( | ||||||
| f"In 'multiclass' mode, ``output`` should contain class indices of shape " | ||||||
| f"(N, ...), but got shape {output.shape}. " | ||||||
| f"It looks like you passed a one-hot or logits tensor. " | ||||||
| f"Please convert it first with ``output.argmax(dim=1)``." | ||||||
| ) | ||||||
| if mode == "multiclass" and target.ndim == output.ndim + 1: | ||||||
| raise ValueError( | ||||||
| f"In 'multiclass' mode, ``target`` should contain class indices of shape " | ||||||
| f"(N, ...), but got shape {target.shape}. " | ||||||
| f"It looks like you passed a one-hot tensor. " | ||||||
| f"Please convert it first with ``target.argmax(dim=1)``." | ||||||
| ) | ||||||
| raise ValueError( | ||||||
| "Dimensions should match, but ``output`` shape is not equal to ``target`` " | ||||||
| + f"shape, {output.shape} != {target.shape}" | ||||||
| ) | ||||||
|
|
||||||
|
|
||||||
| if mode != "multiclass" and ignore_index is not None: | ||||||
| raise ValueError( | ||||||
| f"``ignore_index`` parameter is not supported for '{mode}' mode" | ||||||
|
|
@@ -163,6 +179,21 @@ def get_stats( | |||||
| ) | ||||||
|
|
||||||
| if mode == "multiclass": | ||||||
| if output.ndim > 1 and output.shape[1] == num_classes and output.ndim >= 3: | ||||||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
| raise ValueError( | ||||||
| f"In 'multiclass' mode, ``output`` should contain class indices of shape " | ||||||
| f"(N, H, W) or (N,), but got shape {tuple(output.shape)}. " | ||||||
| f"It looks like you passed a one-hot or logits tensor of shape (N, C, ...). " | ||||||
| f"For that use case, please use mode='multilabel' instead, " | ||||||
| f"or convert your tensor with ``output.argmax(dim=1)`` first." | ||||||
| ) | ||||||
| if target.ndim > 1 and target.shape[1] == num_classes and target.ndim >= 3: | ||||||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
| raise ValueError( | ||||||
| f"In 'multiclass' mode, ``target`` should contain class indices of shape " | ||||||
| f"(N, H, W) or (N,), but got shape {tuple(target.shape)}. " | ||||||
| f"It looks like you passed a one-hot encoded tensor of shape (N, C, ...). " | ||||||
| f"Convert it with ``target.argmax(dim=1)`` first." | ||||||
| ) | ||||||
| tp, fp, fn, tn = _get_stats_multiclass( | ||||||
| output, target, num_classes, ignore_index | ||||||
| ) | ||||||
|
|
||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| import pytest | ||
| import torch | ||
| import segmentation_models_pytorch as smp | ||
|
|
||
|
|
||
| class TestGetStatsMulticlass: | ||
| """Tests for get_stats in multiclass mode.""" | ||
|
|
||
| def test_correct_input(self): | ||
| """Class index tensors of shape (N, ...) should work correctly.""" | ||
| tp, fp, fn, tn = smp.metrics.get_stats( | ||
| output=torch.tensor([[0, 1, 2, 1]]), | ||
| target=torch.tensor([[0, 1, 2, 2]]), | ||
| mode="multiclass", | ||
| num_classes=3, | ||
| ) | ||
| assert tp.shape == (1, 3) | ||
| assert fp.tolist() == [[0, 1, 0]] | ||
| assert fn.tolist() == [[0, 0, 1]] | ||
|
|
||
| def test_onehot_output_raises(self): | ||
| """Passing a one-hot encoded output (N, C, ...) should raise ValueError with hint.""" | ||
| with pytest.raises(ValueError, match="output.argmax"): | ||
| smp.metrics.get_stats( | ||
| output=torch.tensor([[[1, 0, 0], [0, 1, 0], [0, 0, 1]]]), | ||
| target=torch.tensor([[0, 1, 2]]), | ||
| mode="multiclass", | ||
| num_classes=3, | ||
| ) | ||
|
|
||
| def test_onehot_target_raises(self): | ||
| """Passing a one-hot encoded target (N, C, ...) should raise ValueError with hint.""" | ||
| with pytest.raises(ValueError, match="target.argmax"): | ||
| smp.metrics.get_stats( | ||
| output=torch.tensor([[0, 1, 2]]), | ||
| target=torch.tensor([[[1, 0, 0], [0, 1, 0], [0, 0, 1]]]), | ||
| mode="multiclass", | ||
| num_classes=3, | ||
| ) | ||
|
|
||
|
|
||
| def test_argmax_fix_gives_perfect_iou(self): | ||
| """Correcting a one-hot tensor with argmax(dim=1) should yield IoU=1.0.""" | ||
| output_onehot = torch.tensor([[[1, 0, 0], [0, 1, 0], [0, 0, 1]]]) | ||
| target_onehot = torch.tensor([[[1, 0, 0], [0, 1, 0], [0, 0, 1]]]) | ||
|
|
||
| tp, fp, fn, tn = smp.metrics.get_stats( | ||
| output=output_onehot.argmax(dim=1), | ||
| target=target_onehot.argmax(dim=1), | ||
| mode="multiclass", | ||
| num_classes=3, | ||
| ) | ||
| iou = smp.metrics.iou_score(tp, fp, fn, tn, reduction="macro") | ||
| assert iou.item() == pytest.approx(1.0) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
not super robust, what if both are passed as (N, C, H, W), but better than nothing 👍