Skip to content

Fix the torch_metric shape error #2786

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

Merged
merged 3 commits into from
Apr 28, 2025
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ but cannot always guarantee backwards compatibility. Changes that may **break co

**Fixed**

- Fixed a bug when training a `TorchForecastingModel`, where using certain `torchmetrics` that require a 2D model output (e.g. R2Score) raised an error. [He Weilin](https://github.com/cnhwl).

**Dependencies**

### For developers of the library:
Expand Down
5 changes: 2 additions & 3 deletions darts/models/forecasting/pl_forecasting_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -409,9 +409,8 @@ def _update_metrics(self, output, target, metrics):
pred = output.squeeze(dim=-1)

# torch metrics require 2D targets of shape (batch size * ocl, num targets)
if self.n_targets > 1:
target = target.reshape(-1, self.n_targets)
pred = pred.reshape(-1, self.n_targets)
target = target.reshape(-1, self.n_targets)
pred = pred.reshape(-1, self.n_targets)

metrics.update(pred, target)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
MeanAbsolutePercentageError,
Metric,
MetricCollection,
R2Score,
)

from darts.models import (
Expand Down Expand Up @@ -1428,6 +1429,7 @@ def test_metrics(self):
metric_collection = MetricCollection([
MeanAbsolutePercentageError(),
MeanAbsoluteError(),
R2Score(),
])

model_kwargs = {
Expand Down Expand Up @@ -1476,6 +1478,7 @@ def test_metrics_w_likelihood(self):
metric_collection = MetricCollection([
MeanAbsolutePercentageError(),
MeanAbsoluteError(),
R2Score(),
])
model_kwargs = {
"logger": DummyLogger(),
Expand Down