Models

class BaseModel[source]

Base class for creating neural models.

This class provides useful utilities for the model designer:

  • the methods add_model_specific_args() and add_argparse_args() allow to automatically add to an ArgumentParser the arguments needed to initialize the model (with typing and default values).

  • the method loss() can be used to compute a custom loss on the provided training target. Inference modules in tsl will call this method for the loss computation, if implemented in the model.

  • the method predict() can be used to define a variation of the forward() function for only inference purposes (e.g., removing outputs used only for auxiliary tasks during training).

  • the parameter return_type specifies which the return type of the forward function (Tensor, list or dict).

  • the class attribute can_be_compiled indicates whether the model is covered by TSL’s full-graph compile() tests.

property has_loss: bool

Returns True if the model has implemented the loss() method.

property has_predict: bool

Returns True if the model has implemented the predict() method.

loss(target, *args, **kwargs)[source]

Compute a custom loss w.r.t. target.

predict(*args, **kwargs)[source]

Forward function used only for inference.

reset_parameters()[source]

Reset the parameters of the model.

classmethod get_model_signature() → dict[source]

Get signature of the model’s BaseModel’s __init__ function.

classmethod get_forward_signature() → dict[source]

Get signature of the model’s forward() function.

classmethod filter_model_args_(mapping: dict)[source]

Remove from mapping all the keys that are not in BaseModel’s __init__ function.

classmethod model_excluded_args() → Set[source]

Set of arguments of __init__() to be excluded when adding model’s args to an ArgumentParser (see add_model_specific_args()).

classmethod add_model_specific_args(parser: ArgumentParser)[source]

Adds to the ArgumentParser parser the arguments needed to initialize the model (with typing and default values).

The arguments added are all the parameters of the __init__() method, excluding the keys returned by model_excluded_args().

classmethod add_argparse_args(parser: ArgumentParser, exclude_args: Set | None = None)[source]

Adds to the ArgumentParser parser all the parameters of the __init__() method (with typing and default values).

Spatiotemporal Models

DCRNNModel

The Diffusion Convolutional Recurrent Neural Network from the paper "Diffusion Convolutional Recurrent Neural Network: Data-Driven Traffic Forecasting" (Li et al., ICLR 2018).

GraphWaveNetModel

The Graph WaveNet model from the paper "Graph WaveNet for Deep Spatial-Temporal Graph Modeling" (Wu et al., IJCAI 2019).

GatedGraphNetworkModel

Simple time-then-space model with an MLP with residual connections as encoder (flattened time dimension) and a gated GN decoder with node identification.

RNNEncGCNDecModel

Simple time-then-space model.

STCNModel

Spatiotemporal GNN with interleaved temporal and spatial diffusion convolutions.

EvolveGCNModel

The EvolveGCN model from the paper "EvolveGCN: Evolving Graph Convolutional Networks for Dynamic Graphs" (Pereja et al., AAAI 2020).

GRUGCNModel

Simple time-then-space model with a GRU encoder and a GCN decoder from the paper "On the Equivalence Between Temporal and Static Equivariant Graph Representations" (Guo et al., ICML 2022).

AGCRNModel

The Adaptive Graph Convolutional Recurrent Network from the paper "Adaptive Graph Convolutional Recurrent Network for Traffic Forecasting" (Bai et al., NeurIPS 2020).

GRINModel

The Graph Recurrent Imputation Network with DCRNN cells from the paper "Filling the G_ap_s: Multivariate Time Series Imputation by Graph Neural Networks" (Cini et al., ICLR 2022).

SPINModel

The Spatiotemporal Point Inference Network (SPIN) from the paper "Learning to Reconstruct Missing Data from Spatiotemporal Graphs with Sparse Observations" (Marisca et al., NeurIPS 2022).

SPINHierarchicalModel

STGNN

Base class for SpatioTemporal Graph Neural Networks (STGNNs) following the template architecture of the paper "Taming Local Effects in Graph-based Spatiotemporal Forecasting" (Cini et al., NeurIPS 2023).

DisjointSTGNN

STGNN with each STMP layer split into temporal then spatial stacks.

TimeThenSpace

Disjoint STGNN composed from one temporal and multiple spatial modules.

class DCRNNModel(input_size: int, output_size: int, horizon: int, exog_size: int = 0, hidden_size: int = 32, kernel_size: int = 2, ff_size: int = 256, n_layers: int = 1, cache_support: bool = False, dropout: float = 0.0, activation: str = 'relu')[source]

The Diffusion Convolutional Recurrent Neural Network from the paper “Diffusion Convolutional Recurrent Neural Network: Data-Driven Traffic Forecasting” (Li et al., ICLR 2018).

Differently from the original implementation, the recurrent decoder is substituted with a fixed-length nonlinear readout.

Parameters:
  • input_size (int) – Number of features of the input sample.

  • output_size (int) – Number of output channels.

  • horizon (int) – Number of future time steps to forecast.

  • exog_size (int) – Number of features of the input covariate, if any. (default: 0)

  • hidden_size (int) – Number of hidden units. (default: 32)

  • kernel_size (int) – Order of the spatial diffusion process. (default: 2)

  • ff_size (int) – Number of units in the nonlinear readout. (default: 256)

  • n_layers (int) – Number of DCRNN cells. (default: 1)

  • dropout (float) – Dropout probability. (default: 0)

  • activation (str) – Activation function in the readout. (default: 'relu')

can_be_compiled: bool = True
forward(x: Tensor, edge_index: Any, edge_weight: Any = None, u: Any = None) → Tensor[source]
return_type

alias of Tensor

class GraphWaveNetModel(input_size: int, output_size: int, horizon: int, exog_size: int = 0, hidden_size: int = 32, ff_size: int = 256, n_layers: int = 8, temporal_kernel_size: int = 2, spatial_kernel_size: int = 2, learned_adjacency: bool = True, n_nodes: int | None = None, emb_size: int = 10, dilation: int = 2, dilation_mod: int = 2, norm: str = 'batch', dropout: float = 0.3)[source]

