How to Harness the Power of Time Series Forecasting with Darts in Python

Nov 5, 2020 | Data Science

In the realm of data analysis and machine learning, time series forecasting is a vital skill. With Darts, a user-friendly Python library, you can effortlessly perform forecasting and anomaly detection on your time series data. This tutorial will guide you through the simple steps to get started with Darts, showcasing its capabilities and enabling you to make deep insights into your data.

Setting Up Your Environment

Before diving into the magic of Darts, let’s set up a clean Python environment. Here’s how:

  1. Choose your favorite environment manager: Conda, venv, or virtualenv.
  2. Once your environment is established, install Darts with:
    pip install darts

For detailed installation instructions, you may refer to the installation guide.

Forecasting with Darts

Now, let’s forecast some time series data! Imagine creating a well-prepared dish; you start with a recipe, gather ingredients, and follow steps to achieve a sumptuous meal. Similarly, here are the steps to forecast using Darts:

1. Create a Time Series Object

First, read your time series data into a Pandas DataFrame:

import pandas as pd
from darts import TimeSeries

df = pd.read_csv('AirPassengers.csv', delimiter=',')
series = TimeSeries.from_dataframe(df, 'Month', '#Passengers')

Next, split your data into training and validation sets:

train, val = series[:-36], series[-36:]

2. Fit a Model and Make Predictions

Just as a chef requires careful cooking to enhance flavors, you need a model to forecast the future values:

from darts.models import ExponentialSmoothing

model = ExponentialSmoothing()
model.fit(train)
prediction = model.predict(len(val), num_samples=1000)

3. Visualizing the Forecast

Presentation is key! Use Matplotlib to showcase your predictions:

import matplotlib.pyplot as plt

series.plot()
prediction.plot(label='forecast', low_quantile=0.05, high_quantile=0.95)
plt.legend()
plt.show()

Anomaly Detection

Darts isn’t just about forecasting; it excels in anomaly detection as well. Think of it as a vigilant guard watching your data for any unusual patterns. Let’s dive into how to implement it:

1. Load Your Multivariate Data

from darts.datasets import ETTh2Dataset

series = ETTh2Dataset().load()[:10000][['MUFL', 'LULL']]
train, val = series.split_before(0.6)

2. Train a K-Means Scorer

from darts.ad import KMeansScorer

scorer = KMeansScorer(k=2, window=5)
scorer.fit(train)
anom_score = scorer.score(val)

3. Detect Anomalies

from darts.ad import QuantileDetector

detector = QuantileDetector(high_quantile=0.99)
detector.fit(scorer.score(train))
binary_anom = detector.detect(anom_score)

4. Visualize Anomalies

Finally, plot your results to see how effectively your guard caught anomalies:

series.plot()
(anom_score - 2).plot(label='computed anomaly score', c='orangered', lw=3)
(binary_anom * 45 - 150).plot(label='detected binary anomaly', lw=4)
plt.show()

Troubleshooting Tips

If you encounter issues while using Darts, consider these troubleshooting ideas:

  • Ensure your data is in the correct format. Darts requires a time series format compatible with Pandas DataFrames.
  • Check for missing values in your dataset, as they may lead to unexpected behaviors.
  • Verify that you have the latest version of Python (3.8+) and Darts installed.
  • For model-specific errors, refer to the Darts User Guide.
  • For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.

Conclusion

With its diverse modeling techniques and robust functionality, Darts streamlines time series forecasting and anomaly detection for your projects. It empowers you to extract valuable insights effortlessly. At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.

Stay Informed with the Newest F(x) Insights and Blogs

Tech News and Blog Highlights, Straight to Your Inbox