用python作時間序列預測三:時間序列分解

在初始概念篇中,咱們簡單提到了時間序列由趨勢、週期性、季節性、偏差構成,本文將介紹如何將時間序列的這些成分分解出來。分解的使用場景有不少,好比當咱們須要計算該時間序列是否具備季節性,或者咱們要去除該時間序列的趨勢和季節性,讓時間序列變得平穩時都會用到時間序列分解。python

加法和乘法時間序列

時間序列的各個觀測值能夠是以上成分相加或相乘獲得:
Value = Trend + Seasonality + Error
Value = Trend * Seasonality * Errorgit

分解

下面的代碼展現瞭如何用python從時間序列中分解出相應的成分:github

from statsmodels.tsa.seasonal import seasonal_decompose
from dateutil.parser import parse

# Import Data
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/a10.csv', parse_dates=['date'], index_col='date')

# Multiplicative Decomposition 
result_mul = seasonal_decompose(df['value'], model='multiplicative', extrapolate_trend='freq')

# Additive Decomposition
result_add = seasonal_decompose(df['value'], model='additive', extrapolate_trend='freq')

# Plot
plt.rcParams.update({'figure.figsize': (10,10)})
result_mul.plot().suptitle('Multiplicative Decompose', fontsize=22)
result_add.plot().suptitle('Additive Decompose', fontsize=22)
plt.show()

# Extract the Components ----# Actual Values = Product of (Seasonal * Trend * Resid)
df_reconstructed = pd.concat([result_mul.seasonal, result_mul.trend, result_mul.resid, result_mul.observed], axis=1)
df_reconstructed.columns = ['seas', 'trend', 'resid', 'actual_values']
df_reconstructed.head()

對比上面的加法分解和乘法分解能夠看到,加法分解的殘差圖中有一些季節性成分沒有被分解出去,而乘法相對而言隨機多了(越隨機意味着留有的成分越少),因此對於當前時間序列來講,乘法分解更適合。code

小結

時間序列分解不只能夠讓咱們更清晰的瞭解序列的特性,有時候人們還會用分解出的殘差序列(偏差)代替原始序列來作預測,由於原始時間序列通常是非平穩序列,而這個殘差序列是平穩序列,有助於咱們作出更好的預測,固然預測後的序列還要加回或乘回趨勢成分和季節性成分,平穩序列的具體內容將在下一篇文章中介紹。blog

ok,本篇就這麼多內容啦~,感謝閱讀O(∩_∩)O。ip

相關文章
相關標籤/搜索