timeseries

package
v1.8.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 20, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

README

timeseries — Time-Series Forecasting Models

This package provides three time-series forecasting architectures built on ztensor:

Model Paper Use Case
N-BEATS Neural Basis Expansion Analysis Univariate forecasting with interpretable trend/seasonality decomposition
PatchTST Patch Time-Series Transformer Univariate/multivariate forecasting via patch-based attention
TFT Temporal Fusion Transformer Multi-horizon probabilistic forecasting with static/temporal covariates

Training Patterns

The timeseries models return rich, domain-specific outputs that are essential for interpretability — N-BEATS produces per-stack decompositions (trend vs. seasonality), and TFT provides quantile forecasts with variable importance weights. These outputs do not fit naturally into the single-tensor training.Model[T] interface.

For full control over the training loop and access to all model outputs, use the models directly:

model, _ := timeseries.NewNBEATS(config, engine, ops)

for epoch := range epochs {
    out, _ := model.Forward(ctx, batchInput)

    // Access decomposition for interpretability loss terms.
    trendForecast := out.StackForecasts[0]
    seasonForecast := out.StackForecasts[1]

    // Compute loss on out.Forecast, backpropagate manually.
}
Trainer Integration (via Adapter)

When training.Trainer[T] integration is needed (e.g., to reuse optimizer and scheduling infrastructure), use the adapter wrappers:

model, _ := timeseries.NewNBEATS(config, engine, ops)
adapter, _ := timeseries.NewNBEATSAdapter(model)

// adapter satisfies training.Model[float32]
trainer := training.NewTrainer(adapter, optimizer, lossFn)
trainer.Train(data)

Available adapters:

Adapter Wraps Forward Input Forward Output
NBEATSAdapter *NBEATS [batch, inputLen] [batch, outputLen] (forecast only)
PatchTSTAdapter *PatchTST [batch, inputLen] or [batch, channels, inputLen] [batch, outputDim] or [batch, channels, outputDim]
TFTAdapter *TFT Two tensors: static [batch, features], time [batch, seqLen, features] [batch, nHorizons * nQuantiles]

Trade-offs of the adapter approach:

  • The adapters extract only the primary forecast tensor, discarding decomposition and interpretability outputs. Use standalone loops when these are needed.
  • Backward() is not implemented on the adapters. The training infrastructure should use engine-level autograd or numerical gradients.
  • All adapters expose Parameters() for optimizer integration (weight updates, learning rate scheduling, gradient clipping).
When to Use Which
Scenario Approach
Custom loss with decomposition terms Standalone
Quantile loss with variable importance Standalone
Standard MSE/MAE training with existing Trainer Adapter
Hyperparameter search with Trainer infrastructure Adapter

Documentation

Overview

Package timeseries provides time-series forecasting models built on ztensor.

Models in this package accept static covariates and temporal features, producing multi-horizon forecasts with optional quantile estimates.

Package timeseries provides time-series forecasting models built on ztensor.

Stability: alpha

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func QuantileLoss

func QuantileLoss(predicted [][]float64, targets []float64, quantiles []float64) (float64, error)

QuantileLoss computes the asymmetric quantile loss (pinball loss) for a set of predictions. predicted has shape [nHorizons][nQuantiles], targets has shape [nHorizons].

Types

type Forecast

type Forecast struct {
	Horizons  []float64             // point forecasts per horizon
	Quantiles map[float64][]float64 // quantile -> values per horizon (nil if no quantiles)
}

Forecast represents a multi-horizon forecast with optional quantile estimates.

type NBEATS

type NBEATS struct {
	// contains filtered or unexported fields
}

NBEATS implements the N-BEATS (Neural Basis Expansion Analysis for Interpretable Time Series Forecasting) architecture.

The model consists of stacks of blocks. Each block applies FC layers to produce theta parameters, which are expanded through a basis function (polynomial for trend, Fourier for seasonality, learned for generic) to produce backcast and forecast signals. Double residual stacking subtracts the backcast from the input and accumulates forecasts.

func NewNBEATS

