Skip to main content

Timeseries Learning Library for PyTorch.

Project description

PyPI Version Docs Status

pytorch_timeseries

An all-in-one deep learning library for time series research. Full documentation.

  • Datasets downloaded automatically
  • Easy to extend with your own model
  • Highly customizable pipeline
  • One-command experiment runner

Installation

pip install torch-timeseries

Python 3.8+ required.

Two Ways to Use

Way 1 — Custom pipeline (bring your own training loop)

Import a dataset and dataloader, then write your own training logic. Full control over loss, optimizer, and batch handling.

import torch
import torch.nn as nn

from torch_timeseries.dataset import ETTh1
from torch_timeseries.scaler import StandardScaler
from torch_timeseries.dataloader.v2 import (
    ForecastDataModule, WindowConfig, SplitConfig, LoaderConfig
)

# Dataset is downloaded automatically on first use.
dataset = ETTh1("./data")

dm = ForecastDataModule(
    dataset=dataset,
    scaler=StandardScaler(),
    window=WindowConfig(window=96, horizon=1, steps=96),
    # ETTh1 academic split: 12 months train, 4 months val, 4 months test.
    # If split is omitted, the datamodule uses this dataset default.
    split=SplitConfig(borders=(12 * 30 * 24, 16 * 30 * 24, 20 * 30 * 24)),
    loader=LoaderConfig(batch_size=32),
)

class LinearForecaster(nn.Module):
    """Input: (batch, input_window, features). Output: (batch, pred_len, features)."""

    def __init__(self, input_window: int, pred_len: int):
        super().__init__()
        self.proj = nn.Linear(input_window, pred_len)

    def forward(self, x):
        # x: (B, 96, C) -> (B, C, 96) -> (B, C, 96) -> (B, 96, C)
        return self.proj(x.transpose(1, 2)).transpose(1, 2)

device = "cuda" if torch.cuda.is_available() else "cpu"
model = LinearForecaster(input_window=96, pred_len=96).to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
loss_fn = nn.MSELoss()

for epoch in range(1):
    model.train()
    for batch in dm.train_loader:
        # Each batch is a TSBatch.
        x = batch.x.float().to(device)  # (B, 96, num_features)
        y = batch.y.float().to(device)  # (B, 96, num_features)

        optimizer.zero_grad()
        pred = model(x)                 # (B, 96, num_features)
        loss = loss_fn(pred, y)
        loss.backward()
        optimizer.step()

Use this pattern when you need a non-standard training loop, custom loss, or are prototyping a new architecture.


Way 2 — Default training paradigm (built-in or registered models)

Use the built-in experiment runner. Pick a model, task, and dataset — the library handles data loading, training, evaluation, and result saving.

This path works for built-in models and for your own models registered with the default experiment classes.

Architecture Direction

New development targets the v2 DataModule API and the high-level Experiment entrypoint. Legacy dataloaders and direct experiment classes remain available for compatibility, but new task/model features should use named batches, Task DataModules, and result records.

Register Custom Models

To use the default training loop with your own model, subclass the task experiment class, define _init_model, then register it.

For forecasting, the model should read batch_x with shape (batch, windows, num_features) and return predictions with shape (batch, pred_len, num_features).

from dataclasses import dataclass

import torch
import torch.nn as nn

from torch_timeseries import Experiment, register_model
from torch_timeseries.experiments import ForecastExp


class MyForecastNet(nn.Module):
    """Input: (B, seq_len, C). Output: (B, pred_len, C)."""

    def __init__(self, seq_len: int, pred_len: int):
        super().__init__()
        self.proj = nn.Linear(seq_len, pred_len)

    def forward(self, x):
        return self.proj(x.transpose(1, 2)).transpose(1, 2)


@dataclass
class MyForecastModel(ForecastExp):
    model_type: str = "MyForecastModel"

    def _init_model(self):
        self.model = MyForecastNet(
            seq_len=self.windows,
            pred_len=self.pred_len,
        ).to(self.device)


register_model(MyForecastModel)

# The registered model name is the class name.
device = "cuda" if torch.cuda.is_available() else "cpu"

