您只需幾行代碼即可創(chuàng)建和評(píng)估預(yù)測(cè)。
只要提供pandas的DataFrame,需要包含時(shí)間序列和需要預(yù)測(cè)的值。時(shí)間序列可以是任何pandas.to_datatime認(rèn)識(shí)的格式
在本例中,我們將會(huì)加載一個(gè)數(shù)據(jù)集,代表的是佩頓·曼寧維基百科頁(yè)面的訪問(wèn)量。
本數(shù)據(jù)集包含了從2007-12-10到2016-01-20期間的數(shù)據(jù)。
加載依賴
#將圖表嵌入到Notebook中
%matplotlib inline
# 忽略警告
import warnings
warnings.filterwarnings("ignore")
# 加載依賴
import pandas as pd
import plotly
from greykite.common.data_loader import DataLoader
from greykite.framework.templates.autogen.forecast_config import ForecastConfig
from greykite.framework.templates.autogen.forecast_config import MetadataParam
from greykite.framework.templates.forecaster import Forecaster
from greykite.framework.templates.model_templates import ModelTemplateEnum
from greykite.framework.utils.result_summary import summarize_grid_search_results
將數(shù)據(jù)集加載到pandas DataFrame中
dl = DataLoader()
df = dl.load_peyton_manning()
display(df.head(),df.tail())

這個(gè)df就是從2007-12-10到2016-01-20期間的數(shù)據(jù)。如果要用自己的數(shù)據(jù)集,可以pd.read_csv讀取自己的數(shù)據(jù)。只要是pandas.to_datatime能認(rèn)識(shí)的時(shí)間格式就可以(一般常見(jiàn)的格式都認(rèn)識(shí))。
指定數(shù)據(jù)集信息
metadata = MetadataParam(
time_col="ts", # time列的列名
value_col="y", # value列的列名
freq="D"
'''
"H" 代表小時(shí), "D" 是天, "W" 是星期, etc. `pandas.date_range`能接受的任何格式
'''
)
創(chuàng)建預(yù)測(cè)模型
你可以選擇PROPHET或者SILVERKITE預(yù)測(cè)模型模板。
在本例中,我們使用SILVERKITE作為預(yù)測(cè)模型。
首先創(chuàng)建Forecaster()對(duì)象,然后對(duì)該實(shí)例對(duì)象應(yīng)用run_forecast_config方法。
傳入兩個(gè)參數(shù),df 和 config。df就是前面創(chuàng)建的數(shù)據(jù)集,config需要用ForecastConfig()函數(shù)創(chuàng)建。
ForecastConfig()里面的參數(shù)包括:
- model_template:模型算法,這里選擇使用ModelTemplateEnum.SILVERKITE.name
- forecast_horizon:預(yù)測(cè)的步長(zhǎng),這里預(yù)測(cè)365步
- coverage:置信度,0.95是95%置信度在預(yù)測(cè)的范圍內(nèi)。
- metadata_param:這個(gè)就選上一步創(chuàng)建的那個(gè)數(shù)據(jù)集信息,時(shí)間列名、值列名、時(shí)間頻率
forecaster = Forecaster() # 創(chuàng)建forecaster對(duì)象,并且存儲(chǔ)預(yù)測(cè)結(jié)果
result = forecaster.run_forecast_config( # 結(jié)果也被存儲(chǔ)為`forecaster.forecast_result`
df=df,
config=ForecastConfig(
model_template=ModelTemplateEnum.SILVERKITE.name,
forecast_horizon=365, # 向前預(yù)測(cè)365步長(zhǎng)
coverage=0.95, # 95%預(yù)測(cè)置信度
metadata_param=metadata
)
)
檢查結(jié)果
run_forecast_config的輸出是一個(gè)字典,包含了未來(lái)的預(yù)測(cè),歷史擬合性能評(píng)估,以及原始的時(shí)間序列。
繪制歷史的時(shí)序數(shù)據(jù)
使用plotly畫(huà)出可交互的圖表
ts = result.timeseries
fig = ts.plot()
plotly.io.show(fig)