func NewNBEATS(config NBEATSConfig, engine compute.Engine[float32], ops numeric.Arithmetic[float32]) (*NBEATS, error)

NewNBEATS creates a new N-BEATS model with the given configuration.

func (*NBEATS) Decompose

Decompose runs forward and returns the per-stack decomposition of the forecast. This is useful for interpretable forecasting: separating trend from seasonality.

func (*NBEATS) Forward

Forward runs the N-BEATS forward pass. Input x has shape [batch, inputLen]. Returns NBEATSOutput with forecast of shape [batch, outputLen] and per-stack decomposition.

type NBEATSAdapter

type NBEATSAdapter struct {
	Model *NBEATS
	// contains filtered or unexported fields
}

NBEATSAdapter wraps an NBEATS model to satisfy training.Model[float32]. The Forward method extracts the Forecast tensor from NBEATSOutput, discarding per-stack decomposition. Use NBEATS.Forward directly when interpretability (stack-level forecasts/backcasts) is needed.

func NewNBEATSAdapter

func NewNBEATSAdapter(m *NBEATS) (*NBEATSAdapter, error)

NewNBEATSAdapter creates a trainable adapter for the given NBEATS model.

func (*NBEATSAdapter) Backward

Backward is not implemented for timeseries models. Timeseries models use standalone training loops with numerical or engine-level gradient computation rather than manual backward passes.

func (*NBEATSAdapter) Forward

Forward runs the NBEATS forward pass and returns the forecast tensor. Expects a single input tensor of shape [batch, inputLen].

func (*NBEATSAdapter) Parameters

func (a *NBEATSAdapter) Parameters() []*graph.Parameter[float32]

Parameters returns all trainable parameters from the NBEATS model.

type NBEATSConfig

type NBEATSConfig struct {
	InputLength     int         // length of the lookback window
	OutputLength    int         // forecast horizon
	StackTypes      []StackType // types of stacks (e.g., [StackTrend, StackSeasonality])
	NBlocksPerStack int         // number of blocks in each stack
	HiddenDim       int         // hidden dimension of FC layers in each block
	NHarmonics      int         // number of Fourier harmonics for seasonality stacks
}

NBEATSConfig holds the configuration for an NBEATS model.

type NBEATSOutput

type NBEATSOutput struct {
	Forecast       *tensor.TensorNumeric[float32]   // [batch, outputLen]
	StackForecasts []*tensor.TensorNumeric[float32] // per-stack forecasts for decomposition
	StackBackcasts []*tensor.TensorNumeric[float32] // per-stack backcasts
}

NBEATSOutput holds the result of an N-BEATS forward pass.

type PatchTST

type PatchTST struct {
	// contains filtered or unexported fields
}

PatchTST implements the Patch Time-Series Transformer.

func NewPatchTST

func NewPatchTST(config PatchTSTConfig, engine compute.Engine[float32], ops numeric.Arithmetic[float32]) (*PatchTST, error)

NewPatchTST creates a new PatchTST model with the given configuration.

func (*PatchTST) Forward

Forward runs the PatchTST forward pass on input time series data. input shape: [batch, channels, input_length] for multivariate, or [batch, input_length] for univariate (treated as 1 channel). Returns predictions of shape [batch, channels, output_dim] if channel_independent, or [batch, output_dim] if not channel_independent.

func (*PatchTST) Predict

func (m *PatchTST) Predict(input [][]float64) ([][]float64, error)

Predict runs inference on multivariate time series data using float64 slices. input[channel]time has one sub-slice per channel, each of length InputLength. Returns output[channel][horizon] with OutputDim predictions per channel. For single-channel input, pass a single sub-slice.

type PatchTSTAdapter

type PatchTSTAdapter struct {
	Model *PatchTST
	// contains filtered or unexported fields
}

PatchTSTAdapter wraps a PatchTST model to satisfy training.Model[float32]. PatchTST.Forward already returns a tensor, so the adapter is a thin pass-through.

func NewPatchTSTAdapter

func NewPatchTSTAdapter(m *PatchTST) (*PatchTSTAdapter, error)

