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

[refactor] Encapsulate _convert_raw_predictions_to_raw_df #1291

Merged
merged 4 commits into from
Apr 21, 2023
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
21 changes: 16 additions & 5 deletions neuralprophet/data/process.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import logging
from typing import Optional
from typing import List, Optional

import numpy as np
import pandas as pd
Expand All @@ -12,6 +12,7 @@
ConfigLaggedRegressors,
ConfigSeasonality,
)
from neuralprophet.np_types import Components

log = logging.getLogger("NP.data.processing")

Expand Down Expand Up @@ -144,7 +145,13 @@ def _reshape_raw_predictions_to_forecst_df(model, df, predicted, components, pre
return df_forecast


def _convert_raw_predictions_to_raw_df(model, dates, predicted, components=None):
def _convert_raw_predictions_to_raw_df(
dates: pd.Series,
predicted: np.ndarray,
n_forecasts: int,
quantiles: List[float],
components: Optional[Components] = None,
) -> pd.DataFrame:
"""Turns forecast-origin-wise predictions into forecast-target-wise predictions.

Parameters
Expand All @@ -153,6 +160,10 @@ def _convert_raw_predictions_to_raw_df(model, dates, predicted, components=None)
timestamps referring to the start of the predictions.
predicted : np.array
Array containing the forecasts
n_forecasts : int
optional, number of steps ahead of prediction time step to forecast
quantiles : list[float]
optional, list of quantiles for quantile regression uncertainty estimate
components : dict[np.array]
Dictionary of components containing an array of each components' contribution to the forecast

Expand All @@ -173,13 +184,13 @@ def _convert_raw_predictions_to_raw_df(model, dates, predicted, components=None)
df_raw = pd.DataFrame()
df_raw.insert(0, "ds", dates.values)
df_raw.insert(1, "ID", "__df__") # type: ignore
for forecast_lag in range(model.n_forecasts):
for quantile_idx in range(len(model.config_train.quantiles)):
for forecast_lag in range(n_forecasts):
for quantile_idx in range(len(quantiles)):
# 0 is the median quantile index
if quantile_idx == 0:
step_name = f"step{forecast_lag}"
else:
step_name = f"step{forecast_lag} {model.config_train.quantiles[quantile_idx] * 100}%"
step_name = f"step{forecast_lag} {quantiles[quantile_idx] * 100}%"
data = all_data[:, forecast_lag, quantile_idx]
ser = pd.Series(data=data, name=step_name)
df_raw = df_raw.merge(ser, left_index=True, right_index=True)
Expand Down
8 changes: 7 additions & 1 deletion neuralprophet/forecaster.py
Original file line number Diff line number Diff line change
Expand Up @@ -1067,7 +1067,13 @@ def predict(self, df: pd.DataFrame, decompose: bool = True, raw: bool = False):
df_i, self.config_missing.drop_missing, self.predict_steps, self.n_lags
)
if raw:
fcst = _convert_raw_predictions_to_raw_df(self, dates, predicted, components)
fcst = _convert_raw_predictions_to_raw_df(
dates=dates,
predicted=predicted,
n_forecasts=self.n_forecasts,
quantiles=self.config_train.quantiles,
components=components,
)
if periods_added[df_name] > 0:
fcst = fcst[:-1]
else:
Expand Down
3 changes: 3 additions & 0 deletions neuralprophet/np_types.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import sys
from typing import Dict, List, Union

import torch
import torchmetrics

# Ensure compatibility with python 3.7
Expand All @@ -21,3 +22,5 @@
CollectMetricsMode = Union[List[str], bool, Dict[str, torchmetrics.Metric]]

SeasonGlobalLocalMode = Literal["global", "local"]

Components = Dict[str, torch.Tensor]