Cross-validation交叉驗(yàn)證:
默認(rèn)地,run_forecast_config提供了歷史數(shù)據(jù)的估計(jì),所以你可以看到這個(gè)模型對(duì)于歷史數(shù)據(jù)的“預(yù)測(cè)”效果。
這個(gè)被存儲(chǔ)在grid_search (交叉驗(yàn)證拆分)和backtest(holdout測(cè)試集)
讓我們看一下交叉驗(yàn)證的結(jié)果吧。
下面展示了MAPE(Mean Absolute Percentage Error)
grid_search = result.grid_search
cv_results = summarize_grid_search_results(
grid_search=grid_search,
decimals=2, # 小數(shù)位
# The below saves space in the printed output. Remove to show all available metrics and columns.
cv_report_metrics=None,
column_order=["rank", "mean_test", "split_test", "mean_train", "split_train", "mean_fit_time", "mean_score_time", "params"])
# Transposes to save space in the printed output
# 轉(zhuǎn)置,節(jié)省打印輸出的空間
cv_results["params"] = cv_results["params"].astype(str)
cv_results.set_index("params", drop=True, inplace=True)
cv_results.transpose()

這些參數(shù)具體代表的含義,我尚不能解釋清楚。埋坑,待以后用到的時(shí)候再研究吧。如果讀者您知道,請(qǐng)不吝賜教。
使用Backtest ,畫(huà)出歷史數(shù)據(jù)的擬合效果吧。
backtest = result.backtest
fig = backtest.plot()
plotly.io.show(fig)

使用前一部分的歷史數(shù)據(jù)歷史數(shù)據(jù)作為訓(xùn)練集,來(lái)預(yù)測(cè)后一部分的歷史數(shù)據(jù)??纯锤鷮?shí)際的數(shù)據(jù)差別。
這個(gè)預(yù)測(cè)的時(shí)間周期,是跟上面模型創(chuàng)建時(shí)定義的forecast_horizon=365一樣。要往后預(yù)測(cè)365天,默認(rèn)做模型檢驗(yàn)的時(shí)候,backtest也時(shí)拿最后的365天做校驗(yàn)。
你也可以查看歷史數(shù)據(jù)評(píng)估矩陣(基于歷史的訓(xùn)練和測(cè)試集)
dict_train = {}
for i,j in backtest.train_evaluation.items():
dict_train[i] = j
df_train = pd.DataFrame(dict_train,index=["train"])
dict_test = {}
for i,j in backtest.test_evaluation.items():
dict_test[i] = j
df_test = pd.DataFrame(dict_train,index=["test"])
metrics = pd.concat([df_train,df_test],axis=0).T
metrics

Forecast預(yù)測(cè)
結(jié)果的forecast屬性包含了預(yù)測(cè)的結(jié)果,就跟backtest類似,你可以畫(huà)出結(jié)果,或者看到評(píng)估矩陣。
讓我們畫(huà)出預(yù)測(cè)結(jié)果吧(使用所有的數(shù)據(jù)進(jìn)行訓(xùn)練):
forecast = result.forecast
fig = forecast.plot()
plotly.io.show(fig)

這個(gè)預(yù)測(cè)結(jié)果的數(shù)值可以在df里面拿到。
forecast.df.tail().round(2)

Model Diagnostics模型診斷:
各個(gè)組件圖展示了展示了你的數(shù)據(jù)集的整體趨勢(shì)、季節(jié)性影響、以及事件、節(jié)假日模式。
fig = forecast.plot_components()
plotly.io.show(fig) # 如果使用PROPHET算法模板,就用 fig.show()






模型總結(jié),可以了解模型如何工作以及可以進(jìn)一步改進(jìn)的內(nèi)容。但是看不懂,先寫(xiě)在這下面。
summary = result.model[-1].summary() # -1 retrieves the estimator from the pipeline
print(summary)
應(yīng)用模型
這個(gè)訓(xùn)練的模型可以在sklearn.pipeline.Pipeline中被使用
model = result.model
model
你可以拿這個(gè)模型來(lái)預(yù)測(cè)任意時(shí)間范圍,make_future_dataframe這個(gè)函數(shù)可以幫你方便地創(chuàng)建未來(lái)日期的dataframe。
注意傳給predict函數(shù)的dataframe需要跟前面?zhèn)鹘orun_forecast_config 的df具有相同的列。包括數(shù)值列,要用np.nan來(lái)填充。
future_df = result.timeseries.make_future_dataframe(
periods=4,
include_history=False)
future_df

調(diào)用.predict()函數(shù)來(lái)計(jì)算預(yù)測(cè)值。
model.predict(future_df)
