今回の課題
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()
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")
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()
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()
以上です。