Import tsai in your project
mainTo use the tsai package in your Python scripts or notebooks, import everything from the tsai.all module:
from tsai.all import *repository·main·Indexed 27 days ago
https://github.com/timeseriesai/tsaiA 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.
To use the tsai package in your Python scripts or notebooks, import everything from the tsai.all module:
from tsai.all import *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:
get_Monash_regression_data..fit() API..save().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)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 tsaiTo install tsai along with all optional dependencies (such as sktime, tsfresh, PyWavelets, and nbformat) upfront, use the [extras] flag:
pip install tsai[extras]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]"Forecasting in tsai supports univariate/multivariate inputs and outputs, and single/multi-step ahead prediction.
Key Requirements:
X (input) and y (target) using SlidingWindow.TimeSplitter for splitting, passing fcst_horizon for multi-step scenarios.TSForecaster with a model architecture ending in Plus (e.g., TSTPlus, InceptionTimePlus). These models automatically configure the head to match the target shape.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")direction argument. Note that in multi-objective mode, the function uses best_trials (plural) instead of best_trial to report results..pkl file to the resume parameter. The function will attempt to load the study using joblib and print the best results found so far.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():
passFor 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.
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.To use a saved model for inference on new data, use load_learner and follow the same preprocessing and windowing steps used during training.
learn = load_learner('path/to/model.pt')new_df = learn.transform(new_df)new_X, _ = prepare_forecasting_data(new_df, ...)new_scaled_preds, *_ = learn.get_X_preds(new_X)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)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.