The Graph WaveNet model from the paper “Graph WaveNet for Deep Spatial-Temporal Graph Modeling” (Wu et al., IJCAI 2019).

Parameters:
  • input_size (int) – Number of features of the input sample.

  • output_size (int) – Number of output channels.

  • horizon (int) – Number of future time steps to forecast.

  • exog_size (int) – Number of features of the input covariate, if any. (default: 0)

  • hidden_size (int) – Number of hidden units. (default: 32)

  • ff_size (int) – Number of units in the nonlinear readout. (default: 256)

  • n_layers (int) – Number of Graph WaveNet blocks. (default: 8)

  • temporal_kernel_size (int) – Size of the temporal convolution kernel. (default: 2)

  • spatial_kernel_size (int) – Order of the spatial diffusion process. (default: 2)

  • learned_adjacency (bool) – If True, then consider an additional learned adjacency matrix. (default: True)

  • n_nodes (int, optional) – Number of nodes in the input graph, required only when learned_adjacency is True. (default: None)

  • emb_size (int) – Number of features in the node embeddings used for graph learning. (default: 10)

  • dilation (int) – Dilation of the temporal convolutional kernels. (default: 2)

  • dilation_mod (int) – Length of the cycle for the dilation coefficient. (default: 2)

  • norm (str) – Normalization strategy. (default: 'batch')

  • dropout (float) – Dropout probability. (default: 0.3)

can_be_compiled: bool = True
forward(x: Tensor, edge_index: Any, edge_weight: Any = None, u: Any = None) → Tensor[source]
get_learned_adj()[source]
return_type

alias of Tensor

class GatedGraphNetworkModel(input_size: int, input_window_size: int, horizon: int, n_nodes: int, hidden_size: int, output_size: int = None, exog_size: int = 0, enc_layers: int = 1, gnn_layers: int = 1, full_graph: bool = True, activation: str = 'silu')[source]

Simple time-then-space model with an MLP with residual connections as encoder (flattened time dimension) and a gated GN decoder with node identification.

Inspired by the FC-GNN model from the paper “Multivariate Time Series Forecasting with Latent Graph Inference” (Satorras et al., 2022).

Parameters:
  • input_size (int) – Size of the input.

  • input_window_size (int) – Size of the input window (this model cannot process sequences of variable length).

  • hidden_size (int) – Number of hidden units in each hidden layer.

  • output_size (int) – Size of the output.

  • horizon (int) – Forecasting steps.

  • n_nodes (int) – Number of nodes.

  • exog_size (int) – Size of the optional exogenous variables.

  • enc_layers (int) – Number of layers in the MLP encoder.

  • gnn_layers (int) – Number of GNN layers in the decoder.

  • full_graph (int) – Whether to use a full graph for the GNN. In that case, the model turns into a dense spatial attention layer.

can_be_compiled: bool = True
forward(x, edge_index=None, u=None)[source]
return_type

alias of Tensor

class RNNEncGCNDecModel(input_size, hidden_size, output_size, exog_size, rnn_layers, gcn_layers, rnn_dropout, gcn_dropout, horizon, cell_type='gru', activation='relu')[source]

Simple time-then-space model.

Input time series are encoded in vectors using an RNN and then decoded using a stack of GCN layers.

Parameters:
  • input_size (int) – Input size.

  • hidden_size (int) – Units in the hidden layers.

  • output_size (int) – Size of the optional readout.

  • exog_size (int) – Size of the exogenous variables.

  • rnn_layers (int) – Number of recurrent layers in the encoder.

  • gcn_layers (int) – Number of graph convolutional layers in the decoder.

  • rnn_dropout (float, optional) – Dropout probability in the RNN encoder.

  • gcn_dropout (float, optional) – Dropout probability int the GCN decoder.

  • horizon (int) – Forecasting horizon.

  • cell_type (str, optional) – Type of cell that should be used. (options: ['gru', 'lstm']). (default: 'gru')

  • activation (str, optional) – Activation function.

can_be_compiled: bool = False
forward(x, edge_index, edge_weight, u=None, **kwargs)[source]
return_type

alias of Tensor

class STCNModel(input_size, exog_size, hidden_size, ff_size, output_size, n_layers, horizon, temporal_kernel_size, spatial_kernel_size, temporal_convs_layer=2, spatial_convs_layer=1, dilation=1, norm='none', gated=False, activation='relu', dropout=0.0)[source]

Spatiotemporal GNN with interleaved temporal and spatial diffusion convolutions.

Parameters:
  • input_size (int) – Size of the input.

  • exog_size (int) – Size of the exogenous variables.

  • hidden_size (int) – Number of units in the hidden layer.

  • ff_size (int) – Number of units in the hidden layers of the nonlinear readout.

  • output_size (int) – Number of output channels.

  • n_layers (int) – Number of GraphWaveNet blocks.

  • horizon (int) – Forecasting horizon.

  • temporal_kernel_size (int) – Size of the temporal convolution kernel.

  • spatial_kernel_size (int) – Order of the spatial diffusion process.

  • dilation (int, optional) – Dilation of the temporal convolutional kernels.

  • norm (str, optional) – Normalization strategy.

  • gated (bool, optional) – Whether to use gated TanH activation in the temporal convolutional layers.

  • activation (str, optional) – Activation function.

  • dropout (float, optional) – Dropout probability.

can_be_compiled: bool = True
forward(x, edge_index, edge_weight=None, u=None, **kwargs)[source]

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

return_type

alias of Tensor

class EvolveGCNModel(input_size, hidden_size, output_size, horizon, exog_size, n_layers, norm, root_weight, cached, variant='H', activation='relu')[source]

