jdb78 / pytorch-forecasting

Time series forecasting with PyTorch
https://pytorch-forecasting.readthedocs.io/
MIT License
3.87k stars 611 forks source link

Predicting Using Pre-Trained Model does not work as expected #623

Closed aamrb96 closed 2 years ago

aamrb96 commented 3 years ago

PyTorch-Forecasting version:

PyTorch version:

Python version:

Operating System:

Description

I pretrained a model on a different machine and want to use it on my windows laptop. I am using the checkpoints to export the model.I want to forecast data that I parsed into a TimeSeriesDataSet object and then transformed into a dataloader using the to_dataloader method.

Expected behavior

I expected the function to output forecasts for each forecast step.

Actual behavior

However, a TypeError is raised: DataLoader' object is not subscriptable. I checked theinit.pyfile for theforward()` methods input. It states that

Args:
            x (Dict[str, torch.Tensor]): input from dataloader generated from
                :py:class:`~pytorch_forecasting.data.timeseries.TimeSeriesDataSet`.

The entire Traceback:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-86-a8c73f261f76> in <module>
----> 1 predictions = nbeats(test_dataloader)

~\.conda\envs\nbeats\lib\site-packages\torch\nn\modules\module.py in _call_impl(self, *input, **kwargs)
   1049         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1050                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1051             return forward_call(*input, **kwargs)
   1052         # Do not call functions when jit is used
   1053         full_backward_hooks, non_full_backward_hooks = [], []

~\Desktop\NBEATs_jbk\pytorch_forecasting\models\nbeats\__init__.py in forward(self, x)
    138             Dict[str, torch.Tensor]: output of model
    139         """
--> 140         target = x["encoder_cont"][..., 0]
    141 
    142         timesteps = self.hparams.context_length + self.hparams.prediction_length

TypeError: 'DataLoader' object is not subscriptable

Maybe I am missing something here - pytorch and pytorch lightning are new to me. Any help would be greatly appreciated!

Code to reproduce the problem

training_cutoff = m4_data[DATA]["time_idx"].max() - max_prediction_length

context_length = max_encoder_length prediction_length = max_prediction_length

training = TimeSeriesDataSet( train_data, time_idx="time_idx", target="value",

categorical_encoders={"series": NaNLabelEncoder().fit(m4_data["Daily-train"].series)},

group_ids=["identifier"],
min_encoder_length=context_length,
max_encoder_length=context_length,
max_prediction_length=prediction_length,
min_prediction_length=prediction_length,
time_varying_unknown_reals=["value"],
randomize_length=None,
add_relative_time_idx=False,
add_target_scales=False,

)

net = NBeats.from_dataset( training, learning_rate=3e-2, log_interval=10, log_val_interval=1, log_gradient_flow=False, weight_decay=1e-2 )

Model trained on a different machine using the example provided in the documentation

trained_model = r"\epoch=17-step=269.ckpt"

nbeats = net.load_from_checkpoint(trained_model)

nbeats.eval() nbeats.freeze()

testing = TimeSeriesDataSet( test_data, time_idx="time_idx", target="value",

categorical_encoders={"series": NaNLabelEncoder().fit(m4_data["Daily-train"].series)},

group_ids=["identifier"],
min_encoder_length=context_length,
max_encoder_length=context_length,
max_prediction_length=prediction_length,
min_prediction_length=prediction_length,
time_varying_unknown_reals=["value"],
randomize_length=None,
add_relative_time_idx=False,
add_target_scales=False,

)

test_dataloader = testing.to_dataloader(train=False, batch_size=batch_size, num_workers=8)

predictions = nbeats(test_dataloader)



Paste the command(s) you ran and the output. Including a link to a colab notebook will speed up issue resolution.
If there was a crash, please include the traceback here.
The code used to initialize the TimeSeriesDataSet and model should be also included.
jdb78 commented 2 years ago

Use the .predict() method. Calling the model directly is like calling the pytorch module, i.e. that can be done with a batch but not with a dataloader.