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

[WIP] Dlinear with covariates #3211

Open
wants to merge 3 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
73 changes: 56 additions & 17 deletions src/gluonts/torch/model/d_linear/estimator.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
TestSplitSampler,
ExpectedNumInstanceSampler,
SelectFields,
RenameFields,
)
from gluonts.torch.model.estimator import PyTorchLightningEstimator
from gluonts.torch.model.predictor import PyTorchPredictor
Expand Down Expand Up @@ -103,6 +104,7 @@ def __init__(
trainer_kwargs: Optional[Dict[str, Any]] = None,
train_sampler: Optional[InstanceSampler] = None,
validation_sampler: Optional[InstanceSampler] = None,
num_feat_dynamic_real: int = 0,
) -> None:
default_trainer_kwargs = {
"max_epochs": 100,
Expand Down Expand Up @@ -132,18 +134,29 @@ def __init__(
min_future=prediction_length
)

self.num_feat_dynamic_real = num_feat_dynamic_real

def create_transformation(self) -> Transformation:
return SelectFields(
[
FieldName.ITEM_ID,
FieldName.INFO,
FieldName.START,
FieldName.TARGET,
],
allow_missing=True,
) + AddObservedValuesIndicator(
target_field=FieldName.TARGET,
output_field=FieldName.OBSERVED_VALUES,
return (
SelectFields(
[
FieldName.ITEM_ID,
FieldName.INFO,
FieldName.START,
FieldName.TARGET,
]
+ (
[FieldName.FEAT_DYNAMIC_REAL]
if self.num_feat_dynamic_real > 0
else []
),
allow_missing=True,
)
+ RenameFields({FieldName.FEAT_DYNAMIC_REAL: FieldName.FEAT_TIME})
+ AddObservedValuesIndicator(
target_field=FieldName.TARGET,
output_field=FieldName.OBSERVED_VALUES,
)
)

def create_lightning_module(self) -> pl.LightningModule:
Expand All @@ -157,6 +170,7 @@ def create_lightning_module(self) -> pl.LightningModule:
"distr_output": self.distr_output,
"kernel_size": self.kernel_size,
"scaling": self.scaling,
"num_feat_dynamic_real": self.num_feat_dynamic_real,
},
)

Expand All @@ -179,9 +193,10 @@ def _create_instance_splitter(
instance_sampler=instance_sampler,
past_length=self.context_length,
future_length=self.prediction_length,
time_series_fields=[
FieldName.OBSERVED_VALUES,
],
time_series_fields=[FieldName.OBSERVED_VALUES]
+ (
[FieldName.FEAT_TIME] if self.num_feat_dynamic_real > 0 else []
),
dummy_value=self.distr_output.value_in_support,
)

