### Install Additional Packages for Example Data Source: https://github.com/nx-ai/tirex/blob/main/docs/content/how-to/classification/practice.md Install the 'aeon' package, which is used for example data loading. ```bash pip install aeon ``` -------------------------------- ### Install TiRex with All Extras Source: https://github.com/nx-ai/tirex/blob/main/README.md Install TiRex with all available extras. ```sh pip install "tirex-ts[all]" ``` -------------------------------- ### Setup Python Virtual Environment Source: https://github.com/nx-ai/tirex/blob/main/docs/content/contributing/index.md Installs the package in editable mode within a Python virtual environment. Ensure you activate the environment first. ```bash python -m venv .venv && source .venv/bin/activate && pip install -e .[dev] ``` -------------------------------- ### Load TiRex Model with Minimal Configuration Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/configuration.md Loads a TiRex model using the default configuration parameters. This is the simplest way to get started. ```python from tirex import load_model # Minimal (uses defaults) model = load_model("NX-AI/TiRex") ``` -------------------------------- ### Set up Isolated Environment and Install Project Source: https://github.com/nx-ai/tirex/blob/main/docs/README.md Creates a virtual environment for Sphinx and TiRex imports, then installs the project in editable mode for autodoc to import TiRex. ```bash python -m venv .venv && source .venv/bin/activate pip install -e . ``` -------------------------------- ### Install Tirex and Dependencies Source: https://github.com/nx-ai/tirex/blob/main/examples/quick_start_tirex_regression.ipynb Install the tirex-ts library with notebook, gluonts, hfdataset, and regression extras, along with the aeon library. Use the -q flag for quiet installation. ```python !pip install 'tirex-ts[notebooks,gluonts,hfdataset,regression]' -q !pip install aeon ``` -------------------------------- ### Install JavaScript Dependencies Source: https://github.com/nx-ai/tirex/blob/main/docs/README.md Installs JavaScript dependencies for the documentation site. Run this once or whenever package.json changes. ```bash npm --prefix docs install ``` -------------------------------- ### Install TiRex with Classification Support Source: https://github.com/nx-ai/tirex/blob/main/docs/content/how-to/classification/practice.md Install the TiRex library with the 'classification' extra for classification functionalities. ```sh # install with the extra 'classification' for classification support pip install 'tirex-ts[classification]' ``` -------------------------------- ### Install TiRex Source: https://github.com/nx-ai/tirex/blob/main/examples/quick_start_tirex.ipynb Install the TiRex library with necessary dependencies for notebooks, GluonTS, and Hugging Face datasets. ```python !pip install 'tirex-ts[notebooks,gluonts,hfdataset]' -q ``` -------------------------------- ### Install TiRex Source: https://github.com/nx-ai/tirex/blob/main/README.md Install the base TiRex package using pip. ```sh pip install tirex-ts ``` -------------------------------- ### Load Example Data for Forecasting Source: https://github.com/nx-ai/tirex/blob/main/docs/content/how-to/forecasting/practice.md Loads example time series data from a URL and splits it into context and future values. This is a prerequisite for generating forecasts. ```python # load example data and split into context (to be learnt from) and future values data_base_url = "https://raw.githubusercontent.com/NX-AI/tirex/refs/heads/main/tests/data/" # short horizon example: air passengers per month ctx_s, future_s = np.split(pd.read_csv(f"{data_base_url}/air_passengers.csv").values.reshape(-1), [-59]) ``` -------------------------------- ### Install Tirex and Dependencies Source: https://github.com/nx-ai/tirex/blob/main/examples/quick_start_tirex_classification.ipynb Install the tirex-ts library with necessary dependencies for notebooks, GluonTS, HF datasets, and classification. Also installs the aeon library. ```python !pip install 'tirex-ts[notebooks,gluonts,hfdataset,classification]' -q !pip install aeon ``` -------------------------------- ### Install TiRex with Adapters Source: https://github.com/nx-ai/tirex/blob/main/README.md Install TiRex with additional input/output adapters for GluonTS and HFDataset. ```sh pip install "tirex-ts[gluonts,hfdataset]" ``` -------------------------------- ### Load Model - Basic Usage (CPU) Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/api-reference/load_model.md Demonstrates loading a TiRex model for CPU inference. Ensure the 'tirex' library is installed. ```python from tirex import load_model model = load_model("NX-AI/TiRex", device="cpu") ``` -------------------------------- ### Load and Forecast with TiRex Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/INDEX.md Demonstrates loading a pre-trained TiRex model and performing a forecast. Ensure the 'tirex' library is installed. ```python from tirex import load_model model = load_model("NX-AI/TiRex") # Forecast quantiles, mean = model.forecast(context, prediction_length=64) ``` -------------------------------- ### Quick Start Forecasting Model Source: https://github.com/nx-ai/tirex/blob/main/README.md Load the TiRex forecasting model and perform a forecast on sample data. ```python import torch from tirex import load_model, ForecastModel model: ForecastModel = load_model("NX-AI/TiRex") data = torch.rand((5, 128)) # Sample Data (5 time series with length 128) quantiles, mean = model.forecast(context=data, prediction_length=64) ``` -------------------------------- ### Install TiRex with Plotting Support Source: https://github.com/nx-ai/tirex/blob/main/docs/content/how-to/forecasting/practice.md Install the TiRex library using pip, including the 'plotting' extra for visualization capabilities. ```sh pip install 'tirex-ts[plotting]' ``` -------------------------------- ### Install Dependencies for Tirex ONNX Source: https://github.com/nx-ai/tirex/blob/main/examples/tirex_onnx.ipynb Installs the required Python packages for running the ONNX model and plotting results. Use this at the beginning of your environment setup. ```python # For running the onnx model: !pip install -q numpy onnxruntime huggingface_hub # For plotting and loading data: !pip install -q pandas tirex-ts matplotlib scikit-learn ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/nx-ai/tirex/blob/main/inference/README.md Installs Python dependencies required for development and inference. Ensure you have pip installed. ```bash pip install -r requirements.txt -r requirements-dev.txt ``` -------------------------------- ### Complete Workflow Example Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/api-reference/BaseTirexClassifier.md Demonstrates the end-to-end usage of TiRexGBMClassifier, including data generation, model training, prediction, evaluation, and model persistence. ```python import torch from tirex.models.classification.gbm_classifier import TiRexGBMClassifier # Generate synthetic data train_data = torch.randn(1000, 10, 256) # 1000 samples, 10 variates, 256 steps train_labels = torch.randint(0, 5, (1000,)) # 5 classes test_data = torch.randn(200, 10, 256) test_labels = torch.randint(0, 5, (200,)) # Create and train classifier classifier = TiRexGBMClassifier( data_augmentation=True, device="cuda:0", batch_size=128 ) print("Training classifier...") classifier.fit((train_data, train_labels)) # Make predictions predictions = classifier.predict(test_data) probabilities = classifier.predict_proba(test_data) # Evaluate accuracy = (predictions == test_labels).float().mean() print(f"Accuracy: {accuracy:.4f}") # Save model classifier.save_model("my_classifier.pkl") # Load and use loaded_classifier = TiRexGBMClassifier.load_model("my_classifier.pkl") new_predictions = loaded_classifier.predict(test_data) ``` -------------------------------- ### Example Usage of run_fft_analysis Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/api-reference/utility-functions.md This example demonstrates how to use the `run_fft_analysis` function with a sample time series. It shows how to generate a sine wave, call the function, and print the detected peak frequencies and their corresponding heights. ```python from tirex.util import run_fft_analysis ts = torch.sin(torch.linspace(0, 8*3.14, 1024)) # Period = 256 freqs, spectrum, peak_indices = run_fft_analysis(ts, peak_prominence=0.1) print(f"Detected peaks at frequencies: {freqs[peak_indices]}") print(f"Peak heights: {spectrum[peak_indices]}") ``` -------------------------------- ### Run Development Server Source: https://github.com/nx-ai/tirex/blob/main/inference/README.md Starts the TiRex inference server locally. This command runs the main application module. ```bash python -m app.main ``` -------------------------------- ### Run TiRex Container with MQTT Enabled Source: https://github.com/nx-ai/tirex/blob/main/docs/content/deployment/index.md Starts the TiRex container with MQTT API enabled. Configure the MQTT broker host and port using environment variables. ```bash docker run -p 8000:8000 -it -e MQTT_ENABLED=1 -e MQTT_BROKER_HOST=broker.emqx.io -e MQTT_BROKER_PORT=1883 ghcr.io/nx-ai/tirex-cpu ``` -------------------------------- ### Python Example for POST /forecast/mean Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/endpoints.md Demonstrates how to use the Python requests library to send a POST request to the /forecast/mean endpoint and retrieve the generated forecasts. Ensure the server is running at the specified URL. ```python import requests response = requests.post( "http://localhost:8000/forecast/mean", json={ "context": [ [1.0, 1.5, 1.2, 1.8, 2.0, 1.9], [2.0, 2.3, 2.1, 2.4, 2.5, 2.3] ], "prediction_length": 8 } ) forecasts = response.json() # [[1.95, 2.05, ...], [2.4, 2.5, ...]] ``` -------------------------------- ### Install Tirex with Dependencies Source: https://github.com/nx-ai/tirex/blob/main/examples/chronos_zs/chronos_zs.ipynb Installs the tirex-ts library along with gluonts, hfdataset, and test dependencies using pip. ```python !pip install 'tirex-ts[gluonts,hfdataset,test]' ``` -------------------------------- ### Install TiRex with Regression Support Source: https://github.com/nx-ai/tirex/blob/main/docs/content/how-to/regression/practice.md Install TiRex including the 'regression' extra for regression capabilities. This command ensures all necessary dependencies for regression tasks are included. ```sh # install with the extra 'regression' for regression support pip install 'tirex-ts[regression]' ``` -------------------------------- ### sLSTMBlockConfig Example Usage Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/types.md Demonstrates how to instantiate and use the sLSTMBlockConfig class to create a configuration object and access its computed head_dim property. ```python from tirex.models.slstm.cell import sLSTMBlockConfig config = sLSTMBlockConfig( embedding_dim=256, num_heads=4, ffn_proj_factor=2.6667 ) print(config.head_dim) # 64 ``` -------------------------------- ### Set HTTP Server Configuration via Environment Variables Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/configuration.md Configure the HTTP server's host, port, inference device, batch size, and model path using environment variables. Ensure to start the server after setting these variables. ```bash export HTTP_HOST="127.0.0.1" export HTTP_PORT="5000" export DEVICE="cuda:1" export BATCH_SIZE="256" export MODEL_PATH="NX-AI/TiRex" # Start server python inference/app/main.py ``` -------------------------------- ### TirexGBMClassifier Example Source: https://github.com/nx-ai/tirex/blob/main/docs/sphinx/source/tirex.classification.md Demonstrates how to create, train, and make predictions with the TirexGBMClassifier. Includes model initialization with custom parameters and data preparation using PyTorch tensors. ```python >>> from tirex.models.classification import TirexGBMClassifier >>> >>> # Create model with custom LightGBM parameters >>> model = TirexGBMClassifier( ... data_augmentation=True, ... n_estimators=50, ... random_state=42 ... ) >>> >>> # Prepare data (can use NumPy arrays or PyTorch tensors) >>> X_train = torch.randn(100, 1, 128) # 100 samples, 1 number of variates, 128 sequence length >>> y_train = torch.randint(0, 3, (100,)) # 3 classes >>> >>> # Train the model >>> model.fit((X_train, y_train)) >>> >>> # Make predictions >>> X_test = torch.randn(20, 1, 128) >>> predictions = model.predict(X_test) >>> probabilities = model.predict_proba(X_test) ``` -------------------------------- ### POST /forecast/mean Request Body Example Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/endpoints.md Example JSON structure for the request body when calling the /forecast/mean endpoint. It includes sample time series data and the desired prediction length. ```json { "context": [ [0.5, 1.2, 0.8, 1.5, ...], [2.1, 2.3, 2.0, 2.4, ...], ... ], "prediction_length": 32 } ``` -------------------------------- ### Import TiRex and Supporting Libraries for Regression Source: https://github.com/nx-ai/tirex/blob/main/docs/content/how-to/regression/practice.md Import core PyTorch, scikit-learn metrics and model selection tools, aeon dataset loader, and TiRex regression models. Ensure these libraries are installed before running. ```python # General imports import torch from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score from sklearn.model_selection import train_test_split from aeon.datasets import load_regression # Import TiRex regressors from tirex.models.regression import TirexRFRegressor, TirexLinearRegressor, TirexGBMRegressor ``` -------------------------------- ### Load Model and Forecast with TiRex Source: https://github.com/nx-ai/tirex/blob/main/docs/content/getting-started/quickstart.md Load a pre-trained TiRex model, prepare context data, and generate forecasts for a specified number of steps. Ensure PyTorch is installed. ```python import torch from tirex import load_model, ForecastModel # 1) load model (from HF Hub) model: ForecastModel = load_model("NX-AI/TiRex") # 2) prepare context (batch x length) context = torch.rand((8, 256)) # 3) forecast quantiles + mean for 64 steps quantiles, mean = model.forecast(context=context, prediction_length=64) print(mean.shape) # (8, 64) ``` -------------------------------- ### TiRexGBMRegressor Usage Example Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/api-reference/BaseTirexRegressor.md Instantiate and use the TiRexGBMRegressor for training, prediction, and model saving. Requires specifying the device. ```python from tirex.models.regression.gbm_regressor import TiRexGBMRegressor regressor = TiRexGBMRegressor(device="cuda:0") regressor.fit((train_data, train_targets)) predictions = regressor.predict(test_data) regressor.save_model("my_regressor.pkl") ``` -------------------------------- ### Train and Predict with TirexLinearClassifier Source: https://github.com/nx-ai/tirex/blob/main/docs/sphinx/source/tirex.classification.md Demonstrates how to initialize, train, and make predictions using the TirexLinearClassifier. Ensure PyTorch and the Tirex library are installed. The model requires time series data and corresponding labels for training. ```python import torch from tirex.models.classification import TirexLinearClassifier # Create model with TiRex embeddings model = TirexLinearClassifier( data_augmentation=True, max_epochs=2, lr=1e-4, batch_size=32 ) # Prepare data X_train = torch.randn(100, 1, 128) # 100 samples, 1 number of variates, 128 sequence length y_train = torch.randint(0, 3, (100,)) # 3 classes # Train the model metrics = model.fit((X_train, y_train)) Epoch 1, Train Loss: ... # Make predictions X_test = torch.randn(20, 1, 128) predictions = model.predict(X_test) probabilities = model.predict_proba(X_test) ``` -------------------------------- ### Full TiRex Configuration Pipeline Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/configuration.md This snippet illustrates loading a TiRex model with custom configurations, generating forecasts using specific parameters, extracting embeddings for downstream tasks, training a classifier, and saving the trained model. Ensure PyTorch and TiRex are installed and a CUDA-enabled GPU is available for optimal performance. ```python import torch from tirex import load_model from tirex.models.classification.gbm_classifier import TiRexGBMClassifier # 1. Load model with custom configuration model = load_model( path="NX-AI/TiRex", device="cuda:0", backend="cuda", compile=True ) # 2. Generate forecasts with custom parameters context = torch.randn(64, 512) # 64 series, 512 timesteps quantiles, mean = model.forecast( context, prediction_length=128, batch_size=32, output_type="numpy", resample_strategy="frequency" ) # 3. Extract embeddings for downstream task from tirex.models.embedding import TiRexEmbedding embedding_model = TiRexEmbedding( device="cuda:0", data_augmentation=True, batch_size=128 ) train_data = torch.randn(1000, 10, 256) train_labels = torch.randint(0, 5, (1000,)) embeddings = embedding_model(train_data) # 4. Train classifier classifier = TiRexGBMClassifier( data_augmentation=True, device="cuda:0", batch_size=256 ) classifier.fit((train_data, train_labels)) predictions = classifier.predict(train_data[:100]) # 5. Save model classifier.save_model("my_classifier.pkl") ``` -------------------------------- ### Make HTTP Request to TiRex API Source: https://github.com/nx-ai/tirex/blob/main/docs/content/deployment/index.md Example of making a POST request to the TiRex HTTP API for forecasting. The API expects JSON payloads and supports both mean and quantile forecasts. ```bash curl -X 'POST' 'http://localhost:8000/forecast/mean' -H 'Content-Type: application/json' -d '{"context": [[0, 1, 2, 3]], "prediction_length": 4}' ``` ```python import requests body = {"context": [[0, 1, 2, 3]], "prediction_length": 4} response = requests.post('http://localhost:8000/forecast/mean', json=body) print(response.text) ``` ```javascript const body = JSON.stringify({ context: [[0, 1, 2, 3]], prediction_length: 4 }); const headers = { 'Content-Type': 'application/json' }; const data = await fetch('http://localhost:8000/forecast/mean', { method: 'POST', headers, body }); console.log(await data.json()); ``` -------------------------------- ### Run Documentation Locally Source: https://github.com/nx-ai/tirex/blob/main/docs/README.md Launches the documentation development server with hot reload on http://localhost:3000/. ```bash npm --prefix docs run start ``` -------------------------------- ### Load and Forecast with TiRex Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/api-reference/TiRexZero.md Demonstrates how to load a TiRex model and perform forecasting. Ensure the model is loaded before calling forecast. The output provides quantiles and mean predictions. ```python import torch from tirex import load_model model = load_model("NX-AI/TiRex") data = torch.rand((3, 256)) # 3 series, 256 timesteps quantiles, mean = model.forecast( context=data, prediction_length=128 ) # quantiles: (3, 128, 9) — 3 samples, 128 timesteps, 9 quantiles # mean: (3, 128) — median of quantiles ``` -------------------------------- ### Build and Serve Production Documentation Source: https://github.com/nx-ai/tirex/blob/main/docs/README.md Builds the static production version of the documentation and optionally serves it locally. Failures in the build step may indicate issues with redirects, broken links, or unescaped characters in the API Markdown. ```bash npm --prefix docs run build npm --prefix docs run serve # optional: serve the static build locally ``` -------------------------------- ### TiRexRFClassifier Example Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/api-reference/BaseTirexClassifier.md Example usage of the TiRexRFClassifier, a Random Forest classifier. ```APIDOC ## TiRexRFClassifier ### Description Random Forest classifier. ### Initialization ```python from tirex.models.classification.rf_classifier import TiRexRFClassifier classifier = TiRexRFClassifier(device="cuda:0") ``` ### Usage Example ```python classifier.fit((train_data, train_labels)) predictions = classifier.predict(test_data) ``` ``` -------------------------------- ### TiRexLinearClassifier Example Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/api-reference/BaseTirexClassifier.md Example usage of the TiRexLinearClassifier, a linear model classifier with logistic regression. ```APIDOC ## TiRexLinearClassifier ### Description Linear model classifier with logistic regression. ### Initialization ```python from tirex.models.classification.linear_classifier import TiRexLinearClassifier classifier = TiRexLinearClassifier(device="cuda:0") ``` ### Usage Example ```python classifier.fit((train_data, train_labels)) predictions = classifier.predict(test_data) ``` ``` -------------------------------- ### TiRexGBMClassifier Example Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/api-reference/BaseTirexClassifier.md Example usage of the TiRexGBMClassifier, a gradient boosting classifier using a LightGBM head. ```APIDOC ## TiRexGBMClassifier ### Description Gradient boosting classifier using LightGBM head. ### Initialization ```python from tirex.models.classification.gbm_classifier import TiRexGBMClassifier classifier = TiRexGBMClassifier(device="cuda:0") ``` ### Usage Example ```python classifier.fit((train_data, train_labels)) predictions = classifier.predict(test_data) classifier.save_model("my_classifier.pkl") ``` ``` -------------------------------- ### Install TiRex with GiftEval Dependencies Source: https://github.com/nx-ai/tirex/blob/main/examples/gifteval/gifteval.ipynb Install the tirex-ts package with all necessary dependencies for GiftEval, including gluonts, hfdataset, test, and notebooks. ```python !pip install 'tirex-ts[gluonts,hfdataset,test,notebooks]' ``` -------------------------------- ### Install TiRex with CUDA Kernels Source: https://github.com/nx-ai/tirex/blob/main/README.md Install the TiRex package including CUDA and other dependencies using pip. This command ensures that the necessary components for GPU acceleration are included. ```sh pip install "tirex-ts[cuda,gluonts,hfdataset]" ``` -------------------------------- ### Run Benchmark on All Configurations Source: https://github.com/nx-ai/tirex/blob/main/benchmark/Readme.md Execute benchmarks across all possible system configurations. This is useful for comprehensive performance testing. ```bash python benchmark.py --all --hardware test ``` -------------------------------- ### POST /forecast/mean Response Schema Example Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/endpoints.md Example JSON structure for the response body when a successful forecast is generated by the /forecast/mean endpoint. It shows the forecasted values for each time series. ```json [ [0.95, 1.10, 1.25, ...], [2.15, 2.22, 2.18, ...], ... ] ``` -------------------------------- ### Batch Forecasting with Mean and Quantiles Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/endpoints.md Demonstrates how to perform batch forecasting for multiple time series. It shows requests for both mean forecasts and quantile forecasts. ```python import requests import json # Prepare batch of 3 time series context = [ [1.0, 1.2, 1.1, 1.3, 1.5, 1.4, 1.6, 1.8], [0.5, 0.7, 0.6, 0.8, 1.0, 0.9, 1.1, 1.3], [2.0, 2.1, 2.0, 2.2, 2.3, 2.2, 2.4, 2.5], ] # Get mean forecasts response_mean = requests.post( "http://localhost:8000/forecast/mean", json={"context": context, "prediction_length": 4} ) mean_forecasts = response_mean.json() print("Mean forecasts:", mean_forecasts) # [[1.7, 1.8, 1.85, 1.9], [1.2, 1.3, 1.35, 1.4], [2.5, 2.55, 2.6, 2.65]] # Get quantile forecasts response_q = requests.post( "http://localhost:8000/forecast/quantiles", json={"context": context, "prediction_length": 4} ) quantile_forecasts = response_q.json() print("Quantile forecasts shape:", len(quantile_forecasts), len(quantile_forecasts[0]), len(quantile_forecasts[0][0])) # (3, 4, 9) — batch_size, forecast_length, num_quantiles ``` -------------------------------- ### TiRexLinearRegressor Usage Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/api-reference/BaseTirexRegressor.md Example usage of the TiRexLinearRegressor, a linear regression model. ```python from tirex.models.regression.linear_regressor import TiRexLinearRegressor # Assuming train_data, train_targets, test_data are defined regressor = TiRexLinearRegressor(device="cuda:0") regressor.fit((train_data, train_targets)) predictions = regressor.predict(test_data) ``` -------------------------------- ### TiRexRFRegressor Usage Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/api-reference/BaseTirexRegressor.md Example usage of the TiRexRFRegressor, a Random Forest regressor. ```python from tirex.models.regression.rf_regressor import TiRexRFRegressor # Assuming train_data, train_targets, test_data are defined regressor = TiRexRFRegressor(device="cuda:0") regressor.fit((train_data, train_targets)) predictions = regressor.predict(test_data) ``` -------------------------------- ### Train and Predict with TiRex Classifier Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/INDEX.md Shows how to initialize, train, and predict using the TiRex Gradient Boosting Machine classifier. Requires training data and labels. ```python from tirex.models.classification.gbm_classifier import TiRexGBMClassifier classifier = TiRexGBMClassifier() classifier.fit((train_data, train_labels)) predictions = classifier.predict(test_data) ``` -------------------------------- ### TiRexLinearClassifier Usage Example Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/api-reference/BaseTirexClassifier.md Instantiate and use the TiRexLinearClassifier for training and prediction. Requires 'cuda:0' device. ```python from tirex.models.classification.linear_classifier import TiRexLinearClassifier classifier = TiRexLinearClassifier(device="cuda:0") classifier.fit((train_data, train_labels)) predictions = classifier.predict(test_data) ``` -------------------------------- ### TiRexZero Constructor Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/api-reference/TiRexZero.md Initializes the TiRexZero forecasting model. It's recommended to use the `load_model` function for instantiation. ```APIDOC ## TiRexZero Constructor ### Description Initializes the TiRexZero forecasting model. This class represents a 35M parameter xLSTM-based deep learning model for zero-shot time series forecasting. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method `__init__` ### Parameters #### Parameters - **backend** (`str`) - Required - Computation backend: `"torch"` or `"cuda"` (for custom sLSTM kernels) - **model_config** (`TiRexZeroConfig | dict`) - Required - Configuration dataclass or dictionary with keys: `input_patch_size`, `output_patch_size`, `quantiles`, `block_kwargs`, `input_ff_dim`, `train_ctx_len` - **train_ctx_len** (`int | None`) - Optional - Context length used during training. If provided, overrides value in `model_config` ### Example ```python from tirex import load_model # Standard usage via load_model (recommended) model = load_model("NX-AI/TiRex", device="cuda:0") # Direct instantiation (requires checkpoint) # Not typically done manually; use load_model instead ``` ### Response #### Success Response (200) N/A (Constructor) #### Response Example N/A (Constructor) ``` -------------------------------- ### TiRexRFClassifier Usage Example Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/api-reference/BaseTirexClassifier.md Instantiate and use the TiRexRFClassifier for training and prediction. Requires 'cuda:0' device. ```python from tirex.models.classification.rf_classifier import TiRexRFClassifier classifier = TiRexRFClassifier(device="cuda:0") classifier.fit((train_data, train_labels)) predictions = classifier.predict(test_data) ``` -------------------------------- ### Run Benchmark for Single Configuration Source: https://github.com/nx-ai/tirex/blob/main/benchmark/Readme.md Execute benchmarks for a specific set of parameters including backend, device, compilation, batch sizes, prediction lengths, and context lengths. ```bash python benchmark.py --backend torch --device cpu --compile True --batch_sizes 1 16 256 --prediction_lengths 32 64 128 --context_lengths 2048 --hardware test ``` -------------------------------- ### TiRexGBMRegressor Usage Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/api-reference/BaseTirexRegressor.md Example usage of the TiRexGBMRegressor, a gradient boosting regressor using LightGBM head. ```python from tirex.models.regression.gbm_regressor import TiRexGBMRegressor # Assuming train_data, train_targets, test_data are defined regressor = TiRexGBMRegressor(device="cuda:0") regressor.fit((train_data, train_targets)) predictions = regressor.predict(test_data) regressor.save_model("my_regressor.pkl") ``` -------------------------------- ### TiRexLinearRegressor Usage Example Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/api-reference/BaseTirexRegressor.md Instantiate and use the TiRexLinearRegressor for training and prediction. Requires specifying the device. ```python from tirex.models.regression.linear_regressor import TiRexLinearRegressor regressor = TiRexLinearRegressor(device="cuda:0") regressor.fit((train_data, train_targets)) predictions = regressor.predict(test_data) ``` -------------------------------- ### Initialize and Train TirexGBMRegressor Source: https://github.com/nx-ai/tirex/blob/main/docs/sphinx/source/tirex.regression.md Demonstrates how to initialize TirexGBMRegressor with custom parameters, prepare data, and train the model. Supports PyTorch tensors for data. ```python >>> import torch >>> from tirex.models.regression import TirexGBMRegressor >>> >>> # Create model with custom LightGBM parameters >>> model = TirexGBMRegressor( ... data_augmentation=True, ... n_estimators=50, ... random_state=42 ... ) >>> >>> # Prepare data (can use NumPy arrays or PyTorch tensors) >>> X_train = torch.randn(100, 1, 128) # 100 samples, 1 number of variates, 128 sequence length >>> y_train = torch.randn(100,) # target values >>> >>> # Train the model >>> model.fit((X_train, y_train)) >>> >>> # Make predictions >>> X_test = torch.randn(20, 1, 128) >>> predictions = model.predict(X_test) ``` -------------------------------- ### TiRexRFRegressor Usage Example Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/api-reference/BaseTirexRegressor.md Instantiate and use the TiRexRFRegressor for training and prediction. Requires specifying the device. ```python from tirex.models.regression.rf_regressor import TiRexRFRegressor regressor = TiRexRFRegressor(device="cuda:0") regressor.fit((train_data, train_targets)) predictions = regressor.predict(test_data) ``` -------------------------------- ### Load TiRexZero Model Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/api-reference/TiRexZero.md Use `load_model` for standard usage, which is the recommended approach. Direct instantiation is possible but not typically done manually. ```python from tirex import load_model # Standard usage via load_model (recommended) model = load_model("NX-AI/TiRex", device="cuda:0") # Direct instantiation (requires checkpoint) # Not typically done manually; use load_model instead ``` -------------------------------- ### TiRexGBMClassifier Usage Example Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/api-reference/BaseTirexClassifier.md Instantiate and use the TiRexGBMClassifier for training, prediction, and saving the model. Requires 'cuda:0' device. ```python from tirex.models.classification.gbm_classifier import TiRexGBMClassifier classifier = TiRexGBMClassifier(device="cuda:0") classifier.fit((train_data, train_labels)) predictions = classifier.predict(test_data) classifier.save_model("my_classifier.pkl") ``` -------------------------------- ### Initialize Gradient Boosting Regressor with TiRex Source: https://github.com/nx-ai/tirex/blob/main/docs/content/how-to/regression/practice.md Use this to initialize a Gradient Boosting regressor. Configure parameters for embedding computation, training, and early stopping. LightGBM runs on CPU. ```python regressor = TirexGBMRegressor( data_augmentation=False, device="cuda:0", batch_size=512, early_stopping_rounds=10, min_delta=0.0, val_split_ratio=0.2, random_state=42 ) ``` -------------------------------- ### Load and Preprocess Data Source: https://github.com/nx-ai/tirex/blob/main/docs/content/how-to/classification/practice.md Load the Italy Power Demand dataset, encode string labels into integers, and convert data to PyTorch tensors for training and testing. ```python # Load train data train_X, train_y = load_italy_power_demand(split="train") # Load test data test_X, test_y = load_italy_power_demand(split="test") # Encode string labels -> integers label_encoder = LabelEncoder() train_y = label_encoder.fit_transform(train_y) test_y = label_encoder.transform(test_y) # Convert to torch tensors train_X = torch.tensor(train_X, dtype=torch.float32) test_X = torch.tensor(test_X, dtype=torch.float32) train_y = torch.tensor(train_y, dtype=torch.long) test_y = torch.tensor(test_y, dtype=torch.long) ``` -------------------------------- ### Initialize Gradient Boosting Regressor Source: https://github.com/nx-ai/tirex/blob/main/docs/content/how-to/regression/practice.md Initializes the TiRex Gradient Boosting Regressor. Model weights are fetched from HuggingFace. LightGBM runs on CPU. ```APIDOC ## Initialize Gradient Boosting Regressor Model weights of the TiRex backbone model are automatically fetched from HuggingFace. ### Constructor ```python TirexGBMRegressor( data_augmentation=False, device="cuda:0", batch_size=512, early_stopping_rounds=10, min_delta=0.0, val_split_ratio=0.2, random_state=42 ) ``` ### Parameters - `data_augmentation` (bool): Whether to use additional data augmentation concatenated to the embeddings. Defaults to False. - `device` (str | None): Device used for embedding computation (for example, "cuda:0" for GPU or "cpu"). If None, uses CUDA if available, else CPU. Note: LightGBM itself always runs on CPU. - `compile` (bool): Whether to compile the frozen embedding model. Default: False - `batch_size` (int): Batch size for embedding calculations. Default: 512. - `early_stopping_rounds` (int | None): Number of rounds without improvement of all metrics for Early Stopping. Default: 10. Set to None to disable early stopping. - `min_delta` (float): Minimum improvement in score to keep training. Default: 0.0. - `val_split_ratio` (float): Proportion of training data to use for validation, if validation data are not provided. Default: 0.2. - The rest of the parameters are kwargs to LightGBM's LGBMRegressor. For more details see [LGBMRegressor documentation](https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.LGBMRegressor.html). ``` -------------------------------- ### TiRex Forecast with GluonTS Output Source: https://github.com/nx-ai/tirex/blob/main/examples/quick_start_tirex.ipynb Generates forecasts using the GluonTS QuantileForecast format. Requires the optional `tirex[gluonts]` dependency to be installed. ```python try: # QuantileForecast (GluonTS) predictions_gluonts = model.forecast(context=data, prediction_length=24, output_type="gluonts") print("Predictions (GluonTS Quantile Forecast):\n", type(predictions_gluon), type(predictions_gluon[0])) predictions_gluonts[0].plot() except Exception as e: print(e) # To use the gluonts function you need to install the optional dependency # pip install tirex[gluonts] ``` -------------------------------- ### Initialize and Train TirexRFRegressor Source: https://github.com/nx-ai/tirex/blob/main/docs/sphinx/source/tirex.regression.md Demonstrates how to initialize TirexRFRegressor with custom parameters, prepare data, train the model, and make predictions. Ensure data is in the correct PyTorch tensor format. ```python >>> import torch >>> from tirex.models.regression import TirexRFRegressor >>> >>> # Create model with custom Random Forest parameters >>> model = TirexRFRegressor( ... data_augmentation=True, ... n_estimators=50, ... max_depth=10, ... random_state=42 ... ) >>> >>> # Prepare data (can use NumPy arrays or PyTorch tensors) >>> X_train = torch.randn(100, 1, 128) # 100 samples, 1 number of variates, 128 sequence length >>> y_train = torch.randn(100,) # target values >>> >>> # Train the model >>> model.fit((X_train, y_train)) >>> >>> # Make predictions >>> X_test = torch.randn(20, 1, 128) >>> predictions = model.predict(X_test) ``` -------------------------------- ### Run ONNX Model with Custom Session Options Source: https://github.com/nx-ai/tirex/blob/main/examples/tirex_onnx.ipynb Demonstrates how to configure ONNX Runtime session options for performance optimization, such as graph optimization level and thread counts. This allows fine-tuning the inference process. ```python # Run onnx model with custom session options # ONNX Parameters: see https://onnxruntime.ai/docs/api/python/api_summary.html#sessionoptions sess_options = onnxruntime.SessionOptions() sess_options.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_EXTENDED sess_options.intra_op_num_threads = 10 sess_options.inter_op_num_threads = 1 # On which device to run: in our case on CPU version providers = ["CPUExecutionProvider"] model_optimized = TiRexONNX.from_pretrained("NX-AI/TiRex", providers=providers, sess_options=sess_options) quantiles_opt, median_opt = model_optimized.forecast(context_onnx, prediction_length=768) quantiles_opt.shape, median_opt.shape ``` -------------------------------- ### ResidualBlock Example Usage Source: https://github.com/nx-ai/tirex/blob/main/_autodocs/api-reference/TiRexZero.md Demonstrates creating and using a ResidualBlock with random tensor input. The output shape is determined by the block's out_dim. ```python block = ResidualBlock(in_dim=128, h_dim=512, out_dim=256) x = torch.randn(4, 10, 128) output = block(x) # shape: (4, 10, 256) ``` -------------------------------- ### Run CPU Docker Container Source: https://github.com/nx-ai/tirex/blob/main/inference/README.md Runs the Docker container for CPU inference. This command maps port 8000 and starts the tirex-inference-cpu container interactively. ```bash docker run -p 8000:8000 -it tirex-inference-cpu ``` -------------------------------- ### Build CPU Docker Image Source: https://github.com/nx-ai/tirex/blob/main/inference/README.md Builds the Docker image for the CPU inference environment. Use this command to create the tirex-inference-cpu image. ```bash docker build -f Dockerfile.cpu -t tirex-inference-cpu . ``` -------------------------------- ### TiRex Forecast Output Types Source: https://github.com/nx-ai/tirex/blob/main/examples/quick_start_tirex.ipynb Demonstrates generating forecasts as 2D Torch tensors, NumPy arrays, and iterating through batches. Ensure `torch` or `numpy` is installed. ```python data = torch.tensor(data_short) # Default: 2D Torch tensor quantiles, means = model.forecast(context=data, prediction_length=24, output_type="torch") print("Predictions:\n", type(quantiles), quantiles.shape) # 2D Numpy Array quantiles, means = model.forecast(context=data, prediction_length=24, output_type="numpy") print("Predictions:\n", type(quantiles), quantiles.shape) # Iterate by patch # You can also use the forecast function as iterable. This might help with big datasets. All output_types are supported for i, fc_batch in enumerate( model.forecast(context=[data, data, data, data, data], batch_size=2, output_type="torch", yield_per_batch=True) ): quantiles, means = fc_batch print(f"Predictions batch {i}:\n", type(quantiles), quantiles.shape) ``` -------------------------------- ### Instantiate and Train TirexLinearRegressor Source: https://github.com/nx-ai/tirex/blob/main/docs/sphinx/source/tirex.regression.md Demonstrates how to initialize a TirexLinearRegressor with custom parameters, prepare training data, and train the model. The embedding backbone is frozen, and only the regression head is trained. ```python import torch from tirex.models.regression import TirexLinearRegressor # Create model with TiRex embeddings model = TirexLinearRegressor( data_augmentation=True, max_epochs=2, lr=1e-4, batch_size=32 ) # Prepare data X_train = torch.randn(100, 1, 128) # 100 samples, 1 number of variates, 128 sequence length y_train = torch.randn(100, 1) # target values # Train the model metrics = model.fit((X_train, y_train)) Epoch 1, Train Loss: ... # Make predictions X_test = torch.randn(20, 1, 128) predictions = model.predict(X_test) ```