LoginSignup
1
3

More than 5 years have passed since last update.

#[自分用メモ]Prophetの使い方

Last updated at Posted at 2019-04-01

Prophetの使い方

prophetをインストールする

!pip install fbprophet

インポート

import io
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
from fbprophet import Prophet

型を指定してCSV読み込み

df = pd.read_csv('Query.csv',dtype = {'ds':'object','y':'int'})

行削除

df.drop(index=[13,22])

デフォルトの使い方

予測モデルの作成

model = Prophet()
model.fit(df)

予測期間の指定

future_df = model.make_future_dataframe(periods = 365)

予測の作成

forecast_df = model.predict(future_df)

プロット

model.plot(forecast_df)

予測モデル

時系列 = トレンド + 周期性 + イベント

パラメータが直感的に理解できる

調整可能なパラメータ

①線形トレンド 'linear' or 非線形トレンド 'logistic'

ビジネスの時系列は基本的に非線形トレンド
成長上限が決まっている
成長初期段階では線形で近似できる

②変化点、変化点の数

③週周期と年周期

④イベント

非線形トレンドの指定

from fbprophet import Prophet

予測モデルの作成

model = Prophet(gwowth='logistic')

df['cap']に上限を指定

df['cap'] = 8.5

予測モデルの作成

model.fit(df)
future_df = model.mke_future_dataframe(365*5)
future_df['cap'] = 8.5
forecast_df = model.predict(future_df)

新製品発表などトレンド変化

model = Prophet(changepoints=['2013-01-31']
model.fit(df)

等間隔に変化点を置いて推定

n_changepoints=変化点の数

model = Prophet(n_changepoints=25)
model.fit(df)

週周期と年周期の指定

model = Prophet(weekly_seasonality=False,
yearly_seasonality=True)
model.fit(df)

不定期イベント

イベント日を列挙したデータフレームを用意する

horiday,ds,lower,upper
24時間テレビ,2015-08-22,0,1
クリスマス,2015-12-25,-1,0

イベント日のデータフレームを渡す

model = Prophet(holidays=event_dataframe)
model.fit(df)

評価指標

MAPE(平均絶対パーセント誤差) 実績から何%外れているか?

SHF

diagnosticsは日本語で診断

from fbprophet import diagnostics

精度検証をする。horizonに検証したい期間を入力する

cv = diagnostics.cross_validation(model, horizon='365 days')
cv.tail()

def cal_mape(df):
return((df['yhat'] - df['y']).div(df['y']).abs().sum()*(1/len(df)))

def all_metrics(df):
if 'yhat' not in df.columns:
raise ValueError(
'Please run Cross-Validation first before computing quality metrics.')

me = (df['yhat'] - df['y']).sum()/len(df['yhat'])
mse = (df['yhat'] - df['y']).pow(2).sum()/len(df)
rmse = np.sqrt((df['yhat'] - df['y']).pow(2).sum()/len(df))
mae = (df['yhat'] - df['y']).abs().sum()/len(df)
mpe = (df['yhat'] - df['y']).div(df['y']).sum()*(1/len(df))
mape = (df['yhat'] - df['y']).div(df['y']).abs().sum()*(1/len(df))

return {'ME':me, 'MSE':mse, 'RMSE': rmse, 'MAE': mae, 'MPE': mpe, 'MAPE': mape}

all_metrics(cv)

100日、150日、200日、250日のMAPEを算出する

def cal_some_mape(model):
some_mape = pd.DataFrame(columns=['horizon','mape'])
for i in range(100, 251, 50):
horizon = str(i) + ' days'
cv = diagnostics.cross_validation(model, horizon=horizon)
mape = cal_mape(cv)
series = pd.Series([i, mape], index=some_mape.columns)
some_mape = some_mape.append(series, ignore_index=True)
return some_mape

some_mape = cal_some_mape(model)

1
3
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
1
3