![](/img/trans.png)
[英]R forecast.holt vs Python statsmodels.tsa.holtwinters
[英]How to take confidence interval of statsmodels.tsa.holtwinters-ExponentialSmoothing Models in python?
我在python用ExponentialSmoothing做了時間序列預測分析。我用的是statsmodels.tsa.holtwinters。
model = ExponentialSmoothing(df, seasonal='mul', seasonal_periods=12).fit()
pred = model.predict(start=df.index[0], end=122)
plt.plot(df_fc.index, df_fc, label='Train')
plt.plot(pred.index, pred, label='Holt-Winters')
plt.legend(loc='best')
我想采用 model 結果的置信區間。 但是我在“statsmodels.tsa.holtwinters - ExponentialSmoothing”中找不到任何關於此的 function。 我該怎么做?
從 GitHub 問題的這個答案中,很明顯您應該使用新的ETSModel
class,而不是舊的(但仍然存在兼容性) ExponentialSmoothing
。 ETSModel
比ExponentialSmoothing
包含更多參數和更多功能。
要計算置信區間,我建議您使用ETSResults
的simulate
方法:
from statsmodels.tsa.exponential_smoothing.ets import ETSModel
import pandas as pd
# Build model.
ets_model = ETSModel(
endog=y, # y should be a pd.Series
seasonal='mul',
seasonal_periods=12,
)
ets_result = ets_model.fit()
# Simulate predictions.
n_steps_prediction = y.shape[0]
n_repetitions = 500
df_simul = ets_result.simulate(
nsimulations=n_steps_prediction,
repetitions=n_repetitions,
anchor='start',
)
# Calculate confidence intervals.
upper_ci = df_simul.quantile(q=0.9, axis='columns')
lower_ci = df_simul.quantile(q=0.1, axis='columns')
基本上,調用simulate
方法,您會得到一個 DataFrame ,其中包含n_repetitions
列和n_steps_prediction
步驟(在這種情況下,訓練數據集y
中的項目數量相同)。 然后,您使用 DataFrame quantile
方法計算置信區間(請記住axis='columns'
選項)。 您還可以從df_simul
計算其他統計數據。
我還檢查了源代碼: simulate
在內部被forecast
方法調用以預測未來的步驟。 因此,您還可以使用相同的方法預測未來的步驟及其置信區間:只需使用anchor='end'
,這樣模擬將從y
的最后一步開始。
公平地說,還有一種更直接的方法來計算置信區間: get_prediction
方法(內部使用simulate
)。 但我不太喜歡它的界面,它對我來說不夠靈活,我沒有找到指定所需置信區間的方法。 在我看來,使用simulate
方法的方法很容易理解,而且非常靈活。
如果您想了解有關如何執行此類模擬的更多詳細信息,請閱讀優秀的《預測:原理與實踐》在線書籍中的這一章。
補充@Enrico的答案,我們可以通過以下方式使用get_prediction
:
ci = model.get_prediction(start = forecast_data.index[0], end = forecast_data.index[-1])
preds = ci.pred_int(alpha = .05) #confidence interval
limits = ci.predicted_mean
preds = pd.concat([limits, preds], axis = 1)
preds.columns = ['yhat', 'yhat_lower', 'yhat_upper']
preds
實施答案(由我自己).... @Enrico,我們可以通過以下方式使用get_prediction :
from statsmodels.tsa.exponential_smoothing.ets import ETSModel
#---sales:pd.series, time series data(index should be timedate format)
#---new advanced holt's winter ts model implementation
HWTES_Model = ETSModel(endog=sales, trend= 'mul', seasonal='mul', seasonal_periods=4).fit()
point_forecast = HWTES_Model.forecast(16)
#-------Confidence Interval forecast calculation start------------------
ci = HWTES_Model.get_prediction(start = point_forecast.index[0],
end = point_forecast.index[-1])
lower_conf_forecast = ci.pred_int(alpha=alpha_1).iloc[:,0]
upper_conf_forecast = ci.pred_int(alpha=alpha_1).iloc[:,1]
#-------Confidence Interval forecast calculation end-----------------
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.