The EvolveGCN model from the paper “EvolveGCN: Evolving Graph Convolutional Networks for Dynamic Graphs” (Pereja et al., AAAI 2020).

Parameters:
  • input_size (int) – Size of the input.

  • hidden_size (int) – Number of hidden units in each hidden layer.

  • output_size (int) – Size of the output.

  • horizon (int) – Forecasting steps.

  • exog_size (int) – Size of the optional exogenous variables.

  • n_layers (int) – Number of layers in the encoder.

  • asymmetric_norm (bool) – Whether to consider the input graph as directed.

  • root_weight (bool) – Whether to add a parametrized skip connection.

  • cached (bool) – Whether to cache normalized edge_weights.

  • variant (str) – Variant of EvolveGCN to use (options: ‘H’ or ‘O’)

  • activation (str) – Activation after each GCN layer.

can_be_compiled: bool = True
forward(x, edge_index, edge_weight=None, u=None)[source]
return_type

alias of Tensor

class GRUGCNModel(input_size, hidden_size, output_size, horizon, exog_size, enc_layers, gcn_layers, norm='mean', encode_edges=False, activation='softplus')[source]

Simple time-then-space model with a GRU encoder and a GCN decoder from the paper “On the Equivalence Between Temporal and Static Equivariant Graph Representations” (Guo et al., ICML 2022).

Parameters:
  • input_size (int) – Size of the input.

  • hidden_size (int) – Number of hidden units in each hidden layer.

  • output_size (int) – Size of the output.

  • horizon (int) – Forecasting steps.

  • exog_size (int) – Size of the optional exogenous variables.

  • enc_layers (int) – Number of layers in the GRU encoder.

  • gcn_layers (int) – Number of GCN layers in GCN decoder.

  • norm (str) – Normalization used by the graph convolutional layers.

can_be_compiled: bool = False
forward(x, edge_index, edge_weight=None, edge_features=None, u=None)[source]
return_type

alias of Tensor

class AGCRNModel(input_size: int, output_size: int, horizon: int, n_nodes: int, hidden_size: int = 64, emb_size: int = 10, exog_size: int = 0, n_layers: int = 1)[source]

The Adaptive Graph Convolutional Recurrent Network from the paper “Adaptive Graph Convolutional Recurrent Network for Traffic Forecasting” (Bai et al., NeurIPS 2020).

Parameters:
  • input_size (int) – Number of features of the input sample.

  • output_size (int) – Number of output channels.

  • horizon (int) – Number of future time steps to forecast.

  • exog_size (int) – Number of features of the input covariate, if any.

  • hidden_size (int) – Number of hidden units.

  • hidden_size – Size of the learned node embeddings.

  • n_nodes (int) – Number of nodes in the input (static) graph.

  • n_layers (int) – Number of AGCRN cells. (default: 1)

can_be_compiled: bool = True
forward(x: Tensor, u: Any = None) → Tensor[source]
return_type

alias of Tensor

class GRINModel(input_size: int, hidden_size: int = 64, ff_size: int = 128, embedding_size: int | None = None, exog_size: int = 0, n_layers: int = 1, n_nodes: int | None = None, kernel_size: int = 2, decoder_order: int = 1, layer_norm: bool = False, dropout: float = 0.0, ff_dropout: float = 0.0, merge_mode: str = 'mlp')[source]

The Graph Recurrent Imputation Network with DCRNN cells from the paper “Filling the G_ap_s: Multivariate Time Series Imputation by Graph Neural Networks” (Cini et al., ICLR 2022).

Parameters:
  • input_size (int) – Size of the input.

  • hidden_size (int) – Number of units in the DCRNN hidden layer. (default: 64)

  • ff_size (int) – Number of units in the nonlinear readout. (default: 128)

  • embedding_size (int, optional) – Number of features in the optional node embeddings. (default: None)

  • exog_size (int) – Number of channels in the exogenous variables, if any. (default: None)

  • n_layers (int) – Number DCRNN cells. (default: 1)

  • n_nodes (int, optional) – Number of nodes in the input graph. (default: None)

  • kernel_size (int) – Order of the spatial diffusion process in the DCRNN cells. (default: 2)

  • decoder_order (int) – Order of the spatial diffusion process in the spatial decoder. (default: 1)

  • layer_norm (bool, optional) – If True, then use layer normalization. (default: False)

  • dropout (float, optional) – Dropout probability in the DCRNN cells. (default: 0)

  • ff_dropout (float, optional) – Dropout probability in the readout. (default: 0)

  • merge_mode (str, optional) – Strategy used to merge representations coming from the two branches of the bidirectional model. (default: mlp)

can_be_compiled: bool = True
forward(x: Any, edge_index: Any, edge_weight: Any = None, mask: Any = None, u: Any = None) → list[source]
predict(x: Any, edge_index: Any, edge_weight: Any = None, mask: Any = None, u: Any = None) → Any[source]
return_type

alias of list

class SPINModel(input_size: int, hidden_size: int, n_nodes: int, exog_size: int | None = None, output_size: int | None = None, temporal_self_attention: bool = True, reweigh: str | None = 'softmax', n_layers: int = 4, eta: int = 3, message_layers: int = 1)[source]

The Spatiotemporal Point Inference Network (SPIN) from the paper “Learning to Reconstruct Missing Data from Spatiotemporal Graphs with Sparse Observations” (Marisca et al., NeurIPS 2022).

can_be_compiled: bool = True
forward(x: Any, u: Any, mask: Any, edge_index: Any, node_index: Any = None, target_nodes: Any = None) → Tuple[Any, List[Any]][source]
predict(x: Any, u: Any, mask: Any, edge_index: Any, node_index: Any = None, target_nodes: Any = None) → Any[source]
return_type

alias of tuple

