# Time Series Forecasting Made Easy with Darts in Python

- Canonical: https://33rdsquare.com/time-series-forecasting-made-easy-using-darts/
- Published: 2024-09-03
- Author: Jordan Brown
- Categories: [Artificial Intelligence & Machine Learning & ChatGPT](https://33rdsquare.com/category/tech/ai/)

---

Time series forecasting is a crucial task across many domains, from predicting sales and stock prices to analyzing sensor data and weather patterns. Building accurate time series models has traditionally required complex statistical methods, meticulous data preprocessing, and significant domain expertise.

However, the Darts library in Python aims to simplify time series forecasting and make it more accessible to data scientists and developers. Darts provides a unified interface for working with time series data and includes a variety of classical and deep learning models out-of-the-box.

In this post, we‘ll explore how to get started with Darts for time series forecasting. We‘ll walk through the key steps of loading data, preprocessing, training models, and evaluating performance. By the end, you‘ll see how Darts can help tackle real-world time series problems more easily and efficiently. Let‘s dive in!

## What is Darts?

Darts is an open-source Python library for easy manipulation and forecasting of time series. It contains a variety of models, from classical statistical models to state-of-the-art deep learning models.

Some key features of Darts include:

- Support for univariate and multivariate time series
- Data processing tools for scaling, imputation, lags, etc.
- Wide variety of forecasting models:
  - Statistical models like ARIMA, exponential smoothing, Theta, etc.
  - Regression models like linear regression and RandomForest
  - Deep learning models like RNNs, TCNs, Transformers (e.g. N-BEATS)
- Training and inference with numpy/pandas adapters
- Backtesting and hyperparameter tuning
- Hierarchical/grouped models and ensembling
- Interactive visualizations

Darts aims to do for time series what scikit-learn did for machine learning – provide a consistent interface and make advanced modeling more accessible. With Darts, we can quickly experiment with different model types, input parameters, and evaluation schemes.

## Installing Darts

To get started, we first need to install Darts. It‘s recommended to use a virtual environment:

```
conda create -n darts_env
conda activate darts_env
conda install -c conda-forge -c pytorch u8darts-all
```

This will install Darts and all its dependencies, including PyTorch. We can then launch a Jupyter notebook and verify the installation:

```
import darts
```

If no errors occur, we‘re ready to start using Darts!

## Loading and Visualizing Time Series Data

Darts comes with a few example datasets we can use, including:

- AirPassengersDataset: monthly totals of international airline passengers from 1949-1960
- MonthlyMilkDataset: pounds of milk produced per cow from 1962-1975

Let‘s load these and visualize them:

```
from darts.datasets import AirPassengersDataset, MonthlyMilkDataset

air_series = AirPassengersDataset().load()
milk_series = MonthlyMilkDataset().load()

air_series.plot(label="Air Passengers")
milk_series.plot(label="Milk Production")
plt.legend();
```

This plots the raw time series, showing the trend and any seasonality present. We can see the airline passenger data has an upward trend and yearly seasonal component, while the milk data has a slight downward trend.

Before modeling, it‘s often helpful to scale the data to a consistent range like [0,1] or with zero mean and unit variance. Darts provides a `Scaler` transformer for this:

```
from darts.dataprocessing.transformers import Scaler

scaler_air, scaler_milk = Scaler(), Scaler()

air_scaled = scaler_air.fit_transform(air_series)
milk_scaled = scaler_milk.fit_transform(milk_series)
```

We fit a separate scaler to each series to preserve their unique distributions. Visualizing the scaled series shows their magnitudes are now comparable.

## Training Time Series Models

With our data loaded and preprocessed, we‘re ready to start training models. Darts offers both classical time series models and newer deep learning architectures.

For this example, let‘s use one of the deep learning models – N-BEATS. N-BEATS is a deep neural architecture that has achieved state-of-the-art performance on many time series benchmarks. It works by fitting a set of basis functions to the input series and can capture complex patterns and relationships.

To train an N-BEATS model in Darts:

```
from darts.models import NBEATSModel

model = NBEATSModel(
    input_chunk_length=24,
    output_chunk_length=12,
    n_epochs=100,
    random_state=42
)
```

Here we specify the model will take in 24 time steps (e.g. 2 years of monthly data) as input and predict the next 12 time steps (1 year). We train it for 100 epochs total.

The real power of Darts is we can use this same N-BEATS model for both our univariate air passengers data and our multivariate milk production data:

```
model.fit([air_scaled, milk_scaled], verbose=True)
```

Behind the scenes, Darts builds a unified N-BEATS architecture that learns across all our series and leverages common signal to make more accurate forecasts. Training logs will print as the model fits, showing the loss decreasing on each series.

## Evaluating Model Performance

Once our model has finished training, we can evaluate how well it performs on held-out test data. A standard metric for assessing forecast accuracy is Mean Absolute Percentage Error (MAPE). Darts provides functions to easily compute this and other metrics:

```
from darts.metrics import mape

air_preds = model.predict(n=36, series=air_scaled)
milk_preds = model.predict(n=36, series=milk_scaled)

mape_air = mape(air_scaled, air_preds)
mape_milk = mape(milk_scaled, milk_preds)

print(f"Air Passengers MAPE: {mape_air:.2f}%")
print(f"Milk Production MAPE: {mape_milk:.2f}%")
```

Here we produce 36 step ahead forecasts from the end of the training series and compare them to the actual values. MAPE scores around 10% or lower are generally considered very good for time series models.

We can also visualize the forecasts against the ground truth:

```
air_scaled.plot(label="Actual")
air_preds.plot(label="Forecast")
plt.legend();

milk_scaled.plot(label="Actual")
milk_preds.plot(label="Forecast")
plt.legend();
```

Plotting the predictions in this way gives a more intuitive sense of how well the model has fit the data and helps identify any regions where performance degrades.

## Next Steps and Future Outlook

We‘ve seen how Darts makes it straightforward to train state-of-the-art deep learning models for time series forecasting. However, we‘ve only scratched the surface of what‘s possible with this powerful library.

Some additional techniques to explore:

- Backtesting to simulate model performance on rolling windows of historical data
- Hyperparameter tuning to find optimal model settings
- Ensembling multiple model architectures to improve robustness
- Training on much larger datasets and productionizing models

The Darts team is actively developing the library and incorporating the latest time series research. Some exciting areas on the roadmap:

- New architectures like LSTM-MSNet and Temporal Fusion Transformers
- Improved probabilistic forecasting and uncertainty estimation
- Benchmarking tools to systematically compare model performance
- End-to-end time series pipelines for common use cases

Time series forecasting is a rapidly evolving field and Darts is well-positioned to help researchers and practitioners stay on the cutting edge. We can expect to see Darts become an increasingly popular and fully-featured tool for time series modeling and analysis.

## Conclusion

Time series forecasting is a challenging but high-impact task, powering applications like demand prediction, anomaly detection, and predictive maintenance. The Darts library marks a significant step forward in making powerful time series models more accessible and easier to use.

In this post, we walked through the key steps of loading data, preprocessing, training models, and evaluating performance with Darts. The built-in datasets, transformers, and models make it simple to get started, while the unified interface enables training on multiple related series.

Whether you‘re a data scientist building demand forecasting models, a researcher prototyping new architectures, or a developer shipping a predictive application, Darts can help you be more effective. Give it a try and see what insights you uncover from your time series data!

---

Source: [Time Series Forecasting Made Easy with Darts in Python](https://33rdsquare.com/time-series-forecasting-made-easy-using-darts/)
