Skip to content
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

rmspe: add epsilon to avoid division by zero #2139

Merged
merged 4 commits into from
Jun 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions ludwig/utils/loss_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,15 @@


def rmspe_loss(targets: torch.Tensor, predictions: torch.Tensor) -> torch.Tensor:
"""Root mean square percentage error."""
loss = torch.sqrt(torch.mean(((targets - predictions).float() / targets) ** 2))
"""Root mean square percentage error.

Bad predictions can lead to arbitrarily large RMSPE values, especially if some values of targets are very close to
zero. We return a large value instead of inf when (some) targets are zero.
"""
epsilon = 1e-4
# add epsilon if targets are zero to avoid division by zero
denominator = targets + epsilon * (targets == 0).float()
loss = torch.sqrt(torch.mean(((targets - predictions).float() / denominator) ** 2))
return loss


Expand Down
8 changes: 8 additions & 0 deletions tests/ludwig/modules/test_loss_modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@ def test_rmspe_loss(preds: torch.Tensor, target: torch.Tensor, output: torch.Ten
assert torch.isclose(loss(preds, target), output, rtol=0.0001)


@pytest.mark.parametrize("preds", [torch.tensor([[0.1, 0.2]]).float()])
@pytest.mark.parametrize("target", [torch.tensor([[0.0, 0.2]]).float()])
@pytest.mark.parametrize("output", [torch.tensor(707.1068).float()])
def test_rmspe_loss_zero_targets(preds: torch.Tensor, target: torch.Tensor, output: torch.Tensor):
loss = loss_modules.RMSPELoss()
assert torch.isclose(loss(preds, target), output, rtol=0.0001)


@pytest.mark.parametrize("preds", [torch.arange(6).reshape(3, 2).float()])
@pytest.mark.parametrize("target", [torch.arange(6, 12).reshape(3, 2).float()])
@pytest.mark.parametrize("output", [torch.tensor(-21.4655).float()])
Expand Down