class SPINHierarchicalModel(input_size: int, h_size: int, z_size: int, n_nodes: int, z_heads: int = 1, exog_size: int | None = None, output_size: int | None = None, n_layers: int = 5, eta: int = 3, message_layers: int = 1, reweigh: str | None = 'softmax', update_z_cross: bool = True, norm: bool = True, spatial_aggr: str = 'add')[source]

The Hierarchical Spatiotemporal Point Inference Network (SPIN-H) from the paper “Learning to Reconstruct Missing Data from Spatiotemporal Graphs with Sparse Observations” (Marisca et al., NeurIPS 2022).

can_be_compiled: bool = True
forward(x: Any, u: Any, mask: Any, edge_index: Any, node_index: Any = None, target_nodes: Any = None) → Tuple[Any, List[Any]][source]
predict(x: Any, u: Any, mask: Any, edge_index: Any, node_index: Any = None, target_nodes: Any = None) → Any[source]
return_type

alias of tuple

class STGNN(input_size: int, horizon: int, n_nodes: int = None, output_size: int = None, exog_size: int = 0, emb_size: int = 0, n_layers: int = 1, add_embedding_before: str | List[str] | None = 'encoding', **kwargs)[source]

Base class for SpatioTemporal Graph Neural Networks (STGNNs) following the template architecture of the paper “Taming Local Effects in Graph-based Spatiotemporal Forecasting” (Cini et al., NeurIPS 2023).

Subclasses construct the three stages by overriding build_encoder(), build_stmp_layer(), and build_decoder(). The map_*_args hooks adapt the model inputs to the interface of each constructed module; therefore subclasses need not implement forward(). emb is the selected node-embedding tensor, or None when embeddings are disabled.

Parameters:
  • input_size (int) – Number of input features.

  • horizon (int) – Forecasting horizon.

  • n_nodes (int, optional) – Number of global nodes. Required when emb_size is positive. (default: None)

  • output_size (int, optional) – Number of output features. (default: None)

  • exog_size (int, optional) – Number of encoder exogenous features. (default: 0)

  • emb_size (int, optional) – Size of each learnable node embedding. (default: 0)

  • n_layers (int, optional) – Number of STMP layers. (default: 1)

  • add_embedding_before (str or list[str], optional) – Retained for backwards compatibility. Embedding placement is determined by the custom encoder and decoder. (default: 'encoding')

  • **kwargs – Additional build-time configuration. Each item is stored as an attribute before the build methods are called.

build_decoder() → Module[source]

Build the decoder module.

Returns:

A decoder called with the arguments returned by map_decoder_args() and returning a forecast with shape [B, H, N, d_out].

Return type:

nn.Module

Raises:

NotImplementedError – Always. Subclasses must provide the decoder.

build_encoder() → Module[source]

Build the encoder module.

Returns:

An encoder called with the arguments returned by map_encoder_args() and returning hidden states with shape [B, T, N, d_h].

Return type:

nn.Module

Raises:

NotImplementedError – Always. Subclasses must provide the encoder.

build_stmp_layer(layer: int) → Module[source]

Build an STMP layer.

Parameters:

layer (int) – Zero-based index of the layer being constructed.

Returns:

An STMP layer called with the arguments returned by map_stmp_args() and returning hidden states.

Return type:

nn.Module

Raises:

NotImplementedError – Always. Subclasses must provide each layer.

forward(x: Any, edge_index: Any, edge_weight: Any | None = None, u: Any | None = None, v: Any | None = None, u_h: Any | None = None, node_idx: Any | None = None, **kwargs) → Any[source]

Compute a forecast following the encoder–STMP–decoder workflow.

Parameters:
  • x (Tensor) – Input sequence with shape [B, T, N, d_in].

  • edge_index (Adj) – Graph connectivity.

  • edge_weight (Tensor, optional) – Edge weights. (default: None)

  • u (Tensor, optional) – Encoder covariates with shape [B, T, N, d] or [B, T, d]. (default: None)

  • v (Tensor, optional) – Static attributes with shape [B, N, d] or [B, d]. (default: None)

  • u_h (Tensor, optional) – Future covariates with shape [B, H, N, d] or [B, H, d]. (default: None)

  • node_idx (Tensor, optional) – Global node indices used to select embeddings. (default: None)

  • **kwargs – Additional arguments available to the argument-mapping hooks.

Returns:

Forecast with shape [B, H, N, d_out].

Return type:

Tensor

Shapes:
  • x – \((B, T, N, F_{in})\), where \(B\) is the batch size, \(T\) is the input-window length, \(N\) is the number of nodes, and \(F_{in}\) is the input size.

  • edge_index – Graph connectivity, for example COO indices with shape \((2, E)\), where \(E\) is the number of edges.

  • edge_weight – Optional edge weights with shape \((E,)\).

  • u – Optional encoder covariates with shape \((B, T, N, F_u)\) or \((B, T, F_u)\).

  • v – Optional static attributes with shape \((B, N, F_v)\) or \((B, F_v)\).

  • u_h – Optional future covariates with shape \((B, H, N, F_c)\) or \((B, H, F_c)\), where \(H\) is the horizon.

  • node_idx – Optional global-node indices with shape \((N,)\).

  • return – \((B, H, N, F_{out})\), where \(F_{out}\) is the output size.

map_decoder_args(h: Any, u_h: Any | None = None, emb: Any | None = None, **kwargs) → Tuple[Tuple[object, ...], Dict[str, object]][source]

Map forward inputs to arguments for the decoder module.

Override this hook to select a subset of inputs, rename them as keyword arguments, or combine future covariates and embeddings before calling the decoder. The default mapping preserves the original positional interface and discards forward keyword arguments.

Parameters:
  • h (Tensor) – Final hidden states.

  • u_h (Tensor, optional) – Future covariates. (default: None)

  • emb (Tensor, optional) – Selected node embeddings. (default: None)

  • **kwargs – Additional arguments passed to forward().

