2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【時系列分析/Python】statsmodelsライブラリのDeterministicProcess関数を使用して、売上予測をする。

Last updated at Posted at 2023-01-07

今回の課題

KaggleのTrendというチュートリアルでstatsmodelsライブラリを使用して、
未来の数値の予測が行われていた。

そのチュートリアルを参考に、
前回投稿した下記の記事の、未来の売上予測を行いたかった。
https://qiita.com/Ayumu-y/items/a2f3f716706a6f34028b

statsmodelsライブラリとは

統計モデルを用いて推定や検定、探索ができるPythonライブラリ。
statsmodelsライブラリの中にDeterministicProcess関数があり、
この関数を使用することで未来の数値の予測ができる。

※公式ドキュメントはこちら

使用したコードの解説

作成したコードが下記の通り。

1)ライブラリのインポート

from statsmodels.tsa.deterministic import DeterministicProcess

2)DeterministicProcess関数をインスタンス化

※公式ドキュメントに説明が書いているが、
 理解が難しいため試行錯誤しながら学ぶ必要がありそうだと感じた。

dp = DeterministicProcess(
    index=trend_df.index # インデックスを指定。ここではDatetimeIndexとなっている。
    , constant=True      # 定数を含めるかどうか
    , order=1            # 含めるタイミングトレンドの順序。
    , drop=True          # 完全な共線性をチェックし、線形従属項を削除することを示すフラグ。
)

# `in_sample`は`index`引数で指定された日付に対応する特徴量を作成する。
X = dp.in_sample()
X.tail()

出力結果
image.png

3)LinearRegressionモデルに目的変数と説明変数を学習させ目的変数を予測する

from sklearn.linear_model import LinearRegression

y = trend_df["sales"]

# DeterministicProcess.LinearRegressionは重複する特徴量に対して悪い振る舞いをする。
# 重複する訴訟に対して線形回帰は悪い振る舞いをするので、ここでは確実に除外する必要がある。
# fit_intercept=Falseとすると、切片0モデルになる。
model = LinearRegression(fit_intercept=False)
model.fit(X, y)

y_pred = pd.Series(model.predict(X), index=X.index)

4)Daily Salesを可視化する

ax = trend_df.plot(style=".", color="0.5", title="Daily Sales - Linear Trend")
_ = y_pred.plot(ax=ax, linewidth=3, label="Trend")

image.png

5)out_of_sampleで、引数のstepの数分の未来の数値を予測する

※注意点
X = dp.out_of_sampleだけでは、データフレームXのインデックスがただの数字になってしまうので、
DatetimeIndexに変換するためのコードも入れる必要があった。

X = dp.out_of_sample(steps=365)

# indexが数値になってしまうので、下記の2行のコードでDatetimeIndexに変更しておく。
X["date"] = pd.date_range(start="2017-08-16", end="2018-08-15", freq="D")
X = X.set_index("date")

y_fore = pd.Series(model.predict(X), index=X.index)
y_fore.head()

image.png

6)未来の売上を予測して可視化する

ax = trend_df["2013-01-01":].plot(title="Tunnel Traffic - Linear Trend Forecast", **plot_params)
ax = y_pred["2013-01-01":].plot(ax=ax, linewidth=3, label="Trend")
ax = y_fore.plot(ax=ax, linewidth=3, label="Trend Forecast", color="C3")
_ = ax.legend()

image.png

以上です。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?