If you require full control over the training process, you can bypass the Package layer and use the M Layer directly. This involves manually setting up a TimeSeries dataset, an EncoderDecoderTimeSeriesDataModule, the model (e.g., TFT), and a PyTorch Lightning Trainer.
Note: When initializing the model manually, you must pass metadata=data_module.metadata to ensure important parameters like encoder_cont are correctly initialized.
from pytorch_forecasting.data.timeseries import TimeSeries
from pytorch_forecasting.data.data_module import EncoderDecoderTimeSeriesDataModule
from pytorch_forecasting.metrics import MAE, SMAPE
from pytorch_forecasting.models.temporal_fusion_transformer._tft_v2 import TFT
from lightning.pytorch import Trainer
# Create TimeSeries dataset
dataset = TimeSeries(
data=data_df,
time="time_idx",
target="y",
group=["series_id"],
num=["x", "future_known_feature", "static_feature"],
cat=["category", "static_feature_cat"],
known=["future_known_feature"],
unknown=["x", "category"],
static=["static_feature", "static_feature_cat"],
)
# Create the data_module
data_module = EncoderDecoderTimeSeriesDataModule(
time_series_dataset=dataset,
max_encoder_length=30,
max_prediction_length=1,
batch_size=32,
)
# Initialise the Model
model = TFT(
loss=MAE(),
logging_metrics=[MAE(), SMAPE()],
optimizer="adam",
optimizer_params={"lr": 1e-3},
lr_scheduler="reduce_lr_on_plateau",
lr_scheduler_params={"mode": "min", "factor": 0.1, "patience": 10},
hidden_size=64,
num_layers=2,
attention_head_size=4,
dropout=0.1,
metadata=data_module.metadata, # pass the metadata from the datamodule to the model
)
# Train the model
trainer = Trainer(
max_epochs=5,
accelerator="auto",
devices=1,
enable_progress_bar=True,
log_every_n_steps=10,
)
trainer.fit(model, data_module)