Returns:

Positional and keyword arguments for decoder.

Return type:

tuple[tuple, dict]

map_encoder_args(x: Any, u: Any | None = None, v: Any | None = None, emb: Any | None = None, **kwargs) → Tuple[Tuple[object, ...], Dict[str, object]][source]

Map forward inputs to arguments for the encoder module.

Override this hook to select a subset of inputs, rename them as keyword arguments, or concatenate them before calling the encoder. The default mapping preserves the original positional interface and discards forward keyword arguments.

Parameters:
  • x (Tensor) – Input sequence.

  • u (Tensor, optional) – Encoder covariates. (default: None)

  • v (Tensor, optional) – Static attributes. (default: None)

  • emb (Tensor, optional) – Selected node embeddings. (default: None)

  • **kwargs – Additional arguments passed to forward().

Returns:

Positional and keyword arguments for encoder.

Return type:

tuple[tuple, dict]

map_stmp_args(h: Any, edge_index: Any, edge_weight: Any | None = None, *, layer: int, **kwargs) → Tuple[Tuple[object, ...], Dict[str, object]][source]

Map inputs to arguments for one STMP layer.

Override this hook to adapt the inputs for a particular layer. The default mapping forwards all forward() keyword arguments to every STMP layer, preserving the previous behavior.

Parameters:
  • h (Tensor) – Hidden states.

  • edge_index (Adj) – Graph connectivity.

  • edge_weight (Tensor, optional) – Edge weights. (default: None)

  • layer (int) – Zero-based STMP layer index.

  • **kwargs – Additional arguments passed to forward().

Returns:

Positional and keyword arguments for the STMP layer at layer.

Return type:

tuple[tuple, dict]

stmp(h: Any, edge_index: Any, edge_weight: Any | None = None, **kwargs) → Any[source]

Apply the constructed STMP stack.

Parameters:
  • h (Tensor) – Hidden states with shape [B, T, N, d_h].

  • edge_index (Adj) – Graph connectivity.

  • edge_weight (Tensor, optional) – Edge weights. (default: None)

  • **kwargs – Additional arguments available to map_stmp_args().

Returns:

Updated hidden states.

Return type:

Tensor

Shapes:
  • h – \((B, T, N, F_h)\), where \(B\) is the batch size, \(T\) is the input-window length, \(N\) is the number of nodes, and \(F_h\) is the hidden size.

  • edge_index – Graph connectivity, for example COO indices with shape \((2, E)\), where \(E\) is the number of edges.

  • edge_weight – Optional edge weights with shape \((E,)\).

  • return – \((B, T, N, F_h)\).

summary(show_workflow: bool = False) → str[source]

Return a schematic representation of the model architecture.

Parameters:

show_workflow (bool, optional) – Whether to append the common encoder–STMP–decoder tensor workflow. (default: False)

Returns:

An encoder–STMP–decoder architecture tree. The summary displays module types rather than their parameter values.

Return type:

str

class DisjointSTGNN(input_size: int, horizon: int, n_nodes: int = None, output_size: int = None, exog_size: int = 0, emb_size: int = 0, n_layers: int = 1, n_temporal_layers: int = 1, n_spatial_layers: int = 1, add_embedding_before: str | List[str] | None = 'encoding', **kwargs)[source]

STGNN with each STMP layer split into temporal then spatial stacks.

Parameters:
  • input_size (int) – Number of input features.

  • horizon (int) – Forecasting horizon.

  • n_nodes (int, optional) – Number of global nodes. (default: None)

  • output_size (int, optional) – Number of output features. (default: None)

  • exog_size (int, optional) – Number of encoder exogenous features. (default: 0)

  • emb_size (int, optional) – Size of node embeddings. (default: 0)

  • n_layers (int, optional) – Number of STMP layers. (default: 1)

  • n_temporal_layers (int, optional) – Number of temporal layers in each STMP layer. (default: 1)

  • n_spatial_layers (int, optional) – Number of spatial layers in each STMP layer. (default: 1)

  • add_embedding_before (str or list[str], optional) – Retained for backwards compatibility. (default: 'encoding')

  • **kwargs – Additional build-time configuration.

build_smp_layer(layer: int, inner_layer: int) → Module[source]

Build one spatial sublayer.

Parameters:
  • layer (int) – Zero-based outer STMP layer index.

  • inner_layer (int) – Zero-based spatial sublayer index.

Returns:

A spatial sublayer called with the arguments returned by map_smp_args().

Return type:

nn.Module

build_stmp_layer(layer: int) → Module[source]

Build the temporal and spatial sublayers for one STMP layer.

Parameters:

layer (int) – Zero-based outer STMP layer index.

Returns:

A registry containing the temporal and spatial sublayers.

Return type:

nn.Module

build_tmp_layer(layer: int, inner_layer: int) → Module[source]

Build one temporal sublayer.

Parameters:
  • layer (int) – Zero-based outer STMP layer index.

  • inner_layer (int) – Zero-based temporal sublayer index.

Returns:

A temporal sublayer called with the arguments returned by map_tmp_args().

Return type:

nn.Module

map_smp_args(h: Any, edge_index: Any, edge_weight: Any | None = None, *, layer: int, inner_layer: int, **kwargs) → Tuple[Tuple[object, ...], Dict[str, object]][source]

Map inputs to arguments for one spatial sublayer.

Parameters:
  • h (Tensor) – Hidden states.

  • edge_index (Adj) – Graph connectivity.

  • edge_weight (Tensor, optional) – Edge weights. (default: None)

  • layer (int) – Zero-based outer STMP layer index.

  • inner_layer (int) – Zero-based spatial sublayer index.

  • **kwargs – Additional arguments passed to forward().

Returns:

Positional and keyword arguments for the spatial sublayer.

Return type:

tuple[tuple, dict]

map_tmp_args(h: Any, *, layer: int, inner_layer: int, **kwargs) → Tuple[Tuple[object, ...], Dict[str, object]][source]

Map inputs to arguments for one temporal sublayer.

Parameters:
  • h (Tensor) – Hidden states.

  • layer (int) – Zero-based outer STMP layer index.

  • inner_layer (int) – Zero-based temporal sublayer index.

  • **kwargs – Additional arguments passed to forward().

Returns:

Positional and keyword arguments for the temporal sublayer.

Return type:

tuple[tuple, dict]

smp(h: Any, edge_index: Any, edge_weight: Any | None = None, *, layer: int, inner_layer: int, **kwargs) → Any[source]

Apply one constructed spatial sublayer.

Parameters:
  • h (Tensor) – Hidden states.

  • edge_index (Adj) – Graph connectivity.

  • edge_weight (Tensor, optional) – Edge weights. (default: None)

  • layer (int) – Outer STMP layer index.

  • inner_layer (int) – Spatial sublayer index.

  • **kwargs – Additional arguments available to map_smp_args().

Returns:

Updated hidden states.

Return type:

Tensor

Shapes:
  • h – \((B, T, N, F_h)\), where \(B\) is the batch size, \(T\) is the input-window length, \(N\) is the number of nodes, and \(F_h\) is the hidden size.

  • edge_index – Graph connectivity, for example COO indices with shape \((2, E)\), where \(E\) is the number of edges.

  • edge_weight – Optional edge weights with shape \((E,)\).

  • return – \((B, T, N, F_h)\).

stmp(h: Any, edge_index: Any, edge_weight: Any | None = None, **kwargs) → Any[source]

Apply each temporal stack followed by its spatial stack.

Parameters:
  • h (Tensor) – Hidden states.

  • edge_index (Adj) – Graph connectivity.

  • edge_weight (Tensor, optional) – Edge weights. (default: None)

  • **kwargs – Additional arguments available to map_tmp_args() and map_smp_args().

Returns:

Updated hidden states.

Return type:

Tensor

Shapes:
  • h – \((B, T, N, F_h)\), where \(B\) is the batch size, \(T\) is the input-window length, \(N\) is the number of nodes, and \(F_h\) is the hidden size.

  • edge_index – Graph connectivity, for example COO indices with shape \((2, E)\), where \(E\) is the number of edges.

  • edge_weight – Optional edge weights with shape \((E,)\).

  • return – \((B, T, N, F_h)\).

tmp(h: Any, *, layer: int, inner_layer: int, **kwargs) → Any[source]

Apply one constructed temporal sublayer.

Parameters:
  • h (Tensor) – Hidden states.

  • layer (int) – Outer STMP layer index.

  • inner_layer (int) – Temporal sublayer index.

  • **kwargs – Additional arguments passed to forward().

Returns:

Updated hidden states.

Return type:

Tensor

Shapes:
  • h – \((B, T, N, F_h)\), where \(B\) is the batch size, \(T\) is the input-window length, \(N\) is the number of nodes, and \(F_h\) is the hidden size.

  • return – \((B, T, N, F_h)\).

class TimeThenSpace(input_size: int, horizon: int, n_nodes: int = None, output_size: int = None, exog_size: int = 0, emb_size: int = 0, n_temporal_layers: int = 1, n_spatial_layers: int = 1, add_embedding_before: str | List[str] | None = 'encoding', **kwargs)[source]

Disjoint STGNN composed from one temporal and multiple spatial modules.

Parameters:
  • input_size (int) – Number of input features.

  • horizon (int) – Forecasting horizon.

  • n_nodes (int, optional) – Number of global nodes. (default: None)

  • output_size (int, optional) – Number of output features. (default: None)

  • exog_size (int, optional) – Number of encoder exogenous features. (default: 0)

  • emb_size (int, optional) – Size of node embeddings. (default: 0)

  • n_temporal_layers (int, optional) – Number of temporal layers in each STMP layer. (default: 1)

  • n_spatial_layers (int, optional) – Number of spatial layers in each STMP layer. (default: 1)

  • add_embedding_before (str or list[str], optional) – Retained for backwards compatibility. (default: 'encoding')

  • **kwargs – Additional build-time configuration.

Temporal Models

ARModel

Simple univariate linear AR model for multistep forecasting.

VARModel

A simple VAR model for multistep forecasting.

RNNModel

Simple RNN for multistep forecasting.

FCRNNModel

A simple fully connected RNN for multistep forecasting that simply flattens data along the spatial dimension.

TCNModel

A simple Causal Dilated Temporal Convolutional Network for multistep forecasting.

TransformerModel

A Transformer from the paper "Attention Is All You Need" (Vaswani et al., NeurIPS 2017) for multistep time series forecasting.

RNNImputerModel

Fill the blanks with 1-step-ahead predictions of a recurrent network.

BiRNNImputerModel

Fill the blanks with 1-step-ahead predictions of a bidirectional recurrent neural network.

STIDModel

The Spatial-Temporal Identity (STID) model from the paper "Spatial-Temporal Identity: A Simple yet Effective Baseline for Multivariate Time Series Forecasting" (Shao et al., CIKM 2022 short paper).

class ARModel(input_size: int, temporal_order: int, output_size: int, horizon: int, exog_size: int = 0, bias: bool = True)[source]

Simple univariate linear AR model for multistep forecasting.

Parameters:
  • input_size (int) – Size of the input.

  • temporal_order (int) – Number of units in the recurrent cell.

  • output_size (int) – Number of output channels.

  • exog_size (int) – Size of the exogenous variables.

  • horizon (int) – Forecasting horizon.

can_be_compiled: bool = True
forward(x: Tensor, u: Tensor | None = None) → Tensor[source]
return_type

