# Pythonで時系列を簡単に

---
[](https://badge.fury.io/py/darts)
[](https://anaconda.org/conda-forge/u8darts-all)

[](https://hub.docker.com/r/unit8/darts)


[](https://pepy.tech/project/darts)
[](https://pepy.tech/project/u8darts)
[](https://codecov.io/gh/unit8co/darts)
[](https://github.com/psf/black) [](https://gitter.im/u8darts/darts?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
**Darts** は、時系列に対するユーザーフレンドリーな予測と異常検知のための Python ライブラリです。ARIMA のような古典的なものから深層ニューラルネットワークまで、さまざまなモデルを含んでいます。予測モデルはすべて、scikit-learn と同様に `fit()` と `predict()` 関数を使って同じ方法で使用できます。
このライブラリは、モデルのバックテスト、複数モデルの予測の組み合わせ、外部データの考慮も簡単にします。
Darts は単変量および多変量の時系列とモデルの両方をサポートしています。
ML ベースのモデルは、複数の時系列を含む潜在的に大規模なデータセットでトレーニングでき、一部のモデルは確率的予測を豊富にサポートしています。
Darts はまた、広範な異常検知機能も提供しています。
たとえば、PyOD モデルを時系列に適用して異常スコアを取得したり、Darts の予測モデルやフィルタリングモデルをラップして本格的な異常検知モデルを得ることは簡単です。
## ドキュメント
* [クイックスタート](https://unit8co.github.io/darts/quickstart/00-quickstart.html)
* [ユーザーガイド](https://unit8co.github.io/darts/userguide.html)
* [API リファレンス](https://unit8co.github.io/darts/generated_api/darts.html)
* [例](https://unit8co.github.io/darts/examples.html)
### 高レベルな紹介
* [入門ブログ記事](https://medium.com/unit8-machine-learning-publication/darts-time-series-made-easy-in-python-5ac2947a8878)
* [紹介動画(25分)](https://youtu.be/g6OXDnXEtFA)
### 特定のトピックに関する記事
* [複数の時系列でモデルをトレーニングする](https://medium.com/unit8-machine-learning-publication/training-forecasting-models-on-multiple-time-series-with-darts-dc4be70b1844)
* [過去と未来の共変量を使用する](https://medium.com/unit8-machine-learning-publication/time-series-forecasting-using-past-and-future-external-data-with-darts-1f0539585993)
* [時間畳み込みネットワークと予測](https://medium.com/unit8-machine-learning-publication/temporal-convolutional-networks-and-forecasting-5ce1b6e97ce4)
* [確率的予測](https://medium.com/unit8-machine-learning-publication/probabilistic-forecasting-in-darts-e88fbe83344e)
* [時系列予測のための転移学習](https://medium.com/unit8-machine-learning-publication/transfer-learning-for-time-series-forecasting-87f39e375278)
* [階層的予測の調整](https://medium.com/unit8-machine-learning-publication/hierarchical-forecast-reconciliation-with-darts-8b4b058bb543)
## クイックインストール
まず、お気に入りのツール([conda](https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html "conda-env")、[venv](https://docs.python.org/3/library/venv.html)、[virtualenv](https://virtualenv.pypa.io/en/latest/) を [virtualenvwrapper](https://virtualenvwrapper.readthedocs.io/en/latest/) ありまたはなしで)を使って、Python 3.11+ のクリーンな Python 環境をプロジェクト用にセットアップすることをお勧めします。
環境がセットアップされたら、pip を使って darts をインストールできます:
pip install darts
詳細については、[インストール手順](https://github.com/unit8co/darts/blob/master/INSTALL.md)を参照してください。
## 使用例
### 予測
Pandas DataFrame から `TimeSeries` オブジェクトを作成し、訓練用と検証用の系列に分割します:
```python
import pandas as pd
from darts import TimeSeries
# Read a pandas DataFrame
df = pd.read_csv("AirPassengers.csv", delimiter=",")
# Create a TimeSeries, specifying the time and value columns
series = TimeSeries.from_dataframe(df, "Month", "#Passengers")
# Set aside the last 36 months as a validation series
train, val = series[:-36], series[-36:]
```
指数平滑モデルを適合させ、検証系列の期間にわたって(確率的な)予測を行います:
```python
from darts.models import ExponentialSmoothing
model = ExponentialSmoothing()
model.fit(train)
prediction = model.predict(len(val), num_samples=1000)
```
中央値、5パーセンタイル、95パーセンタイルをプロットします:
```python
import matplotlib.pyplot as plt
series.plot()
prediction.plot(label="forecast", low_quantile=0.05, high_quantile=0.95)
plt.legend()
```
<div style="text-align:center;">
<img src="https://raw.githubusercontent.com/unit8co/darts/master/static/images/example.png" alt="darts forecast example" />
</div>
### 異常検知
多変量系列を読み込み、トリミングし、2つのコンポーネントを保持して、訓練セットと検証セットに分割します:
```python
from darts.datasets import ETTh2Dataset
series = ETTh2Dataset().load()[:10000][["MUFL", "LULL"]]
train, val = series.split_before(0.6)
```
k-means 異常スコアラーを構築し、訓練セットで学習させ、
検証セットで使用して異常スコアを取得します:
```python
from darts.ad import KMeansScorer
scorer = KMeansScorer(k=2, window=5)
scorer.fit(train)
anom_score = scorer.score(val)
```
バイナリ異常検出器を構築し、trainスコアで学習させ、
その後validationスコアに対して使用してバイナリ異常分類を取得します:
```python
from darts.ad import QuantileDetector
detector = QuantileDetector(high_quantile=0.99)
detector.fit(scorer.score(train))
binary_anom = detector.detect(anom_score)
```
プロット(一部の系列をシフトおよびスケーリングして、すべてが同じ図に表示されるようにする):
```python
import matplotlib.pyplot as plt
series.plot()
(anom_score / 2. - 100).plot(label="computed anomaly score", c="orangered", lw=3)
(binary_anom * 45 - 150).plot(label="detected binary anomaly", lw=4)
```
<div style="text-align:center;">
<img src="https://raw.githubusercontent.com/unit8co/darts/master/static/images/example_ad.png" alt="darts anomaly detection example" />
</div>
## 特徴
* **予測モデル:** 回帰タスクおよび分類タスク向けの予測モデルを多数収録。統計モデル(
ARIMA など)から深層学習モデル(N-BEATS など)まで対応。以下に示す[予測モデル](#forecasting-models)を参照。
* **異常検知** `darts.ad` モジュールには、異常スコアラー、
検出器、アグリゲーターが揃っており、これらを組み合わせて時系列の異常を検知できます。
Darts の予測モデルやフィルタリングモデルをラップして、予測値と実測値を比較する
本格的な異常検知モデルを簡単に構築できます。
`PyODScorer` を使えば、PyOD の検出器を時系列に適用するのも容易です。
* **多変量サポート:** `TimeSeries` は多変量、つまり単一のスカラー値ではなく
複数の時間変化する次元/列を持つことができます。多くのモデルが多変量系列を入力として受け取り、出力できます。
* **複数系列の学習(グローバルモデル):** すべての機械学習ベースのモデル(すべてのニューラルネットワークを含む)は、
複数の(多変量の場合もある)系列で学習することをサポートしています。大規模なデータセットにもスケールできます。
* **確率的サポート:** `TimeSeries` オブジェクトは(オプションで)確率的な
時系列を表現できます。これは例えば信頼区間を得るために使用でき、多くのモデルがさまざまな
確率的予測(パラメトリック分布や分位点の推定など)をサポートしています。
一部の異常検知スコアラーも、これらの予測分布を活用できます。
* **Conformal Prediction サポート:** 当社の conformal prediction モデルは、
任意の事前学習済みグローバル予測モデルに対して、キャリブレーションされた分位点区間を伴う確率的予測を生成できます。
* **過去および未来の共変量サポート:** Darts の多くのモデルは、予測を生成するための入力として、
過去に観測された共変量および/または未来に既知の共変量(外部データ)の時系列をサポートしています。
* **静的共変量サポート:** 時間依存データに加えて、`TimeSeries` は各次元の
静的データも保持でき、一部のモデルでこれを活用できます。
* **階層的整合:** Darts は整合(reconciliation)を行うためのトランスフォーマーを提供しています。
これにより、基盤となる階層を尊重する形で予測を合計できるようにできます。
* **回帰モデル:** 対象系列と共変量のラグ値の関数として予測を得るために、
scikit-learn 互換の任意のモデルをプラグインできます。
* **サンプル重み付き学習:** すべてのグローバルモデルはサンプル重み付きでの学習をサポートしています。
各観測値、予測タイムステップ、対象列に適用できます。
* **予測開始のシフト:** すべてのグローバルモデルは、シフトされた出力ウィンドウでの学習と予測をサポートしています。
これは例えば Day-Ahead Market の予測や、共変量(または対象系列)が
遅延して報告される場合に有用です。
* **説明可能性:** Darts は SHAP 値を用いて一部の予測モデルを*説明*する機能を持っています。
* **データ処理:** 時系列データに対する一般的な変換(スケーリング、欠損値の補完、差分、boxcox など)を
簡単に適用(および元に戻す)するためのツール。
* **メトリクス:** 時系列の適合度を評価するための多様なメトリクス。
R2 スコアから Mean Absolute Scaled Error まで。
* **バックテスト:** 移動時間ウィンドウを用いて過去の予測をシミュレートするためのユーティリティ。
* **PyTorch Lightning サポート:** すべての深層学習モデルは PyTorch Lightning を用いて実装されており、
カスタムコールバック、GPU/TPU トレーニング、カスタムトレーナーなどをサポートしています。
* **MLflow 統合:** Darts 予測モデルの実験の自動トラッキング、比較、永続化のための MLflow との統合。
例については [MLflow クイックスタートノートブック](https://unit8co.github.io/darts/examples/29-MLflow-examples.html)を参照。
* **フィルタリングモデル:** Darts は `KalmanFilter`、`GaussianProcessFilter`、
`MovingAverageFilter` の 3 つのフィルタリングモデルを提供しており、時系列をフィルタリングでき、
場合によっては基盤となる状態/値の確率的推論を得ることもできます。
* **データセット** `darts.datasets` サブモジュールには、迅速かつ再現可能な実験のための
人気のある時系列データセットがいくつか含まれています。
* **複数バックエンドとの互換性:** `TimeSeries` オブジェクトは pandas、polars、numpy、pyarrow、xarray など
さまざまなバックエンドから作成し、エクスポートできます。これにより、異なるデータ処理ライブラリとのシームレスな統合が可能になります。
## 予測モデル
以下に、現在 Darts に実装されている予測モデルの内訳を示します。当社のスイートには回帰モデルと分類モデルの両方が含まれ、それぞれが特定の予測タスクに合わせて調整されています。予測能力を高めるために、新しいモデルと機能を継続的に追加していくことをお約束します。
**回帰モデル:** 当社の回帰モデルは連続的な数値を予測するように設計されており、時系列データにおける将来の傾向やパターンを予測するのに理想的です。これらのモデルを活用して、過去のデータに基づく潜在的な将来の結果についての洞察を得てください。
| モデル | ソース | 対象系列のサポート:<br/><br/>単変量/<br/>多変量 | 共変量のサポート:<br/><br/>過去に観測/<br/>将来に既知/<br/>静的 | 確率的予測:<br/><br/>サンプリング済み/<br/>分布パラメータ | 複数系列でのトレーニングと予測 |
|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------|--------------------------------------------------------------------------|--------------------------------------------------------------------------|-------------------------------------------|
| **ベースラインモデル**<br/>([LocalForecastingModel](https://unit8co.github.io/darts/userguide/covariates.html#local-forecasting-models-lfms)) | | | | | |
| [NaiveMean](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.baselines.html#darts.models.forecasting.baselines.NaiveMean) | | ✅ ✅ | 🔴 🔴 🔴 | 🔴 🔴 | 🔴 |
| [NaiveSeasonal](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.baselines.html#darts.models.forecasting.baselines.NaiveSeasonal) | | ✅ ✅ | 🔴 🔴 🔴 | 🔴 🔴 | 🔴 |
| [NaiveDrift](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.baselines.html#darts.models.forecasting.baselines.NaiveDrift) | | ✅ ✅ | 🔴 🔴 🔴 | 🔴 🔴 | 🔴 |
| [NaiveMovingAverage](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.baselines.html#darts.models.forecasting.baselines.NaiveMovingAverage) | | ✅ ✅ | 🔴 🔴 🔴 | 🔴 🔴 | 🔴 |
| **統計 / クラシックモデル**<br/>([LocalForecastingModel](https://unit8co.github.io/darts/userguide/covariates.html#local-forecasting-models-lfms)) | | | | | |
| [ARIMA](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.arima.html#darts.models.forecasting.arima.ARIMA) | | ✅ 🔴 | 🔴 ✅ 🔴 | ✅ 🔴 | 🔴 |
| [VARIMA](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.varima.html#darts.models.forecasting.varima.VARIMA) | | 🔴 ✅ | 🔴 ✅ 🔴 | ✅ 🔴 | 🔴 |
| [ExponentialSmoothing](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.exponential_smoothing.html#darts.models.forecasting.exponential_smoothing.ExponentialSmoothing) | | ✅ 🔴 | 🔴 🔴 🔴 | ✅ 🔴 | 🔴 |
| [Theta](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.theta.html#darts.models.forecasting.theta.Theta) および [FourTheta](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.theta.html#darts.models.forecasting.theta.FourTheta) | [Theta paper](https://robjhyndman.com/papers/Theta.pdf) & [4 Theta source](https://github.com/Mcompetitions/M4-methods/blob/master/4Theta%20method.R) | ✅ 🔴 | 🔴 🔴 🔴 | 🔴 🔴 | 🔴 |
| [Prophet](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.prophet_model.html#darts.models.forecasting.prophet_model.Prophet) | [Prophet repo](https://github.com/facebook/prophet) | ✅ 🔴 | 🔴 ✅ 🔴 | ✅ 🔴 | 🔴 |
| [FFT](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.fft.html#darts.models.forecasting.fft.FFT) (高速フーリエ変換) | | ✅ 🔴 | 🔴 🔴 🔴 | 🔴 🔴 | 🔴 |
| [KalmanForecaster](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.kalman_forecaster.html#darts.models.forecasting.kalman_forecaster.KalmanForecaster) はシステム同定にカルマンフィルタと N4SID を使用 | [N4SID paper](https://people.duke.edu/~hpgavin/SystemID/References/VanOverschee-Automatica-1994.pdf) | ✅ ✅ | 🔴 ✅ 🔴 | ✅ 🔴 | 🔴 |
| [TBATS](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.sf_tbats.html#darts.models.forecasting.sf_tbats.TBATS) | [TBATS paper](https://robjhyndman.com/papers/ComplexSeasonality.pdf) | ✅ 🔴 | 🔴 ✅ 🔴 | ✅ ✅ | 🔴 |
| [Croston](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.sf_croston.html#darts.models.forecasting.sf_croston.Croston) メソッド | | ✅ 🔴 | 🔴 ✅ 🔴 | ✅ ✅ | 🔴 |
| [StatsForecastModel](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.sf_model.html#darts.models.forecasting.sf_model.StatsForecastModel): 任意の [StatsForecast](https://nixtlaverse.nixtla.io/statsforecast/index.html#models) モデルのラッパー | [Nixtla's statsforecast](https://github.com/Nixtla/statsforecast) | ✅ 🔴 | 🔴 ✅ 🔴 | ✅ ✅ | 🔴 |
| [AutoARIMA](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.sf_auto_arima.html#darts.models.forecasting.sf_auto_arima.AutoARIMA) | [Nixtla's statsforecast](https://github.com/Nixtla/statsforecast) | ✅ 🔴 | 🔴 ✅ 🔴 | ✅ ✅ | 🔴 |
| [AutoETS](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.sf_auto_ets.html#darts.models.forecasting.sf_auto_ets.AutoETS) | [Nixtla's statsforecast](https://github.com/Nixtla/statsforecast) | ✅ 🔴 | 🔴 ✅ 🔴 | ✅ ✅ | 🔴 |
| [AutoCES](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.sf_auto_ces.html#darts.models.forecasting.sf_auto_ces.AutoCES) | [Nixtla's statsforecast](https://github.com/Nixtla/statsforecast) | ✅ 🔴 | 🔴 ✅ 🔴 | ✅ ✅ | 🔴 |
| [AutoMFLES](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.sf_auto_mfles.html#darts.models.forecasting.sf_auto_mfles.AutoMFLES) | [Nixtla's statsforecast](https://github.com/Nixtla/statsforecast) | ✅ 🔴 | 🔴 ✅ 🔴 | ✅ ✅ | 🔴 |
| [AutoTBATS](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.sf_auto_tbats.html#darts.models.forecasting.sf_auto_tbats.AutoTBATS) | [Nixtla's statsforecast](https://github.com/Nixtla/statsforecast) | ✅ 🔴 | 🔴 ✅ 🔴 | ✅ ✅ | 🔴 |
---
[Read more](https://github.com/unit8co/darts)