Expand All @@ -200,7 +215,15 @@ def create_training_data_loader(
instances,
batch_size=self.batch_size,
shuffle_buffer_length=shuffle_buffer_length,
field_names=TRAINING_INPUT_NAMES,
field_names=TRAINING_INPUT_NAMES
+ (
[
f"past_{FieldName.FEAT_TIME}",
f"future_{FieldName.FEAT_TIME}",
]
if self.num_feat_dynamic_real > 0
else []
),
output_type=torch.tensor,
num_batches_per_epoch=self.num_batches_per_epoch,
)
Expand All @@ -217,7 +240,15 @@ def create_validation_data_loader(
return as_stacked_batches(
instances,
batch_size=self.batch_size,
field_names=TRAINING_INPUT_NAMES,
field_names=TRAINING_INPUT_NAMES
+ (
[
f"past_{FieldName.FEAT_TIME}",
f"future_{FieldName.FEAT_TIME}",
]
if self.num_feat_dynamic_real > 0
else []
),
output_type=torch.tensor,
)

Expand All @@ -230,7 +261,15 @@ def create_predictor(

return PyTorchPredictor(
input_transform=transformation + prediction_splitter,
input_names=PREDICTION_INPUT_NAMES,
input_names=PREDICTION_INPUT_NAMES
+ (
[
f"past_{FieldName.FEAT_TIME}",
f"future_{FieldName.FEAT_TIME}",
]
if self.num_feat_dynamic_real > 0
else []
),
prediction_net=module,
forecast_generator=self.distr_output.forecast_generator,
batch_size=self.batch_size,
Expand Down
48 changes: 46 additions & 2 deletions src/gluonts/torch/model/d_linear/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.

from typing import Tuple
from typing import Optional, Tuple

import torch
from torch import nn
Expand Down Expand Up @@ -88,6 +88,7 @@ def __init__(
distr_output=StudentTOutput(),
kernel_size: int = 25,
scaling: str = "mean",
num_feat_dynamic_real: int = 0,
) -> None:
super().__init__()

Expand All @@ -107,6 +108,8 @@ def __init__(
else:
self.scaler = NOPScaler(keepdim=True)

self.num_feat_dynamic_real = num_feat_dynamic_real

self.kernel_size = kernel_size

self.linear_seasonal = make_linear_layer(
Expand All @@ -115,10 +118,37 @@ def __init__(
self.linear_trend = make_linear_layer(
context_length, prediction_length * hidden_dimension
)
# to do: add past and future covariates
self.linear_future_cov = make_linear_layer(
prediction_length * self.num_feat_dynamic_real,
prediction_length * hidden_dimension,
)

self.args_proj = self.distr_output.get_args_proj(hidden_dimension)

def describe_inputs(self, batch_size=1) -> InputSpec:
if self.num_feat_dynamic_real > 0:
input_spec_feat = {
"past_time_feat": Input(
shape=(
batch_size,
self.context_length,
self.num_feat_dynamic_real,
),
dtype=torch.float,
),
"future_time_feat": Input(
shape=(
batch_size,
self.prediction_length,
self.num_feat_dynamic_real,
),
dtype=torch.float,
),
}
else:
input_spec_feat = {}

return InputSpec(
{
"past_target": Input(
Expand All @@ -127,6 +157,7 @@ def describe_inputs(self, batch_size=1) -> InputSpec:
"past_observed_values": Input(
shape=(batch_size, self.context_length), dtype=torch.float
),
**input_spec_feat,
},
torch.zeros,
)
Expand All @@ -135,6 +166,8 @@ def forward(
self,
past_target: torch.Tensor,
past_observed_values: torch.Tensor,
past_time_feat: Optional[torch.Tensor] = None,
future_time_feat: Optional[torch.Tensor] = None,
) -> Tuple[Tuple[torch.Tensor, ...], torch.Tensor, torch.Tensor]:
# scale the input
past_target_scaled, loc, scale = self.scaler(
Expand All @@ -145,6 +178,12 @@ def forward(
trend_output = self.linear_trend(trend.squeeze(-1))
nn_out = seasonal_output + trend_output

if self.num_feat_dynamic_real > 0:
# to do: add past and future covariates
nn_out = nn_out + self.linear_future_cov(
torch.flatten(future_time_feat, start_dim=1)
)

distr_args = self.args_proj(
nn_out.reshape(-1, self.prediction_length, self.hidden_dimension)
)
Expand All @@ -156,9 +195,14 @@ def loss(
past_observed_values: torch.Tensor,
future_target: torch.Tensor,
future_observed_values: torch.Tensor,
past_time_feat: Optional[torch.Tensor] = None,
future_time_feat: Optional[torch.Tensor] = None,
) -> torch.Tensor:
distr_args, loc, scale = self(
past_target=past_target, past_observed_values=past_observed_values
past_target=past_target,
past_observed_values=past_observed_values,
past_time_feat=past_time_feat,
future_time_feat=future_time_feat,
)
loss = self.distr_output.loss(
target=future_target, distr_args=distr_args, loc=loc, scale=scale
Expand Down
Loading