results = Experiment(
    model="MyForecastModel",
    task="Forecast",
    dataset="ETTh1",
    windows=96,
    pred_len=96,
    epochs=1,
    device=device,
).run(seeds=[1])

print(results[0].metrics)

The same registered model can be launched from the CLI after the Python module containing register_model(...) has been imported:

pytexp --model MyForecastModel --task Forecast --dataset_type ETTh1 run 1

Run Built-In Models

Experiment builder (Python API):

from torch_timeseries import Experiment

# single run — returns a RunResult with metrics, hparams, git commit, timing
result = Experiment(model="DLinear", task="Forecast", dataset="ETTh1").run(seeds=[1])
print(result[0].metrics)   # {"mse": 0.382, "mae": 0.271}

# multiple seeds, save results to disk
results = Experiment(
    model="DLinear",
    task="Forecast",
    dataset="ETTh1",
    windows=96,
    pred_len=96,
    lr=0.001,
    save_dir="./results",
).run(seeds=[1, 2, 3])

# grid search across models and datasets
Experiment.grid(
    models=["DLinear", "Autoformer"],
    tasks=["Forecast"],
    datasets=["ETTh1", "ETTm1"],
    seeds=[1, 2, 3],
    save_dir="./results",
).run()

# compare saved results
Experiment.compare(save_dir="./results", task="Forecast")

CLI:

# forecast
pytexp --model DLinear --task Forecast --dataset_type ETTh1 run 3
pytexp --model DLinear --task Forecast --dataset_type ETTh1 runs '[1,2,3]'

# imputation
pytexp --model DLinear --task Imputation --dataset_type ETTh1 run 3

# anomaly detection
pytexp --model DLinear --task AnomalyDetection --dataset_type MSL run 3

# classification
pytexp --model DLinear --task UEAClassification --dataset_type EthanolConcentration run 3

# compare saved results
pytexp compare --save_dir ./results --task Forecast

Use this pattern when you want to benchmark on standard tasks without writing boilerplate.

Development Milestones

Implemented Datasets

Full list: Documentation.

Datasets Forecasting Imputation Anomaly Classification
ETTh1
ETTh2
ETTm1
ETTm2
......And More

Implemented Tasks

  • Forecast
  • Imputation
  • Anomaly Detection
  • Classification (UEA datasets)
  • Contribute your own task!

Implemented Models

Models Forecasting Imputation Anomaly Classification
Informer (2021)
Autoformer (2021)
FEDformer (2022)
DLinear (2022)
PatchTST (2022)
iTransformer (2024)

Dev Install

This library assumes PyTorch is already installed: https://pytorch.org/get-started/locally/

Recommended Python: 3.8.1+

# 1. fork and clone
git clone https://github.com/wayne155/pytorch_timeseries

# 2. install dependencies
pip install -r ./requirements.txt

# 3. make changes and open a pull request

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

torch_timeseries-0.2.1.tar.gz (138.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

torch_timeseries-0.2.1-py3-none-any.whl (209.2 kB view details)

Uploaded Python 3

File details

Details for the file torch_timeseries-0.2.1.tar.gz.

File metadata

  • Download URL: torch_timeseries-0.2.1.tar.gz
  • Upload date:
  • Size: 138.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.9

File hashes

Hashes for torch_timeseries-0.2.1.tar.gz
Algorithm Hash digest
SHA256 e499bb33d66403bd6d0ea03889664fbc75f1408eae0bf87a030a4863b85e0959
MD5 37c94871dacaeb1cdbbfd223e5f96c2a
BLAKE2b-256 9b613288452b890a2252c2a590dc38c8d9e7661c0fbdce12c199fe29705426d3

See more details on using hashes here.

File details

Details for the file torch_timeseries-0.2.1-py3-none-any.whl.

File metadata

File hashes

Hashes for torch_timeseries-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 c07cbd085833dd38938ddb589ba26aea61ad2ff5e60b6d32ea99b32268275d46
MD5 9a8aa27408a2630ff13354999915a9a7
BLAKE2b-256 8efac382d57f025dd57ede5207933fb5570fa86284ae8562ae0d71b604da659b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page