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()andadd_argparse_args()allow to automatically add to anArgumentParserthe 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 theforward()function for only inference purposes (e.g., removing outputs used only for auxiliary tasks during training).the parameter
return_typespecifies which the return type of the forward function (Tensor,listordict).the class attribute
can_be_compiledindicates whether the model is covered by TSL’s full-graphcompile()tests.
- classmethod get_model_signature() dict[source]¶
Get signature of the model’s
BaseModel’s__init__function.
- classmethod filter_model_args_(mapping: dict)[source]¶
Remove from
mappingall the keys that are not inBaseModel’s__init__function.
- classmethod model_excluded_args() Set[source]¶
Set of arguments of
__init__()to be excluded when adding model’s args to anArgumentParser(seeadd_model_specific_args()).
- classmethod add_model_specific_args(parser: ArgumentParser)[source]¶
Adds to the
ArgumentParserparserthe 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 bymodel_excluded_args().
- classmethod add_argparse_args(parser: ArgumentParser, exclude_args: Set | None = None)[source]¶
Adds to the
ArgumentParserparserall the parameters of the__init__()method (with typing and default values).
Spatiotemporal Models¶
The Diffusion Convolutional Recurrent Neural Network from the paper "Diffusion Convolutional Recurrent Neural Network: Data-Driven Traffic Forecasting" (Li et al., ICLR 2018). |
|
The Graph WaveNet model from the paper "Graph WaveNet for Deep Spatial-Temporal Graph Modeling" (Wu et al., IJCAI 2019). |
|
Simple time-then-space model with an MLP with residual connections as encoder (flattened time dimension) and a gated GN decoder with node identification. |
|
Simple time-then-space model. |
|
Spatiotemporal GNN with interleaved temporal and spatial diffusion convolutions. |
|
The EvolveGCN model from the paper "EvolveGCN: Evolving Graph Convolutional Networks for Dynamic Graphs" (Pereja et al., AAAI 2020). |
|
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). |
|
The Adaptive Graph Convolutional Recurrent Network from the paper "Adaptive Graph Convolutional Recurrent Network for Traffic Forecasting" (Bai et al., NeurIPS 2020). |
|
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). |
|
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). |
|
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). |
|
STGNN with each STMP layer split into temporal then spatial stacks. |
|
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')
- 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_adjacencyisTrue. (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)
- 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.
- 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.
- 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.
- 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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- 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.
- 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.
- 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)
- 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)
- forward(x: Any, edge_index: Any, edge_weight: Any = None, mask: Any = None, u: Any = None) list[source]¶
- 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).
- forward(x: Any, u: Any, mask: Any, edge_index: Any, node_index: Any = None, target_nodes: Any = None) Tuple[Any, List[Any]][source]¶
- 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).
- forward(x: Any, u: Any, mask: Any, edge_index: Any, node_index: Any = None, target_nodes: Any = None) Tuple[Any, List[Any]][source]¶
- 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(), andbuild_decoder(). Themap_*_argshooks adapt the model inputs to the interface of each constructed module; therefore subclasses need not implementforward().embis the selected node-embedding tensor, orNonewhen 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_sizeis 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:
- Returns:
Positional and keyword arguments for
decoder.- Return type:
- 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:
- Returns:
Positional and keyword arguments for
encoder.- Return type:
- 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:
- Returns:
Positional and keyword arguments for the STMP layer at
layer.- Return type:
- 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)\).
- 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:
- 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:
- 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:
- Returns:
Positional and keyword arguments for the spatial sublayer.
- Return type:
- 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.
- 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()andmap_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:
- 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¶
Simple univariate linear AR model for multistep forecasting. |
|
A simple VAR model for multistep forecasting. |
|
Simple RNN for multistep forecasting. |
|
A simple fully connected RNN for multistep forecasting that simply flattens data along the spatial dimension. |
|
A simple Causal Dilated Temporal Convolutional Network for multistep forecasting. |
|
A Transformer from the paper "Attention Is All You Need" (Vaswani et al., NeurIPS 2017) for multistep time series forecasting. |
|
Fill the blanks with 1-step-ahead predictions of a recurrent network. |
|
Fill the blanks with 1-step-ahead predictions of a bidirectional recurrent neural network. |
|
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:
- 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:
- 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)
- 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)
- 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 thegated_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)
- 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.
- 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_connectedisTrue. (default:None)detach_input (bool) – If
True, calldetach()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)
- 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_connectedisTrue. (default:None)detach_input (bool) – If
True, calldetach()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.)
- 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 toinput_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)
- 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
uhas a time dimension, then it must be of the same length asxand equal toself.window; otherwise, it must be synchronized with the last step ofx. (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.