NaN values not handled by regression trainers
Description
As title. Pretty simple to address per trainer but perhaps this should be handled in the RegressionMixin? Example fix below:
class RegressionMixin(LightningModule):
def regression_loss(self, y_hat: Tensor, y: Tensor) -> Tensor:
"""Compute regression loss, optionally ignoring NaN targets."""
if self.hparams.get('ignore_nan', False):
valid = torch.isfinite(y)
if not valid.any():
return y_hat.sum() * 0.0
y_hat = y_hat[valid]
y = y[valid]
loss: Tensor = self.criterion(y_hat, y)
return loss
def regression_metrics(self, y_hat: Tensor, y: Tensor, stage: str) -> None:
"""Update regression metrics, optionally ignoring NaN targets."""
if self.hparams.get('ignore_nan', False):
valid = torch.isfinite(y)
if not valid.any():
return
y_hat = y_hat[valid]
y = y[valid]
metrics = getattr(self, f'{stage}_metrics')
metrics(y_hat, y)
This uses a new ignore_nan param but would we want this applied automatically?
Steps to reproduce
NA
Version
main
Can we instead convert NaNs to numbers and then use ignore_index? Most models fail when using NaNs because any number multiplied by or added to a NaN becomes a NaN. If a single pixel in your output mask is NaN, if you don't properly ignore it in the loss function, every parameter in the backpropagation and model eventually becomes NaN.
The regressions losses/metrics don't accept ignore_index - we need to handle nans before passing
I wonder if PyTorch would accept a PR for this...
I did a search and didn't find any issues or PRs related to nan handling for regression. Based on what I read, handling outside the losses is the canonical approach
Hi! I'd like to work on this issue if it's still available.
I've been looking through the current implementation and noticed that the regression loss and metrics are currently computed directly in the regression task implementations rather than through the helper methods shown in the issue description. My plan is to first reproduce the NaN behavior, add a regression test covering it, and then propose a fix with corresponding tests. Please let me know if anyone is already working on this or if you have a preferred implementation approach.
I'm thinking about adding wrappers for torchmetrics to torchgeo.losses. In particular, I need a wrapper that applies latitude scaling for global metric computation. I could imagine a wrapper for NaN handling ending up in the same file. NaN handling isn't really specific to geospatial though, so long-term it would be nice to upstream that somewhere.