alias of Tensor

class VARModel(input_size: int, temporal_order: int, output_size: int, horizon: int, n_nodes: int, exog_size: int = 0, bias: bool = True)[source]

A simple VAR model for multistep forecasting.

Parameters:
  • input_size (int) – Size of the input.

  • n_nodes (int) – Number of nodes.

  • temporal_order (int) – Number of units in the recurrent cell.

  • output_size (int) – Number of output channels.

  • exog_size (int) – Size of the exogenous variables.

  • horizon (int) – Forecasting horizon.

forward(x: Tensor, u: Tensor | None = None) → Tensor[source]
class RNNModel(input_size: int, output_size: int, horizon: int, exog_size: int = 0, hidden_size: int = 32, ff_size: int = 64, rec_layers: int = 1, ff_layers: int = 1, rec_dropout: float = 0.0, ff_dropout: float = 0.0, cell_type: str = 'gru', activation: str = 'relu')[source]

Simple RNN for multistep forecasting.

Parameters:
  • input_size (int) – Size of the input.

  • hidden_size (int) – Number of units in the recurrent cell.

  • output_size (int) – Number of output channels.

  • ff_size (int) – Number of units in the link predictor.

  • exog_size (int) – Size of the exogenous variables.

  • rec_layers (int) – Number of RNN layers.

  • ff_layers (int) – Number of hidden layers in the decoder.

  • rec_dropout (float, optional) – Dropout probability in the RNN encoder.

  • ff_dropout (float, optional) – Dropout probability int the GCN decoder.

  • horizon (int) – Forecasting horizon.

  • cell_type (str, optional) – Type of cell that should be use (options: [gru, lstm]). (default: gru)

  • activation (str, optional) – Activation function. (default: relu)

can_be_compiled: bool = False
forward(x: Tensor, u: Tensor | None = None) → Tensor[source]
return_type

alias of Tensor

class FCRNNModel(input_size: int, output_size: int, horizon: int, n_nodes: int, exog_size: int | None = None, hidden_size: int = 32, ff_size: int = 64, rec_layers: int = 1, ff_layers: int = 1, rec_dropout: float = 0.0, ff_dropout: float = 0.0, cell_type: str = 'gru', activation: str = 'relu')[source]

A simple fully connected RNN for multistep forecasting that simply flattens data along the spatial dimension.

Parameters:
  • input_size (int) – Size of the input.

  • hidden_size (int) – Number of units in the recurrent cell.

  • output_size (int) – Number of output channels.

  • ff_size (int) – Number of units in the link predictor.

  • exog_size (int) – Size of the exogenous variables.

  • rec_layers (int) – Number of RNN layers.

  • ff_layers (int) – Number of hidden layers in the decoder.

  • rec_dropout (float, optional) – Dropout probability in the RNN encoder.

  • ff_dropout (float, optional) – Dropout probability int the GCN decoder.

  • horizon (int) – Forecasting horizon.

  • cell_type (str, optional) – Type of cell that should be use (options: [gru, lstm]). (default: gru)

  • activation (str, optional) – Activation function. (default: relu)

can_be_compiled: bool = False
forward(x: Tensor, u: Tensor | None = None) → Tensor[source]
class TCNModel(input_size: int, output_size: int, horizon: int, exog_size: int = 0, hidden_size: int = 32, ff_size: int = 32, kernel_size: int = 2, n_layers: int = 4, n_convs_layer: int = 2, readout_kernel_size: int = 1, dilation: int = 2, gated: bool = False, resnet: bool = True, norm: str = 'batch', dropout: float = 0.0, activation: str = 'relu')[source]

A simple Causal Dilated Temporal Convolutional Network for multistep forecasting. Learned temporal embeddings are pooled together using dynamics weights.

