Lightning-AI / Lightning-AI/torchmetrics

`spectral_angle_mapper` NaNs even with one zero pixel

Open
#3,322 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug / fix help wanted
Dominant language
Python
Stars
2.5k
Forks
526
Avg merge
6d 11h
Merged PRs (30d)
5

Description

## 🐛 Bug

`spectral_angle_mapper` (and probably the class interface too) gives a NaN even with one zero pixel in the image.

The SAM score is the acos of the channel dot product, and requires normalising the dot by the input norms.

However in torchmetrics, the convention is to compute the metric over the whole image, and only reduce over spatial dims after. Therefore, even if there's a single pixel in the inputs that's zero, a pixel in the unreduced norm will be zero -> NaNs when one reduces.

This isn't good behaviour, because one only expects SAM to be NaN when an input is all-zeros, not just one zero pixel.

Solution could either be a) reduce ignoring NaNs; b) add an eps; c) `return reduce(unnormalised_score) / reduce(preds_norm * target_norm)`

### To Reproduce

```python
from torchmetrics.functional.image import spectral_angle_mapper
a, b = torch.ones(2, 1, 3, 8, 8)
a[:, :, 5, 3] = 0
spectral_angle_mapper(a, b)

out: tensor(nan)
```

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start from the spectral_angle_mapper functional entry point and inspect the class interface mentioned in the report. Run the provided tensor reproduction first; done means a single zero pixel no longer makes the reduced score NaN, while an all-zero input still produces NaN.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, pytorch
Domain
machine-learning
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.