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

Adding r2 score #3161

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
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
4 changes: 3 additions & 1 deletion src/gluonts/evaluation/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
quantile_loss,
smape,
num_masked_values,
r2_score
)


Expand Down Expand Up @@ -388,7 +389,7 @@ def get_base_metrics(
"MASE": mase(pred_target, median_fcst, seasonal_error),
"MAPE": mape(pred_target, median_fcst),
"sMAPE": smape(pred_target, median_fcst),
"num_masked_target_values": num_masked_values(pred_target),
"r2_score: ": smape(pred_target, median_fcst),
}

def get_metrics_per_ts(
Expand Down Expand Up @@ -504,6 +505,7 @@ def get_aggregate_metrics(
"sMAPE": "mean",
"MSIS": "mean",
"num_masked_target_values": "sum",
"r2_score":"mean",
}
if self.calculate_owa:
agg_funs["sMAPE_naive2"] = "mean"
Expand Down
16 changes: 16 additions & 0 deletions src/gluonts/evaluation/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,22 @@
from gluonts.time_feature import get_seasonality


def r2_score(target: np.ndarray, forecast: np.ndarray) -> float:
r"""
.. math::

R^2 = 1 - \frac{SS_{res}}{SS_{tot}}

Where:
- SS_{res} = sum((Y - \hat{Y})^2)
- SS_{tot} = sum((Y - \bar{Y})^2)
"""
mean_target = np.mean(target)
ss_res = np.sum((target - forecast)**2)
ss_tot = np.sum((target - mean_target)**2)
r2 = 1 - (ss_res / ss_tot)
return r2

def calculate_seasonal_error(
past_data: np.ndarray,
freq: Optional[str] = None,
Expand Down