Parameters:
  • input_size (int) – Number of features of the input sample.

  • output_size (int) – Number of output channels.

  • horizon (int) – Number of future time steps to forecast.

  • exog_size (int) – Number of features of the input covariate, if any. (default: 0)

  • hidden_size (int) – Number of hidden units. (default: 32)

  • ff_size (int) – Number of units in the hidden layers of the decoder. (default: 32)

  • kernel_size (int) – Size of the convolutional kernel. (default: 2)

  • n_layers (int) – Number of TCN blocks. (default: 4)

  • n_convs_layer (int) – Number of temporal convolutions in each layer. (default: 2)

  • readout_kernel_size (int) – Width of the readout kernel size. (default: 1)

  • dilation (int) – Dilation coefficient of the convolutional kernel. (default: 2)

  • gated (bool) – If True, then the gated_tanh() activation function is used. (default: False)

  • resnet (bool) – If True, then residual connections are used. (default: True)

  • norm (str) – Normalization strategy. (default: 'batch')

  • dropout (float) – Dropout probability. (default: 0)

  • activation (str) – Activation function. (default: 'relu)

can_be_compiled: bool = True
forward(x: Tensor, u: Tensor | None = None) → Tensor[source]
return_type

alias of Tensor

class TransformerModel(input_size: int, output_size: int, horizon: int, exog_size: int = 0, hidden_size: int = 32, ff_size: int = 32, n_heads: int = 1, n_layers: int = 1, dropout: float = 0.0, axis: str = 'time', activation: str = 'elu')[source]

A Transformer from the paper “Attention Is All You Need” (Vaswani et al., NeurIPS 2017) for multistep time series forecasting.

Parameters:
  • input_size (int) – Input size.

  • hidden_size (int) – Dimension of the learned representations.

  • output_size (int) – Dimension of the output.

  • ff_size (int) – Units in the MLP after self attention.

  • exog_size (int) – Dimension of the exogenous variables.

  • horizon (int) – Number of forecasting steps.

  • n_heads (int, optional) – Number of parallel attention heads.

  • n_layers (int, optional) – Number of layers.

  • dropout (float, optional) – Dropout probability.

  • axis (str, optional) – Dimension on which to apply attention to update the representations. Can be either, ‘time’, ‘nodes’, or ‘both’. (default: 'time')

  • activation (str, optional) – Activation function.

can_be_compiled: bool = True
forward(x: Tensor, u: Tensor | None = None) → Tensor[source]
return_type

alias of Tensor

class RNNImputerModel(input_size: int, hidden_size: int = 64, exog_size: int = 0, cell: str = 'gru', concat_mask: bool = True, fully_connected: bool = False, n_nodes: int | None = None, detach_input: bool = False, n_layers: int = 1, cat_states_layers: bool = False)[source]

Fill the blanks with 1-step-ahead predictions of a recurrent network.

\[\bar{x}_{t} = m_{t} \cdot x_{t} + (1 - m_{t}) \cdot \hat{x}_{t}\]
Parameters:
  • input_size (int) – Number of features of the input sample.

  • hidden_size (int) – Number of hidden units. (default: 64)

  • exog_size (int) – Number of features of the input covariate, if any. (default: 0)

  • cell (str) – Type of recurrent cell to be used, one of [gru, lstm]. (default: gru)

  • concat_mask (bool) – If True, then the input tensor is concatenated to the mask when fed to the RNN cell. (default: True)

  • fully_connected (bool) – If True, then node and feature dimensions are flattened together. (default: False)

  • n_nodes (int, optional) – The number of nodes in the input sample, to be provided in case fully_connected is True. (default: None)

  • detach_input (bool) – If True, call detach() on predictions before they are used to fill the gaps, breaking the error backpropagation. (default: False)

  • n_layers (int, optional) – Number of hidden layers. (default: 1)

  • cat_states_layers (bool) – If True, then the states of the RNN are concatenated together. (default: False)

can_be_compiled: bool = True
forward(x: Any, mask: Any, u: Any | None = None, return_hidden: bool = False) → Any | list[source]
predict(x: Any, mask: Any, u: Any | None = None) → Any[source]
class BiRNNImputerModel(input_size: int, hidden_size: int = 64, exog_size: int = 0, cell: str = 'gru', concat_mask: bool = True, fully_connected: bool = False, n_nodes: int | None = None, detach_input: bool = False, n_layers: int = 1, cat_states_layers: bool = False, dropout: float = 0.0)[source]

Fill the blanks with 1-step-ahead predictions of a bidirectional recurrent neural network.

Parameters:
  • input_size (int) – Number of features of the input sample.

  • hidden_size (int) – Number of hidden units. (default: 64)

  • exog_size (int) – Number of features of the input covariate, if any. (default: 0)

  • cell (str) – Type of recurrent cell to be used, one of [gru, lstm]. (default: gru)

  • concat_mask (bool) – If True, then the input tensor is concatenated to the mask when fed to the RNN cell. (default: True)

  • fully_connected (bool) – If True, then node and feature dimensions are flattened together. (default: False)

  • n_nodes (int, optional) – The number of nodes in the input sample, to be provided in case fully_connected is True. (default: None)

  • detach_input (bool) – If True, call detach() on predictions before they are used to fill the gaps, breaking the error backpropagation. (default: False)

  • n_layers (int, optional) – Number of hidden layers. (default: 1)

  • return_previous_state (bool) – If True, then the returned states are shifted one-step behind the imputations. (default: True)

  • cat_states_layers (bool) – If True, then the states of the RNN are concatenated together. (default: False)

  • dropout (float, optional) – Dropout probability in the decoder. (default: 0.)

can_be_compiled: bool = True
forward(x: Any, mask: Any, u: Any | None = None, return_hidden: bool = False, return_predictions: bool = True) → Any | list[source]
predict(x: Any, mask: Any, u: Any | None = None) → Any[source]
return_type

alias of list

class STIDModel(input_size: int, n_nodes: int, window: int, horizon: int, n_exog_emb: Sequence[int] | int = None, output_size: int = None, hidden_size: int = 32, n_layers: int = 3, dropout: float = 0.15)[source]

The Spatial-Temporal Identity (STID) model from the paper “Spatial-Temporal Identity: A Simple yet Effective Baseline for Multivariate Time Series Forecasting” (Shao et al., CIKM 2022 short paper).

Parameters:
  • input_size (int) – Size of the input.

  • n_nodes (int) – Number of nodes.

  • window (int) – Size of the input window (this model cannot process sequences of variable length).

  • horizon (int) – Forecasting steps.

  • n_exog_emb (int or list) – Number of embeddings to be set for optional exogenous variables. Can be an integer or a list of integers where each element is the cardinality of each related covariate. (default: None)

  • output_size (int) – Size of the output. If None, then defaults to input_size. (default: None)

  • hidden_size (int) – Number of hidden units in each hidden layer. (default: 32)

  • n_layers (int) – Number of layers in the MLP encoder. (default: 3)

  • dropout (float) – Dropout probability in MLP hidden layers. (default: 0.15)

can_be_compiled: bool = True
forward(x: Any, u: Any | None = None) → Any[source]
Parameters:
  • x (Tensor) – The input data.

  • u (Tensor, optional) – Optional index of exogenous variables. Each channel contains the index for the corresponding embeddings. If u has a time dimension, then it must be of the same length as x and equal to self.window; otherwise, it must be synchronized with the last step of x. (default: None)

Shapes:
  • x – \((B, T, N, F)\), where \(B\) is the batch size, \(T\) is the number of time steps in the lookback window, \(N\) is the number of nodes, and \(F\) is the number of features/channels.

  • u – \((B, [T,] F)\), where \(B\) is the batch size, \(T\) is the (optional) number of time steps in the lookback window, \(F\) is the number of covariates.

reset_parameters()[source]

Reset the parameters of the model.