tsai Documentation

repository·main·Indexed 27 days ago

https://github.com/timeseriesai/tsai

A state-of-the-art deep learning library for time series and sequential data built on PyTorch and fastai. tsai supports tasks including classification, regression, forecasting, and imputation, providing a wide range of models such as RNNs (LSTM, GRU), Convolutional networks (InceptionTime, ResNet), and Transformers (PatchTST, TST). It supports univariate and multivariate data formats and integrates with sktime for ROCKET models.

Tokens
15.2K
Snippets
24
Records
109
Agent score
91%

What's inside tsai

  1. Use ROCKET models (MiniRocket)

    main

    ROCKET models (e.g., MiniRocketRegressor, MiniRocketClassifier) are not deep learning models and require sktime to be installed. You can install the necessary extras via pip install tsai[extras] or install sktime separately.

    To use MiniRocketRegressor:

    1. Prepare data using get_Monash_regression_data.
    2. Fit the model using the standard scikit-learn .fit() API.
    3. Save the model using .save().
    4. Load the model using load_minirocket() from tsai.models.MINIROCKET for inference.
    # Installation
    pip install tsai[extras]
    
    # Training
    from sklearn.metrics import mean_squared_error, make_scorer
    from tsai.data.external import get_Monash_regression_data
    from tsai.models.MINIROCKET import MiniRocketRegressor
    
    X_train, y_train, *_ = get_Monash_regression_data('AppliancesEnergy')
    rmse_scorer = make_scorer(mean_squared_error, greater_is_better=False)
    reg = MiniRocketRegressor(scoring=rmse_scorer)
    reg.fit(X_train, y_train)
    reg.save('MiniRocketRegressor')
    
    # Inference
    from sklearn.metrics import mean_squared_error
    from tsai.data.external import get_Monash_regression_data
    from tsai.models.MINIROCKET import load_minirocket
    
    *_, X_test, y_test = get_Monash_regression_data('AppliancesEnergy')
    reg = load_minirocket('MiniRocketRegressor')
    y_pred = reg.predict(X_test)
    mean_squared_error(y_test, y_pred, squared=False)
  2. Install tsai via pip

    main

    Install the latest stable version of tsai from PyPI. Note that tsai requires Python 3.10 or newer. Support for Python 3.9 has been dropped.

    To install only the hard dependencies, use:

    pip install tsai

    To install tsai along with all optional dependencies (such as sktime, tsfresh, PyWavelets, and nbformat) upfront, use the [extras] flag:

    pip install tsai[extras]
  3. Install tsai in development mode

    main

    For development or to use the bleeding-edge version, clone the repository and install it in editable mode with the [dev] extra:

    git clone https://github.com/timeseriesAI/tsai
    pip install -e "tsai[dev]"
  4. Perform Time Series Forecasting (Single and Multi-step)

    main

    Forecasting in tsai supports univariate/multivariate inputs and outputs, and single/multi-step ahead prediction.

    Key Requirements:

    • Prepare X (input) and y (target) using SlidingWindow.
    • Use TimeSplitter for splitting, passing fcst_horizon for multi-step scenarios.
    • Use TSForecaster with a model architecture ending in Plus (e.g., TSTPlus, InceptionTimePlus). These models automatically configure the head to match the target shape.
    • Use TSForecasting() as a transform.

    Inference: Use load_learner to load the exported model. The shape of raw_preds will correspond to the horizon used during training.

    # Single-step Forecasting
    from tsai.basics import *
    
    ts = get_forecasting_time_series("Sunspots").values
    X, y = SlidingWindow(60, horizon=1)(ts)
    splits = TimeSplitter(235)(y) 
    tfms = [None, TSForecasting()]
    batch_tfms = TSStandardize()
    fcst = TSForecaster(X, y, splits=splits, path='models', tfms=tfms, batch_tfms=batch_tfms, bs=512, arch="TSTPlus", metrics=mae, cbs=ShowGraph())
    fcst.fit_one_cycle(50, 1e-3)
    fcst.export("fcst.pkl")
    
    # Multi-step Forecasting (3-step ahead)
    from tsai.basics import *
    
    ts = get_forecasting_time_series("Sunspots").values
    X, y = SlidingWindow(60, horizon=3)(ts)
    splits = TimeSplitter(235, fcst_horizon=3)(y) 
    tfms = [None, TSForecasting()]
    batch_tfms = TSStandardize()
    fcst = TSForecaster(X, y, splits=splits, path='models', tfms=tfms, batch_tfms=batch_tfms, bs=512, arch="TSTPlus", metrics=mae, cbs=ShowGraph())
    fcst.fit_one_cycle(50, 1e-3)
    fcst.export("fcst.pkl")
  5. Perform multi-objective optimization with Optuna

    main
    For multi-objective optimization, you must provide a sequence of directions to the direction argument. Note that in multi-objective mode, the function uses best_trials (plural) instead of best_trial to report results.
  6. Exclude notebook cells from export using #|hide

    main

    To prevent specific code cells from being included in the Python script generated by nb2py, add a #|hide flag to the cell. The flag is case-insensitive and can appear in various formats (e.g., #|hide, # Hide, #HIDE).

    Example:

    #|hide
    # This code will NOT appear in the exported .py script
    def internal_helper():
        pass
  7. Use TSDatasets and TSDataLoaders for high-performance training

    main

    For optimal performance with numpy arrays, use TSDatasets combined with TSDataLoaders.from_dsets.

    Setting inplace=True in TSDatasets allows item transforms to be applied during initialization, making batch creation significantly faster by reducing it to simple slicing and casting. This is highly recommended if your transformed data fits in memory.

  8. Run the documentation watcher service

    main
    The watcher service uses watchmedo to monitor .ipynb files recursively. When changes are detected, it automatically triggers nbdev_build_docs. This service uses network_mode: host to ensure compatibility with GitHub Codespaces.
  9. Perform inference with a trained model

    main

    To use a saved model for inference on new data, use load_learner and follow the same preprocessing and windowing steps used during training.

    1. Load the model: learn = load_learner('path/to/model.pt')
    2. Transform new data: new_df = learn.transform(new_df)
    3. Prepare window: new_X, _ = prepare_forecasting_data(new_df, ...)
    4. Get predictions: new_scaled_preds, *_ = learn.get_X_preds(new_X)
    5. Inverse transform to original scale: preds_df = learn.inverse_transform(preds_df)
    from tsai.inference import load_learner
    
    learn = load_learner('models/patchTST.pt')
    # ... (prepare new_df and new_X) ...
    new_scaled_preds, *_ = learn.get_X_preds(new_X)
    
    # Reshape and convert to DataFrame
    new_scaled_preds = to_np(new_scaled_preds).swapaxes(1,2).reshape(-1, len(y_vars))
    dates = pd.date_range(start=fcst_date, periods=fcst_horizon + 1, freq='7D')[1:]
    preds_df = pd.DataFrame(dates, columns=[datetime_col])
    preds_df.loc[:, y_vars] = new_scaled_preds
    
    # Scale back to original values
    preds_df = learn.inverse_transform(preds_df)
    from tsai.inference import load_learner
    learn = load_learner('models/patchTST.pt')
    # ... prepare new_X ...
    new_scaled_preds, *_ = learn.get_X_preds(new_X)
    new_scaled_preds = to_np(new_scaled_preds).swapaxes(1,2).reshape(-1, len(y_vars))
    dates = pd.date_range(start=fcst_date, periods=fcst_horizon + 1, freq='7D')[1:]
    preds_df = pd.DataFrame(dates, columns=[datetime_col])
    preds_df.loc[:, y_vars] = new_scaled_preds
    preds_df = learn.inverse_transform(preds_df)
  10. Run the Jekyll documentation server

    main
    The jekyll service builds the documentation from source and serves it using Jekyll. It performs the following steps: copies docs_src to docs, installs the package, builds the documentation via nbdev_build_docs, installs Ruby bundles, and starts the Jekyll server on port 4000.