NewPatchTSTAdapter creates a trainable adapter for the given PatchTST model.

func (*PatchTSTAdapter) Backward

Backward is not implemented for timeseries models.

func (*PatchTSTAdapter) Forward

Forward runs the PatchTST forward pass. Expects a single input tensor of shape [batch, input_length] or [batch, channels, input_length].

func (*PatchTSTAdapter) Parameters

func (a *PatchTSTAdapter) Parameters() []*graph.Parameter[float32]

Parameters returns all trainable parameters from the PatchTST model.

type PatchTSTConfig

type PatchTSTConfig struct {
	InputLength        int  // length of input time series
	PatchLength        int  // length of each patch
	Stride             int  // stride between patches
	DModel             int  // transformer hidden dimension
	NHeads             int  // number of attention heads
	NLayers            int  // number of transformer encoder layers
	OutputDim          int  // output prediction dimension
	ChannelIndependent bool // process each channel independently through same transformer
}

PatchTSTConfig holds configuration for a PatchTST model.

func (PatchTSTConfig) NumPatches

func (c PatchTSTConfig) NumPatches() int

NumPatches returns the number of patches produced by the patching configuration.

type StackType

type StackType int

StackType identifies the type of basis expansion used in an N-BEATS stack.

const (
	// StackTrend uses polynomial basis expansion for trend modeling.
	StackTrend StackType = iota
	// StackSeasonality uses Fourier basis expansion for seasonal patterns.
	StackSeasonality
	// StackGeneric uses learned linear projections as basis functions.
	StackGeneric
)

func (StackType) String

func (s StackType) String() string

String returns the string representation of a StackType.

type TFT

type TFT struct {
	// contains filtered or unexported fields
}

TFT implements the Temporal Fusion Transformer for multi-horizon probabilistic forecasting.

func NewTFT

func NewTFT(config TFTConfig, engine compute.Engine[float32], ops numeric.Arithmetic[float32]) (*TFT, error)

NewTFT creates a new Temporal Fusion Transformer with the given configuration.

func (*TFT) Predict

func (m *TFT) Predict(staticFeatures []float64, timeFeatures [][]float64) ([][]float64, error)

Predict runs the TFT forward pass and returns multi-horizon quantile forecasts. staticFeatures has shape [numStaticFeatures]. timeFeatures has shape [seqLen][numTimeFeatures]. Returns a slice of shape [nHorizons][nQuantiles].

func (*TFT) VariableSelectionWeights

func (m *TFT) VariableSelectionWeights(featureType string, features []float64) ([]float64, error)

VariableSelectionWeights returns the softmax variable importance weights for the static or time variable selection network. This enables interpretability — a key feature of TFT. Pass "static" or "time" as featureType.

type TFTAdapter

type TFTAdapter struct {
	Model *TFT
	// contains filtered or unexported fields
}

TFTAdapter wraps a TFT model to satisfy training.Model[float32]. The Forward method expects two inputs: static features [batch, numStaticFeatures] and time features [batch, seqLen, numTimeFeatures]. It processes each batch element individually through TFT.Predict and returns the stacked output.

func NewTFTAdapter

func NewTFTAdapter(m *TFT) (*TFTAdapter, error)

NewTFTAdapter creates a trainable adapter for the given TFT model.

func (*TFTAdapter) Backward

Backward is not implemented for timeseries models.

func (*TFTAdapter) Forward

Forward runs the TFT forward pass. Expects two inputs: static features [batch, numStaticFeatures] and time features [batch, seqLen, numTimeFeatures]. Returns [batch, nHorizons * nQuantiles].

func (*TFTAdapter) Parameters

func (a *TFTAdapter) Parameters() []*graph.Parameter[float32]

Parameters returns all trainable parameters from the TFT model.

type TFTConfig

type TFTConfig struct {
	NumStaticFeatures int
	NumTimeFeatures   int
	DModel            int
	NHeads            int
	NHorizons         int
	Quantiles         []float64
}

TFTConfig holds the configuration for a Temporal Fusion Transformer.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL