Skip to content

NeuralForecastTCN

NeuralForecastTCN

class NeuralForecastTCN(freq: str | int = 'auto', local_scaler_type: Literal['standard', 'robust', 'robust-iqr', 'minmax', 'boxcox'] | None = None, futr_exog_list: list[str] | None = None, verbose_fit: bool = False, verbose_predict: bool = False, input_size: int = -1, inference_input_size: int = -1, kernel_size: int = 2, dilations: list[int] | None = None, encoder_hidden_size: int = 200, encoder_activation: str = 'ReLU', context_size: int = 10, decoder_hidden_size: int = 200, decoder_layers: int = 2, loss=None, valid_loss=None, max_steps: int = 1000, learning_rate: float = 0.001, num_lr_decays: int = -1, early_stop_patience_steps: int = -1, val_check_steps: int = 100, batch_size: int = 32, valid_batch_size: int | None = None, scaler_type: str = 'robust', random_seed: int = 1, num_workers_loader=0, drop_last_loader=False, optimizer=None, optimizer_kwargs: dict | None = None, lr_scheduler=None, lr_scheduler_kwargs: dict | None = None, trainer_kwargs: dict | None = None, broadcasting: bool = False)[source]

NeuralForecast TCN model.

Interface to neuralforecast.models.TCN [1] through neuralforecast.NeuralForecast [2], from neuralforecast [3] by Nixtla.

Temporal Convolution Network (TCN), with MLP decoder. The historical encoder uses dilated skip connections to obtain efficient long memory, while the rest of the architecture allows for future exogenous alignment.

Parameters:
freqUnion[str, int] (default=”auto”)

frequency of the data, see available frequencies [4] from pandas use int freq when using RangeIndex in y

default (“auto”) interprets freq from ForecastingHorizon in fit

local_scaler_typestr (default=None)

scaler to apply per-series to all features before fitting, which is inverted after predicting

can be one of the following:

  • ‘standard’

  • ‘robust’

  • ‘robust-iqr’

  • ‘minmax’

  • ‘boxcox’

futr_exog_liststr list, (default=None)

future exogenous variables

verbose_fitbool (default=False)

print processing steps during fit

verbose_predictbool (default=False)

print processing steps during predict

input_sizeint (default=-1)

maximum sequence length for truncated train backpropagation

default (-1) uses all history

inference_input_sizeint (default=-1)

maximum sequence length for truncated inference

default (-1) uses all history

kernel_sizeint (default=2)

size of the convolving kernel

dilationsint list (default=None)

controls the temporal spacing between the kernel points also known as the à trous algorithm by default set to [1, 2, 4, 8, 16]

encoder_hidden_sizeint (default=200)

units for the TCN’s hidden state size

encoder_activationstr (default=”ReLU”)

type of TCN activation from tanh or relu

context_sizeint (default=10)

size of context vector for each timestamp on the forecasting window

decoder_hidden_sizeint (default=200)

size of hidden layer for the MLP decoder

decoder_layersint (default=2)

number of layers for the MLP decoder

losspytorch module (default=None)

instantiated train loss class from losses collection [Rcdb94044b921-5]

valid_losspytorch module (default=None)

instantiated validation loss class from losses collection [Rcdb94044b921-5]

max_stepsint (default=1000)

maximum number of training steps

learning_ratefloat (default=1e-3)

learning rate between (0, 1)

num_lr_decaysint (default=-1)

number of learning rate decays, evenly distributed across max_steps

early_stop_patience_stepsint (default=-1)

number of validation iterations before early stopping

val_check_stepsint (default=100)

number of training steps between every validation loss check

batch_sizeint (default=32)

number of different series in each batch

valid_batch_sizeOptional[int] (default=None)

number of different series in each validation and test batch

scaler_typestr (default=”robust”)

type of scaler for temporal inputs normalization

random_seedint (default=1)

random_seed for pytorch initializer and numpy generators

num_workers_loaderint (default=0)

workers to be used by TimeSeriesDataLoader

drop_last_loaderbool (default=False)

whether TimeSeriesDataLoader drops last non-full batch

optimizerpytorch optimizer (default=None) [Rcdb94044b921-7]

optimizer to use for training, if passed with None defaults to Adam

optimizer_kwargsdict (default=None) [Rcdb94044b921-8]

dict of parameters to pass to the user defined optimizer

lr_schedulerpytorch learning rate scheduler (default=None) [Rcdb94044b921-9]

user specified lr_scheduler instead of the default choice StepLR [Rcdb94044b921-10]

lr_scheduler_kwargsdict (default=None)

list of parameters used by the user specified lr_scheduler

trainer_kwargsdict (default=None)

keyword trainer arguments inherited from PyTorch Lighning’s trainer [Rcdb94044b921-6]

broadcastingbool (default=False)

if True, a model will be fit per time series. Panels, e.g., multiindex data input, will be broadcasted to single series, and for each single series, one copy of this forecaster will be applied.

Attributes:
algorithm_class

Import underlying NeuralForecast algorithm class.

algorithm_exogenous_support

Set support for exogenous features.

algorithm_name

Set custom model name.

algorithm_parameters

Get keyword parameters for the underlying NeuralForecast algorithm class.

dict

keyword arguments for the underlying algorithm class

cutoff

Cut-off = “present time” state of forecaster.

fh

Forecasting horizon that was passed.

is_fitted

Whether fit has been called.

state

State of the estimator.

Notes

  • If loss is unspecified, MAE is used as the loss function for training.

  • Only futr_exog_list will be considered as exogenous variables.

References

https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases .. [Rcdb94044b921-5] https://nixtlaverse.nixtla.io/neuralforecast/losses.pytorch.html .. [Rcdb94044b921-6] https://lightning.ai/docs/pytorch/stable/api/pytorch_lightning.trainer.trainer.Trainer.html#lightning.pytorch.trainer.trainer.Trainer .. [Rcdb94044b921-7] https://pytorch.org/docs/stable/optim.html .. [Rcdb94044b921-8] https://pytorch.org/docs/stable/optim.html#algorithms .. [Rcdb94044b921-9] https://pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.LRScheduler.html .. [Rcdb94044b921-10] https://pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.StepLR.html

Examples

>>>
>>> # importing necessary libraries
>>> from sktime.datasets import load_longley
>>> from sktime.forecasting.neuralforecast import NeuralForecastTCN
>>> from sktime.split import temporal_train_test_split
>>>
>>> # loading the Longley dataset and splitting it into train and test subsets
>>> y, X = load_longley()
>>> y_train, y_test, X_train, X_test = temporal_train_test_split(y, X, test_size=4)
>>>
>>> # creating model instance configuring the hyperparameters
>>> model = NeuralForecastTCN(
...     "A-DEC", futr_exog_list=["ARMED", "POP"], max_steps=5
... )
>>>
>>> # fitting the model
>>> model.fit(y_train, X=X_train, fh=[1, 2, 3, 4])
Seed set to 1
Epoch 4: 100%|████████████████████████████| 1/1 [00:00<00:00, 48.19it/s, v_num=5, train_loss_step=0.833, train_loss_epoch=0.833]
NeuralForecastTCN(freq='A-DEC', futr_exog_list=['ARMED', 'POP'], max_steps=5)
>>>
>>> # getting point predictions
>>> model.predict(X=X_test)
Predicting DataLoader 0: 100%|███████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 183.39it/s]
1959    63611.593750
1960    63528.542969
1961    63529.167969
1962    63718.667969
Freq: A-DEC, Name: TOTEMP, dtype: float64
>>>

Methods

check_is_fitted([method_name])

Check if the estimator has been fitted.

clone()

Obtain a clone of the object with same hyper-parameters and config.

clone_tags(estimator[, tag_names])

Clone tags from another object as dynamic override.

create_test_instance([parameter_set])

Construct an instance of the class, using first test parameter set.

create_test_instances_and_names([parameter_set])

Create list of all test instances and a list of names for them.

fit(y[, X, fh])

Fit forecaster to training data.

fit_predict(y[, X, fh, X_pred])

Fit and forecast time series at future horizon.

get_class_tag(tag_name[, tag_value_default])

Get class tag value from class, with tag level inheritance from parents.

get_class_tags()

Get class tags from class, with tag level inheritance from parent classes.

get_config()

Get config flags for self.

get_fitted_params([deep])

Get fitted parameters.

get_param_defaults()

Get object's parameter defaults.

get_param_names([sort])

Get object's parameter names.

get_params([deep])

Get a dict of parameters values for this object.

get_pretrained_params([deep])

Get pretrained parameters of this estimator.

get_tag(tag_name[, tag_value_default, ...])

Get tag value from instance, with tag level inheritance and overrides.

get_tags()

Get tags from instance, with tag level inheritance and overrides.

get_test_params([parameter_set])

Return testing parameter settings for the estimator.

is_composite()

Check if the object is composed of other BaseObjects.

load_from_path(serial)

Load object from file location.

load_from_serial(serial)

Load object from serialized memory container.

predict([fh, X])

Forecast time series at future horizon.

predict_interval([fh, X, coverage])

Compute/return prediction interval forecasts.

predict_proba([fh, X, marginal])

Compute/return fully probabilistic forecasts.

predict_quantiles([fh, X, alpha])

Compute/return quantile forecasts.

predict_residuals([y, X])

Return residuals of time series forecasts.

predict_var([fh, X, cov])

Compute/return variance forecasts.

pretrain(y[, X, fh])

Pre-train forecaster on panel (global) data.

reset()

Reset the object to a clean post-init state.

save([path, serialization_format])

Save serialized self to bytes-like object or to (.zip) file.

score(y[, X, fh])

Scores forecast against ground truth, using MAPE (non-symmetric).

set_config(**config_dict)

Set config flags to given values.

set_params(**params)

Set the parameters of this object.

set_random_state([random_state, deep, ...])

Set random_state pseudo-random seed parameters for self.

set_tags(**tag_dict)

Set instance level tag overrides to given values.

update(y[, X, update_params])

Update cutoff value and, optionally, fitted parameters.

update_predict(y[, cv, X, update_params, ...])

Make predictions and update model iteratively over the test set.

update_predict_single([y, fh, X, update_params])

Update model with new data and make forecasts.