### Install datasetsforecast Library Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/getting-started/datarequirements.ipynb Installs the datasetsforecast library, which is used for loading example datasets. ```python %%capture !pip install datasetsforecast ``` -------------------------------- ### Install Libraries Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/tutorials/transfer_learning.ipynb Installs the necessary libraries: datasetsforecast and neuralforecast. This is a prerequisite for running the examples. ```python %%capture !pip install datasetsforecast neuralforecast ``` -------------------------------- ### Install NeuralForecast Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/capabilities/predictInsample.ipynb Installs the neuralforecast library. This is a prerequisite for running the examples. ```python %%capture !pip install neuralforecast ``` -------------------------------- ### Install NeuralForecast and Hyperopt Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/capabilities/hyperparameter_tuning.ipynb Installs the necessary libraries for hyperparameter tuning. This is a prerequisite for running the examples. ```bash %%capture !pip install neuralforecast hyperopt ``` -------------------------------- ### Install NeuralForecast and Dependencies Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/tutorials/longhorizon_nhits.ipynb Installs the necessary libraries for NeuralForecast, datasetsforecast, and utilsforecast. This is a prerequisite for running the examples. ```python %%capture !pip install neuralforecast datasetsforecast utilsforecast ``` -------------------------------- ### Install NeuralForecast and DatasetsForecast Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/tutorials/longhorizon_probabilistic.ipynb Installs the necessary libraries for NeuralForecast and DatasetsForecast. This is typically the first step before using the library. ```python %%capture !pip install neuralforecast datasetsforecast ``` -------------------------------- ### Install Libraries Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/capabilities/time_series_scaling.ipynb Installs the necessary libraries for neural forecasting experiments. ```bash %%capture !pip install neuralforecast !pip install hyperopt ``` -------------------------------- ### Install NeuralForecast and DatasetsForecast Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/tutorials/multivariate_tsmixer.ipynb Installs the necessary libraries for neural network-based forecasting. Run this command in your environment before proceeding. ```bash !pip install neuralforecast datasetsforecast ``` -------------------------------- ### Install NeuralForecast Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/tutorials/getting_started_complete.ipynb Installs the NeuralForecast library. Use `%%capture` to suppress output. ```python %%capture ! pip install neuralforecast ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/nixtla/neuralforecast/blob/main/CONTRIBUTING.md Installs the pre-commit framework and runs it on the neuralforecast directory to ensure code quality before committing. ```bash pre-commit install pre-commit run --files neuralforecast/* ``` -------------------------------- ### Install necessary libraries Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/tutorials/converting_onnx.ipynb Installs the required libraries for ONNX conversion and inference. ```python %%capture !pip install neuralforecast onnxruntime onnxscript onnx ``` -------------------------------- ### Install Necessary Libraries Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/tutorials/comparing_methods.ipynb Installs the required libraries for statistical, machine learning, and neural forecasting. It's recommended to run this in a clean environment. ```python %%capture !pip install statsforecast mlforecast neuralforecast pyarrow ``` -------------------------------- ### Install Necessary Packages Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/tutorials/intermittent_data.ipynb Installs the required libraries for NeuralForecast, including statsforecast, s3fs, fastparquet, and neuralforecast. Use this to set up your environment. ```python %%capture !pip install statsforecast s3fs fastparquet neuralforecast ``` -------------------------------- ### Install Necessary Packages Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/use-cases/electricity_peak_forecasting.ipynb Installs the neuralforecast package using pip. Ensure NeuralForecast is installed before running this code. ```python import numpy as np import pandas as pd ``` -------------------------------- ### Install Machine Learning Libraries Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/tutorials/comparing_methods.ipynb Installs the LightGBM and XGBoost libraries, which are commonly used for gradient boosting models in machine learning. ```bash !pip install lightgbm xgboost ``` -------------------------------- ### Install NeuralForecast with pip Source: https://github.com/nixtla/neuralforecast/blob/main/README.md Use this command to install the NeuralForecast library using pip. ```bash pip install neuralforecast ``` -------------------------------- ### Install uv and Create Virtual Environment Source: https://github.com/nixtla/neuralforecast/blob/main/CONTRIBUTING.md Installs the uv package and creates a Python 3.11 virtual environment. This is the recommended first step for setting up your development environment. ```bash pip install uv uv venv --python 3.11 ``` -------------------------------- ### Install Neuralforecast and Datasetsforecast Source: https://github.com/nixtla/neuralforecast/blob/main/experiments/long_horizon/README.md Alternatively, install the necessary libraries directly using pip. This is useful if you prefer not to use conda environments or if the environment.yml is not available. ```shell pip install git+https://github.com/Nixtla/datasetsforecast.git ``` ```shell pip install git+https://github.com/Nixtla/neuralforecast.git ``` -------------------------------- ### Install Mintlify Source: https://github.com/nixtla/neuralforecast/blob/main/CONTRIBUTING.md Installs the Mintlify command-line interface globally using npm. This tool is used for managing and building project documentation. ```bash npm i -g mint ``` -------------------------------- ### DLinear Model Training and Forecasting Source: https://github.com/nixtla/neuralforecast/blob/main/docs/models.dlinear.html.md This example demonstrates how to use the DLinear model for time series forecasting. It includes data preparation, model instantiation, training, and prediction. Ensure you have the necessary libraries installed and data formatted correctly. ```python import pandas as pd import matplotlib.pyplot as plt from neuralforecast import NeuralForecast from neuralforecast.models import DLinear from neuralforecast.utils import AirPassengersPanel, AirPassengersStatic, augment_calendar_df AirPassengersPanel, calendar_cols = augment_calendar_df(df=AirPassengersPanel, freq='M') Y_train_df = AirPassengersPanel[AirPassengersPanel.ds=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test model = DLinear(h=12, input_size=24, loss=MAE(), scaler_type='robust', learning_rate=1e-3, max_steps=500, val_check_steps=50, early_stop_patience_steps=2) nf = NeuralForecast( models=[model], freq='ME' ) nf.fit(df=Y_train_df, static_df=AirPassengersStatic, val_size=12) forecasts = nf.predict(futr_df=Y_test_df) Y_hat_df = forecasts.reset_index(drop=False).drop(columns=['unique_id','ds']) plot_df = pd.concat([Y_test_df, Y_hat_df], axis=1) plot_df = pd.concat([Y_train_df, plot_df]) if model.loss.is_distribution_output: plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1) plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True') plt.plot(plot_df['ds'], plot_df['DLinear-median'], c='blue', label='median') plt.fill_between(x=plot_df['ds'][-12:], y1=plot_df['DLinear-lo-90'][-12:].values, y2=plot_df['DLinear-hi-90'][-12:].values, alpha=0.4, label='level 90') plt.grid() plt.legend() plt.plot() else: plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1) plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True') plt.plot(plot_df['ds'], plot_df['DLinear'], c='blue', label='Forecast') plt.legend() plt.grid() ``` -------------------------------- ### Install Development Dependencies with CPU PyTorch Backend Source: https://github.com/nixtla/neuralforecast/blob/main/CONTRIBUTING.md Installs the library's development dependencies using uv, specifically for the CPU PyTorch backend. ```bash uv sync --group dev --torch-backend cpu ``` -------------------------------- ### BaseAuto Initialization and Fitting with Optuna Backend Source: https://github.com/nixtla/neuralforecast/blob/main/docs/common.base_auto.html.md Initializes and fits the BaseAuto model using the Optuna backend for hyperparameter optimization. This example shows how to specify Optuna-specific samplers and callbacks. ```python auto2 = BaseAuto(h=12, loss=MAE(), valid_loss=MSE(), cls_model=MLP, config=config_f, search_alg=optuna.samplers.RandomSampler(), num_samples=2, backend='optuna', callbacks=[OptunaLogLossesCallback()]) auto2.fit(dataset=dataset) assert isinstance(auto2.results, optuna.Study) y_hat2 = auto2.predict(dataset=dataset) assert mae(Y_test_df['y'].values, y_hat2[:, 0]) < 200 ``` -------------------------------- ### Install Development Dependencies with Auto PyTorch Backend Source: https://github.com/nixtla/neuralforecast/blob/main/CONTRIBUTING.md Installs the library's development dependencies using uv, automatically selecting the optimal PyTorch backend. ```bash uv sync --group dev --torch-backend auto ``` -------------------------------- ### Install NeuralForecast in Development Mode Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/getting-started/introduction.ipynb Clone the repository and install NeuralForecast in editable mode to make code modifications and see effects in real-time without reinstalling. This is useful for development. ```bash git clone https://github.com/Nixtla/neuralforecast.git cd neuralforecast pip install -e . ``` -------------------------------- ### Install Necessary Packages Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/tutorials/hierarchical_forecasting.ipynb Installs the required libraries for hierarchical forecasting, including datasetsforecast, hierarchicalforecast, neuralforecast, and statsforecast. This command is typically run in a notebook environment. ```bash %%capture !pip install datasetsforecast hierarchicalforecast neuralforecast statsforecast ``` -------------------------------- ### Install NeuralForecast with Conda Source: https://github.com/nixtla/neuralforecast/blob/main/README.md Use this command to install the NeuralForecast library using Conda. ```bash conda install -c conda-forge neuralforecast ``` -------------------------------- ### Minimal NeuralForecast Example Source: https://github.com/nixtla/neuralforecast/blob/main/README.md A basic example demonstrating how to initialize NeuralForecast with the NBEATS model, fit it to data, and make predictions. Ensure you have the AirPassengersDF dataset available. ```python from neuralforecast import NeuralForecast from neuralforecast.models import NBEATS from neuralforecast.utils import AirPassengersDF nf = NeuralForecast( models = [NBEATS(input_size=24, h=12, max_steps=100)], freq = 'ME' ) nf.fit(df=AirPassengersDF) nf.predict() ``` -------------------------------- ### Install Optional Dependencies Source: https://github.com/nixtla/neuralforecast/blob/main/CONTRIBUTING.md Installs additional optional dependencies for the library, including AWS and Spark support, alongside development dependencies. ```bash uv sync --group dev --group aws --extra spark ``` -------------------------------- ### Example Google-Style Docstring Source: https://github.com/nixtla/neuralforecast/blob/main/CONTRIBUTING.md Demonstrates the structure and content of a Google-style docstring for Python functions, including sections for arguments, return values, exceptions, examples, and notes. ```python def function_name(parameter1, parameter2): """Brief summary of the function's purpose. Detailed explanation of what the function does, its behavior, and any important considerations. This section can span multiple lines. Args: parameter1 (type): Description of parameter1. parameter2 (type): Description of parameter2. Returns: type: Description of the return value. Raises: ExceptionType: Description of the circumstances under which this exception is raised. Example: Examples can be provided to demonstrate how to use the function. Literal blocks can be included for code snippets:: result = function_name(10, 'hello') print(result) Notes: Any additional notes or important information. """ # Function implementation pass ``` -------------------------------- ### BaseAuto Initialization and Fitting with Ray Tune Source: https://github.com/nixtla/neuralforecast/blob/main/docs/common.base_auto.html.md Initializes and fits the BaseAuto model using Ray Tune for hyperparameter optimization. This example demonstrates configuring the model, search space, and callbacks for automated tuning. ```python config = { "hidden_size": tune.choice([512]), "num_layers": tune.choice([3, 4]), "input_size": 12, "max_steps": 10, "val_check_steps": 5 } auto = BaseAuto(h=12, loss=MAE(), valid_loss=MSE(), cls_model=MLP, config=config, num_samples=2, cpus=1, gpus=0, callbacks=[RayLogLossesCallback()]) auto.fit(dataset=dataset) y_hat = auto.predict(dataset=dataset) assert mae(Y_test_df['y'].values, y_hat[:, 0]) < 200 ``` -------------------------------- ### Import necessary libraries Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/tutorials/explainability.ipynb Imports core libraries for data manipulation, modeling, and explainability. Ensure Captum and optionally SHAP are installed. ```python import matplotlib.pyplot as plt import numpy as np import pandas as pd import torch from neuralforecast.core import NeuralForecast from neuralforecast.models import MLPMultivariate, NHITS from neuralforecast.losses.pytorch import MQLoss from neuralforecast.utils import AirPassengersPanel, AirPassengersStatic ``` -------------------------------- ### LightningDataModule Example Source: https://github.com/nixtla/neuralforecast/blob/main/docs/tsdataset.html.md Demonstrates how to set up a LightningDataModule for training, validation, and testing using PyTorch's DataLoader and RandomDataset. Useful for integrating custom datasets with PyTorch Lightning trainers. ```python import lightning.pytorch as L import torch.utils.data as data from pytorch_lightning.demos.boring_classes import RandomDataset class MyDataModule(L.LightningDataModule): def prepare_data(self): # download, IO, etc. Useful with shared filesystems # only called on 1 GPU/TPU in distributed ... def setup(self, stage): # make assignments here (val/train/test split) # called on every process in DDP dataset = RandomDataset(1, 100) self.train, self.val, self.test = data.random_split( dataset, [80, 10, 10], generator=torch.Generator().manual_seed(42) ) def train_dataloader(self): return data.DataLoader(self.train) def val_dataloader(self): return data.DataLoader(self.val) def test_dataloader(self): return data.DataLoader(self.test) def on_exception(self, exception): # clean up state after the trainer faced an exception ... def teardown(self): # clean up state after the trainer stops, delete files... # called on every process in DDP ... ``` -------------------------------- ### Vanilla Transformer Usage Example Source: https://github.com/nixtla/neuralforecast/blob/main/docs/models.vanillatransformer.html.md Demonstrates how to instantiate, train, and predict with the Vanilla Transformer model using sample time series data. Requires pandas and matplotlib for data manipulation and plotting. ```python import pandas as pd import matplotlib.pyplot as plt from neuralforecast import NeuralForecast from neuralforecast.models import VanillaTransformer from neuralforecast.utils import AirPassengersPanel, AirPassengersStatic Y_train_df = AirPassengersPanel[AirPassengersPanel.ds=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test model = VanillaTransformer(h=12, input_size=24, hidden_size=16, conv_hidden_size=32, n_head=2, loss=MAE(), scaler_type='robust', learning_rate=1e-3, max_steps=500, val_check_steps=50, early_stop_patience_steps=2) nf = NeuralForecast( models=[model], freq='ME' ) nf.fit(df=Y_train_df, static_df=AirPassengersStatic, val_size=12) forecasts = nf.predict(futr_df=Y_test_df) Y_hat_df = forecasts.reset_index(drop=False).drop(columns=['unique_id','ds']) plot_df = pd.concat([Y_test_df, Y_hat_df], axis=1) plot_df = pd.concat([Y_train_df, plot_df]) if model.loss.is_distribution_output: plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1) plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True') plt.plot(plot_df['ds'], plot_df['VanillaTransformer-median'], c='blue', label='median') plt.fill_between(x=plot_df['ds'][-12:], y1=plot_df['VanillaTransformer-lo-90'][-12:].values, y2=plot_df['VanillaTransformer-hi-90'][-12:].values, alpha=0.4, label='level 90') plt.grid() plt.legend() plt.plot() else: plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1) plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True') plt.plot(plot_df['ds'], plot_df['VanillaTransformer'], c='blue', label='Forecast') plt.legend() plt.grid() ``` -------------------------------- ### Import Necessary Libraries Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/getting-started/introduction.ipynb Import core libraries for logging, data manipulation, plotting, and NeuralForecast models and utilities. This setup is required before using the library. ```python import logging import pandas as pd from utilsforecast.plotting import plot_series from neuralforecast import NeuralForecast from neuralforecast.models import NBEATS, NHITS from neuralforecast.utils import AirPassengersDF ``` -------------------------------- ### RNN Model Usage Example Source: https://github.com/nixtla/neuralforecast/blob/main/docs/models.rnn.html.md Demonstrates how to instantiate, train, and predict with the RNN model using NeuralForecast. Includes data preparation, model configuration with exogenous variables and loss functions, and plotting the results. ```python import pandas as pd import matplotlib.pyplot as plt from neuralforecast import NeuralForecast from neuralforecast.models import RNN from neuralforecast.losses.pytorch import MQLoss from neuralforecast.utils import AirPassengersPanel, AirPassengersStatic Y_train_df = AirPassengersPanel[AirPassengersPanel.ds=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test fcst = NeuralForecast( models=[RNN(h=12, input_size=24, inference_input_size=24, loss=MQLoss(level=[80, 90]), valid_loss=MQLoss(level=[80, 90]), scaler_type='standard', encoder_n_layers=2, encoder_hidden_size=128, decoder_hidden_size=128, decoder_layers=2, max_steps=200, futr_exog_list=['y_[lag12]'], stat_exog_list=['airline1'], ) ], freq='ME' ) fcst.fit(df=Y_train_df, static_df=AirPassengersStatic, val_size=12) forecasts = fcst.predict(futr_df=Y_test_df) Y_hat_df = forecasts.reset_index(drop=False).drop(columns=['unique_id','ds']) plot_df = pd.concat([Y_test_df, Y_hat_df], axis=1) plot_df = pd.concat([Y_train_df, plot_df]) plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1) plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True') plt.plot(plot_df['ds'], plot_df['RNN-median'], c='blue', label='median') plt.fill_between(x=plot_df['ds'][-12:], y1=plot_df['RNN-lo-90'][-12:].values, y2=plot_df['RNN-hi-90'][-12:].values, alpha=0.4, label='level 90') plt.legend() plt.grid() plt.plot() ``` -------------------------------- ### Complete Mask and Incomplete Horizon Weight Example Source: https://github.com/nixtla/neuralforecast/blob/main/scripts/cli.ipynb Demonstrates how to use a complete mask and an incomplete horizon_weight with the MAE metric. This scenario highlights error calculation when certain future points are masked. ```python mask = torch.Tensor([[1,1,1],[1,1,1]]).unsqueeze(-1) horizon_weight = torch.Tensor([1,1,0]) # 2 errors and points are masked. mae = MAE(horizon_weight=horizon_weight) loss = mae(y=y, y_hat=y_hat, mask=mask) assert loss==(1/4), 'Should be 1/4' ``` -------------------------------- ### Show MAPE Initialization Documentation Source: https://github.com/nixtla/neuralforecast/blob/main/scripts/cli.ipynb Displays the documentation for the `MAPE` class constructor. Useful for understanding initialization parameters like `horizon_weight`. ```python show_doc(MAPE, name='MAPE.__init__', title_level=3) ``` -------------------------------- ### DeepNPTS Usage Example Source: https://github.com/nixtla/neuralforecast/blob/main/docs/models.deepnpts.html.md Demonstrates how to use the DeepNPTS model for time series forecasting. It includes data preparation, model initialization, fitting, prediction, and plotting of results. Ensure you have pandas and matplotlib installed for plotting. ```python import pandas as pd import matplotlib.pyplot as plt from neuralforecast import NeuralForecast from neuralforecast.models import DeepNPTS from neuralforecast.utils import AirPassengersPanel, AirPassengersStatic Y_train_df = AirPassengersPanel[AirPassengersPanel.ds=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test nf = NeuralForecast( models=[DeepNPTS(h=12, input_size=24, stat_exog_list=['airline1'], futr_exog_list=['trend'], max_steps=1000, val_check_steps=10, early_stop_patience_steps=3, scaler_type='robust', enable_progress_bar=True), ], freq='ME' ) nf.fit(df=Y_train_df, static_df=AirPassengersStatic, val_size=12) Y_hat_df = nf.predict(futr_df=Y_test_df) # Plot quantile predictions Y_hat_df = Y_hat_df.reset_index(drop=False).drop(columns=['unique_id','ds']) plot_df = pd.concat([Y_test_df, Y_hat_df], axis=1) plot_df = pd.concat([Y_train_df, plot_df]) plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1) plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True') plt.plot(plot_df['ds'], plot_df['DeepNPTS'], c='red', label='mean') plt.grid() plt.plot() ``` -------------------------------- ### Preview Documentation Locally Source: https://github.com/nixtla/neuralforecast/blob/main/CONTRIBUTING.md Runs the make command to generate and preview the project documentation locally. This allows for testing changes before deployment. ```bash make preview_docs ``` -------------------------------- ### SOFTSSharp Model Usage Example Source: https://github.com/nixtla/neuralforecast/blob/main/docs/models.softssharp.html.md Demonstrates how to instantiate and use the SOFTSSharp model for time series forecasting. It includes data preparation, model initialization, training, and prediction, followed by plotting the results. ```python import pandas as pd import matplotlib.pyplot as plt from neuralforecast import NeuralForecast from neuralforecast.models import SOFTSSharp from neuralforecast.utils import AirPassengersPanel, AirPassengersStatic from neuralforecast.losses.pytorch import MASE Y_train_df = AirPassengersPanel[AirPassengersPanel.ds=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) model = SOFTSSharp(h=12, input_size=24, n_series=2, hidden_size=256, d_core=256, e_layers=2, d_ff=64, dropout=0.1, pe_keep_prob=0.5, use_norm=True, loss=MASE(seasonality=4), early_stop_patience_steps=3, batch_size=32) fcst = NeuralForecast(models=[model], freq='ME') fcst.fit(df=Y_train_df, static_df=AirPassengersStatic, val_size=12) forecasts = fcst.predict(futr_df=Y_test_df) fig, ax = plt.subplots(1, 1, figsize = (20, 7)) Y_hat_df = forecasts.reset_index(drop=False).drop(columns=['unique_id','ds']) plot_df = pd.concat([Y_test_df, Y_hat_df], axis=1) plot_df = pd.concat([Y_train_df, plot_df]) plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1) plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True') plt.plot(plot_df['ds'], plot_df['SOFTSSharp'], c='blue', label='Forecast') ax.set_title('AirPassengers Forecast', fontsize=22) ax.set_ylabel('Monthly Passengers', fontsize=20) ax.set_xlabel('Year', fontsize=20) ax.legend(prop={'size': 15}) ax.grid() ``` -------------------------------- ### Informer Model Usage Example Source: https://github.com/nixtla/neuralforecast/blob/main/docs/models.informer.html.md Demonstrates how to instantiate, train, and predict with the Informer model using the NeuralForecast library. Includes data preparation, model configuration, and plotting the results. Ensure necessary libraries like pandas and matplotlib are installed. ```python import pandas as pd import matplotlib.pyplot as plt from neuralforecast import NeuralForecast from neuralforecast.models import Informer from neuralforecast.utils import AirPassengersPanel, AirPassengersStatic, augment_calendar_df AirPassengersPanel, calendar_cols = augment_calendar_df(df=AirPassengersPanel, freq='M') Y_train_df = AirPassengersPanel[AirPassengersPanel.ds=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test model = Informer(h=12, input_size=24, hidden_size = 16, conv_hidden_size = 32, n_head = 2, loss=MAE(), futr_exog_list=calendar_cols, scaler_type='robust', learning_rate=1e-3, max_steps=200, val_check_steps=50, early_stop_patience_steps=2) nf = NeuralForecast( models=[model], freq='ME' ) nf.fit(df=Y_train_df, static_df=AirPassengersStatic, val_size=12) forecasts = nf.predict(futr_df=Y_test_df) Y_hat_df = forecasts.reset_index(drop=False).drop(columns=['unique_id','ds']) plot_df = pd.concat([Y_test_df, Y_hat_df], axis=1) plot_df = pd.concat([Y_train_df, plot_df]) if model.loss.is_distribution_output: plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1) plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True') plt.plot(plot_df['ds'], plot_df['Informer-median'], c='blue', label='median') plt.fill_between(x=plot_df['ds'][-12:], y1=plot_df['Informer-lo-90'][-12:].values, y2=plot_df['Informer-hi-90'][-12:].values, alpha=0.4, label='level 90') plt.grid() plt.legend() plt.plot() else: plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1) plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True') plt.plot(plot_df['ds'], plot_df['Informer'], c='blue', label='Forecast') plt.legend() plt.grid() ``` -------------------------------- ### MLPMultivariate Usage Example Source: https://github.com/nixtla/neuralforecast/blob/main/docs/models.mlpmultivariate.html.md Demonstrates how to use the MLPMultivariate model for joint multivariate forecasting. It includes data preparation, model instantiation with specified parameters, training, prediction, and plotting the results. Ensure you have the necessary libraries installed and data formatted correctly. ```python import pandas as pd import matplotlib.pyplot as plt from neuralforecast import NeuralForecast from neuralforecast.models import MLPMultivariate from neuralforecast.losses.pytorch import MAE from neuralforecast.utils import AirPassengersPanel, AirPassengersStatic Y_train_df = AirPassengersPanel[AirPassengersPanel.ds=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test model = MLPMultivariate(h=12, input_size=24, n_series=2, stat_exog_list=['airline1'], futr_exog_list=['trend'], loss = MAE(), scaler_type='robust', learning_rate=1e-3, stat_exog_list=['airline1'], max_steps=200, val_check_steps=10, early_stop_patience_steps=2) fcst = NeuralForecast( models=[model], freq='ME' ) fcst.fit(df=Y_train_df, static_df=AirPassengersStatic, val_size=12) forecasts = fcst.predict(futr_df=Y_test_df) # Plot predictions Y_hat_df = forecasts.reset_index(drop=False).drop(columns=['unique_id','ds']) plot_df = pd.concat([Y_test_df, Y_hat_df], axis=1) plot_df = pd.concat([Y_train_df, plot_df]) plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1) plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True') plt.plot(plot_df['ds'], plot_df['MLPMultivariate'], c='blue', label='median') plt.grid() plt.legend() plt.plot() ``` -------------------------------- ### NBEATSx Model Training and Prediction Source: https://github.com/nixtla/neuralforecast/blob/main/docs/models.nbeatsx.html.md This example demonstrates how to instantiate, train, and predict using the NBE-ATSx model with exogenous variables. It includes data preparation, model configuration with custom loss and exogenous features, forecasting, and plotting of results. Ensure you have the necessary libraries installed and data formatted correctly. ```python import pandas as pd import matplotlib.pyplot as plt from neuralforecast import NeuralForecast from neuralforecast.models import NBEATSx from neuralforecast.losses.pytorch import MQLoss from neuralforecast.utils import AirPassengersPanel, AirPassengersStatic Y_train_df = AirPassengersPanel[AirPassengersPanel.ds=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test model = NBEATSx(h=12, input_size=24, loss=MQLoss(level=[80, 90]), scaler_type='robust', dropout_prob_theta=0.5, stat_exog_list=['airline1'], futr_exog_list=['trend'], stack_types = ["identity", "trend", "seasonality", "exogenous"], n_blocks = [1,1,1,1], max_steps=200, val_check_steps=10, early_stop_patience_steps=2) nf = NeuralForecast( models=[model], freq='ME' ) nf.fit(df=Y_train_df, static_df=AirPassengersStatic, val_size=12) Y_hat_df = nf.predict(futr_df=Y_test_df) # Plot quantile predictions Y_hat_df = Y_hat_df.reset_index(drop=False).drop(columns=['unique_id','ds']) plot_df = pd.concat([Y_test_df, Y_hat_df], axis=1) plot_df = pd.concat([Y_train_df, plot_df]) plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1) plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True') plt.plot(plot_df['ds'], plot_df['NBEATSx-median'], c='blue', label='median') plt.fill_between(x=plot_df['ds'][-12:], y1=plot_df['NBEATSx-lo-90'][-12:].values, y2=plot_df['NBEATSx-hi-90'][-12:].values, alpha=0.4, label='level 90') plt.legend() plt.grid() plt.plot() ``` -------------------------------- ### Show MAE Initialization Documentation Source: https://github.com/nixtla/neuralforecast/blob/main/scripts/cli.ipynb Displays the documentation for the MAE class constructor. ```python show_doc(MAE, name='MAE.__init__', title_level=3) ``` -------------------------------- ### Display MSE Initialization Documentation Source: https://github.com/nixtla/neuralforecast/blob/main/scripts/cli.ipynb Shows the documentation for the MSE class constructor, detailing its parameters. ```python show_doc(MSE, name='MSE.__init__', title_level=3) ``` -------------------------------- ### Install Seaborn for Plotting Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/tutorials/comparing_methods.ipynb Installs the `seaborn` library, which is used for creating statistical visualizations. ```bash !pip install seaborn ``` -------------------------------- ### Display relMSE Initialization Documentation Source: https://github.com/nixtla/neuralforecast/blob/main/scripts/cli.ipynb Displays the documentation for the relMSE class initialization method using `show_doc`. ```python show_doc(relMSE, name='relMSE.__init__', title_level=3) ``` -------------------------------- ### Display SMAPE Initialization Documentation Source: https://github.com/nixtla/neuralforecast/blob/main/scripts/cli.ipynb Shows the documentation for the SMAPE class constructor. Use this to understand the parameters required for initializing the SMAPE loss function. ```python show_doc(SMAPE, name='SMAPE.__init__', title_level=3) ``` -------------------------------- ### Generate Documentation Source: https://github.com/nixtla/neuralforecast/blob/main/CONTRIBUTING.md Runs the make command to generate all project documentation. This command orchestrates the documentation build process. ```bash make all_docs ``` -------------------------------- ### Display MASE Initialization Documentation Source: https://github.com/nixtla/neuralforecast/blob/main/scripts/cli.ipynb Shows the documentation for the MASE loss function's initialization method. ```python show_doc(MASE, name='MASE.__init__', title_level=3) ``` -------------------------------- ### Initialize, Fit, and Explain NeuralForecast Model Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/tutorials/explainability.ipynb Demonstrates the process of initializing a multivariate model, fitting it to training data, and generating explanations using the Integrated Gradients explainer. ```python models = [ MLPMultivariate( h=12, input_size=24, n_series=2, hist_exog_list=["y_[lag12]"] , futr_exog_list=["trend"], stat_exog_list=['airline1'], max_steps=20, scaler_type="robust", ), ] nf = NeuralForecast( models=models, freq="ME", ) # Fit model nf.fit( df=Y_train_df, static_df=AirPassengersStatic ) # Get predictions and attributions preds_df, explanations = nf.explain( static_df=AirPassengersStatic, futr_df=futr_df, explainer="IntegratedGradients" ) ``` -------------------------------- ### Set Multiprocessing Start Method Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/tutorials/comparing_methods.ipynb Sets the multiprocessing start method to 'spawn'. This is often required for compatibility with certain libraries, especially on macOS and Windows. ```python #| echo: false import multiprocessing multiprocessing.set_start_method('spawn') ``` -------------------------------- ### Display RMSE Initialization Documentation Source: https://github.com/nixtla/neuralforecast/blob/main/scripts/cli.ipynb Shows the documentation for the RMSE class constructor, detailing its parameters. ```python show_doc(RMSE, name='RMSE.__init__', title_level=3) ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/nixtla/neuralforecast/blob/main/CONTRIBUTING.md Change the current directory to the cloned neuralforecast project. ```bash cd neuralforecast ``` -------------------------------- ### DeepNPTS Usage Example Source: https://github.com/nixtla/neuralforecast/blob/main/docs/models.deepnpts.html.md An example demonstrating how to use the DeepNPTS model within the NeuralForecast framework, including data preparation, model instantiation, fitting, and prediction. ```APIDOC ### Usage Example ```python import pandas as pd import matplotlib.pyplot as plt from neuralforecast import NeuralForecast from neuralforecast.models import DeepNPTS from neuralforecast.utils import AirPassengersPanel, AirPassengersStatic Y_train_df = AirPassengersPanel[AirPassengersPanel.ds=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test nf = NeuralForecast( models=[DeepNPTS(h=12, input_size=24, stat_exog_list=['airline1'], futr_exog_list=['trend'], max_steps=1000, val_check_steps=10, early_stop_patience_steps=3, scaler_type='robust', enable_progress_bar=True), ], freq='ME' ) nf.fit(df=Y_train_df, static_df=AirPassengersStatic, val_size=12) Y_hat_df = nf.predict(futr_df=Y_test_df) # Plot quantile predictions Y_hat_df = Y_hat_df.reset_index(drop=False).drop(columns=['unique_id','ds']) plot_df = pd.concat([Y_test_df, Y_hat_df], axis=1) plot_df = pd.concat([Y_train_df, plot_df]) plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1) plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True') plt.plot(plot_df['ds'], plot_df['DeepNPTS'], c='red', label='mean') plt.grid() plt.plot() ``` ``` -------------------------------- ### Install Development Dependencies with CUDA 11.8 PyTorch Backend Source: https://github.com/nixtla/neuralforecast/blob/main/CONTRIBUTING.md Installs the library's development dependencies using uv, targeting the CUDA 11.8 PyTorch backend. ```bash uv sync --group dev --torch-backend cu118 ``` -------------------------------- ### Incomplete Mask and Horizon Weight Example Source: https://github.com/nixtla/neuralforecast/blob/main/scripts/cli.ipynb Demonstrates the usage of MAE loss with an incomplete mask and a horizon weight. This example calculates the loss for a time series, masking specific points and weights. ```python mask = torch.Tensor([[0,1,1],[1,1,1]]).unsqueeze(-1) horizon_weight = torch.Tensor([1,1,0]) # 2 errors are masked, and 3 points. mae = MAE(horizon_weight=horizon_weight) loss = mae(y=y, y_hat=y_hat, mask=mask) assert loss==(1/3), 'Should be 1/3' ``` -------------------------------- ### Instantiate MQLoss with quantiles Source: https://github.com/nixtla/neuralforecast/blob/main/scripts/cli.ipynb Instantiate MQLoss by directly providing the quantile values. This allows for precise control over the predicted quantiles. ```python check = MQLoss(quantiles=[0.0100, 0.1000, 0.5, 0.9000, 0.9900]) print(check.output_names) print(check.quantiles) test_eq(len(check.quantiles), 5) ``` ```python check = MQLoss(quantiles=[0.0100, 0.1000, 0.9000, 0.9900]) test_eq(len(check.quantiles), 4) ``` -------------------------------- ### Instantiate StatsForecast Class Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/tutorials/comparing_methods.ipynb Initializes the StatsForecast class with specified models, frequency, number of jobs, and verbosity. Use this to set up the forecasting environment. ```python sf = StatsForecast( models=models, # A list of models to be used for forecasting freq='D', # The frequency of the time series data (in this case, 'D' stands for daily frequency) n_jobs=-1, # The number of CPU cores to use for parallel execution (-1 means use all available cores) verbose=True, # Show progress ) ``` -------------------------------- ### SOFTS Usage Example Source: https://github.com/nixtla/neuralforecast/blob/main/docs/models.softs.html.md This example demonstrates how to instantiate, train, and use the SOFTS model for time series forecasting with the NeuralForecast library. It includes data preparation, model configuration, fitting, prediction, and plotting. ```APIDOC ## Usage Example ### Code ```python import pandas as pd import matplotlib.pyplot as plt from neuralforecast import NeuralForecast from neuralforecast.models import SOFTS from neuralforecast.utils import AirPassengersPanel, AirPassengersStatic from neuralforecast.losses.pytorch import MASE # Prepare training and testing data Y_train_df = AirPassengersPanel[AirPassengersPanel.ds < AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 132 train Y_test_df = AirPassengersPanel[AirPassengersPanel.ds >= AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test # Instantiate the SOFTS model model = SOFTS(h=12, input_size=24, n_series=2, hidden_size=256, d_core=256, e_layers=2, d_ff=64, dropout=0.1, use_norm=True, loss=MASE(seasonality=4), early_stop_patience_steps=3, batch_size=32) # Initialize NeuralForecast fcst = NeuralForecast(models=[model], freq='ME') # Fit the model fcst.fit(df=Y_train_df, static_df=AirPassengersStatic, val_size=12) # Make predictions forecasts = fcst.predict(futr_df=Y_test_df) # Plot predictions fig, ax = plt.subplots(1, 1, figsize = (20, 7)) Y_hat_df = forecasts.reset_index(drop=False).drop(columns=['unique_id','ds']) plot_df = pd.concat([Y_test_df, Y_hat_df], axis=1) plot_df = pd.concat([Y_train_df, plot_df]) plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1) plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True') plt.plot(plot_df['ds'], plot_df['SOFTS'], c='blue', label='Forecast') ax.set_title('AirPassengers Forecast', fontsize=22) ax.set_ylabel('Monthly Passengers', fontsize=20) ax.set_xlabel('Year', fontsize=20) ax.legend(prop={'size': 15}) ax.grid() ``` ``` -------------------------------- ### TimeMixer Cross-Validation Example Source: https://github.com/nixtla/neuralforecast/blob/main/docs/models.timemixer.html.md Illustrates how to perform cross-validation with the TimeMixer model to forecast multiple historic values. This method is useful for evaluating model performance across different time windows. The example includes plotting the cross-validated forecasts. ```python fcst = NeuralForecast(models=[model], freq='M') forecasts = fcst.cross_validation(df=AirPassengersPanel, static_df=AirPassengersStatic, n_windows=2, step_size=12) # Plot predictions fig, ax = plt.subplots(1, 1, figsize = (20, 7)) Y_hat_df = forecasts.loc['Airline1'] Y_df = AirPassengersPanel[AirPassengersPanel['unique_id']=='Airline1'] plt.plot(Y_df['ds'], Y_df['y'], c='black', label='True') plt.plot(Y_hat_df['ds'], Y_hat_df['TimeMixer'], c='blue', label='Forecast') ax.set_title('AirPassengers Forecast', fontsize=22) ax.set_ylabel('Monthly Passengers', fontsize=20) ax.set_xlabel('Year', fontsize=20) ax.legend(prop={'size': 15}) ax.grid() ``` -------------------------------- ### Get Unique Cutoffs Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/tutorials/comparing_methods.ipynb Extracts the unique cutoff values from the cross-validation dataframe. ```python cutoffs = cv_df['cutoff'].unique() ``` -------------------------------- ### NLinear Model Training and Forecasting Example Source: https://github.com/nixtla/neuralforecast/blob/main/docs/models.nlinear.html.md Demonstrates how to initialize, train, and predict using the NLinear model with the AirPassengers dataset. Includes data preparation, model configuration with custom loss and scaler, and plotting of results. ```python import pandas as pd import matplotlib.pyplot as plt from neuralforecast import NeuralForecast from neuralforecast.models import NLinear from neuralforecast.losses.pytorch import DistributionLoss from neuralforecast.utils import AirPassengersPanel, AirPassengersStatic, augment_calendar_df AirPassengersPanel, calendar_cols = augment_calendar_df(df=AirPassengersPanel, freq='M') Y_train_df = AirPassengersPanel[AirPassengersPanel.ds=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test model = NLinear(h=12, input_size=24, loss=DistributionLoss(distribution='StudentT', level=[80, 90], return_params=True), scaler_type='robust', learning_rate=1e-3, max_steps=500, val_check_steps=50, early_stop_patience_steps=2) nf = NeuralForecast( models=[model], freq='ME' ) nf.fit(df=Y_train_df, static_df=AirPassengersStatic, val_size=12) forecasts = nf.predict(futr_df=Y_test_df) Y_hat_df = forecasts.reset_index(drop=False).drop(columns=['unique_id','ds']) plot_df = pd.concat([Y_test_df, Y_hat_df], axis=1) plot_df = pd.concat([Y_train_df, plot_df]) if model.loss.is_distribution_output: plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1) plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True') plt.plot(plot_df['ds'], plot_df['NLinear-median'], c='blue', label='median') plt.fill_between(x=plot_df['ds'][-12:], y1=plot_df['NLinear-lo-90'][-12:].values, y2=plot_df['NLinear-hi-90'][-12:].values, alpha=0.4, label='level 90') plt.grid() plt.legend() plt.plot() else: plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1) plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True') plt.plot(plot_df['ds'], plot_df['NLinear'], c='blue', label='Forecast') plt.legend() plt.grid() ``` -------------------------------- ### Get Attention Weights Source: https://github.com/nixtla/neuralforecast/blob/main/docs/models.tft.html.md Retrieves the attention weights from a trained NeuralForecast model. This is the first step before plotting or analyzing them. ```python attention = nf.models[0].attention_weights() ``` -------------------------------- ### Instantiate PMM with quantiles Source: https://github.com/nixtla/neuralforecast/blob/main/scripts/cli.ipynb Instantiate a PMM by directly providing the desired quantile values. This allows for precise control over the predicted quantiles. ```python check = PMM(n_components=2, quantiles=[0.0100, 0.1000, 0.5, 0.9000, 0.9900]) print(check.output_names) print(check.quantiles) test_eq(len(check.quantiles), 5) ``` ```python check = PMM(n_components=2, quantiles=[0.0100, 0.1000, 0.9000, 0.9900]) test_eq(len(check.quantiles), 4) ``` -------------------------------- ### Import NeuralForecast and Models Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/tutorials/cross_validation.ipynb Import the `NeuralForecast` class and the desired models (MLP, NBEATS, NHITS) along with the `MQLoss` for training. ```python from neuralforecast import NeuralForecast from neuralforecast.auto import MLP, NBEATS, NHITS from neuralforecast.losses.pytorch import MQLoss ``` -------------------------------- ### MLflow UI command Source: https://github.com/nixtla/neuralforecast/blob/main/nbs/docs/tutorials/using_mlflow.ipynb Command to start the MLflow UI for visualizing experiments. Access the UI via the printed URL. ```bash mlflow ui ```