用Python進行時間序列分解和預測

什么是時間序列?
如何在Python中繪制時間序列數(shù)據(jù)?
時間序列的要素是什么?
如何分解時間序列?
經(jīng)典分解法
如何獲得季節(jié)性調(diào)整值?
STL分解法
時間序列預測的基本方法:
Python中的簡單移動平均(SMA)
為什么使用簡單移動平均?
Python中的加權移動平均(WMA)
Python中的指數(shù)移動平均(EMA)
什么是時間序列?
如何在PYTHON中繪制時間序列數(shù)據(jù)?
#Reading?Time?Series?DataAirpassenger = pd.read_csv("AirPassengers.csv")Airpassenger.head(3)
Airpassenger = Airpassenger.set_index('date')pyplot.rcParams["figure.figsize"] = (12,6)Airpassenger.plot()pyplot.show()

航空旅客人數(shù)
from datetime import datetime# Airpassenger["date"] = Airpassenger["date"].apply(lambda x: datetime.strptime(x, "%d-%m-%Y"))Airpassenger["year"] = Airpassenger["date"].apply(lambda x: x.year)Airpassenger["qtr"] = Airpassenger["date"].apply(lambda x: x.quarter)Airpassenger["yearQtr"]=Airpassenger['year'].astype(str)+'_'+Airpassenger['qtr'].astype(str)airPassengerByQtr=Airpassenger[["passengerCount", "yearQtr"]].groupby(["yearQtr"]).sum()
pyplot.rcParams["figure.figsize"] = (14,6)pyplot.plot(airPassengerByQtr)pyplot.xticks(airPassengerByQtr.index, rotation='vertical')

時間序列的要素是什么?
如何分解時間序列?
時間序列不必具有所有要素。
弄清該時間序列是可加的還是可乘的。
經(jīng)典分解法
該方法起源于1920年,是諸多方法的鼻祖。經(jīng)典分解法有兩種形式:加法和乘法。Python中的statsmodels庫中的函數(shù)season_decompose()提供了經(jīng)典分解法的實現(xiàn)。在經(jīng)典分解法中,需要你指出時間序列是可加的還是可乘的。你可以在此處(https://otexts.com/fpp2/classical-decomposition.html)了解有關加法和乘法分解的更多信息。
import numpy as npfrom pandas import read_csvimport matplotlib.pyplot as pltfrom statsmodels.tsa.seasonal import seasonal_decomposefrom pylab import rcParamselecequip = read_csv(r"C:/Users/datas/python/data/elecequip.csv")result = seasonal_decompose(np.array(elecequip), model='multiplicative', freq=4)rcParams['figure.figsize'] = 10, 5result.plot()pyplot.figure(figsize=(40,10))pyplot.show()

如何獲得季節(jié)性調(diào)整值?
該技術對異常值不可靠。
它傾向于使時間序列數(shù)據(jù)中的突然上升和下降過度平滑。
假設季節(jié)性因素每年只重復一次。
對于前幾次和最后幾次觀察,該方法都不會產(chǎn)生趨勢周期估計。
STL分解法
趨勢周期平滑度
季節(jié)性變化率
可以控制對用戶異常值或異常值的魯棒性。這樣你就可以控制離群值對季節(jié)性和趨勢性的影響。
Import?pandas?as?pdImport?seaborn?as?snsImport?matplotlib.pyplot?as?pltFrom statsmodels.tsa.seasonal import STLelecequip?=read_csv(r"C:/Users/datas/python/data/elecequip.csv")stl?=?STL(elecequip,?period=12,?robust=True)res_robust?=?stl.fit()fig = res_robust.plot()

時間序列預測的基本方法
PYTHON中的簡單移動平均(SMA)
為什么使用簡單移動平均?
Import pandas as pdfrom matplotlib import pyplotelecequip = pd.read_csv(r"C:/Users/datas/python/data/elecequip.csv")# Taking moving average of last 6 obsrolling = elecequip.rolling(window=6)rolling_mean = rolling.mean()# plot the two seriespyplot.plot(elecequip)pyplot.plot(rolling_mean, color='red')pyplot.show()

elecequip["x"].rolling(window=3,?center=True).mean()PYTHON中的加權移動平均(WMA)
import?randomrand?=?[random.randint(1,?i)?for?i?in?range(100,110)]data?=?{}data["Sales"] = randdf?=?pd.DataFrame(data)weights = np.array([0.5, 0.25, 0.10])sum_weights?=?np.sum(weights)df['WMA']=(df['Sales'].rolling(window=3,?center=True).apply(lambda x: np.sum(weights*x)/sum_weights, raw=False))print(df['WMA'])
PYTHON中的指數(shù)移動平均(EMA)
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom statsmodels.tsa.api import ExponentialSmoothingEMA_fit = ExponentialSmoothing(elecequip, seasonal_periods=12, trend='add', seasonal='add').fit(use_boxcox=True)fcast3 = EMA_fit.forecast(12)ax = elecequip.plot(figsize=(10,6), marker='o', color='black', title="Forecasts from Exponential Smoothing" )ax.set_ylabel("Electrical Equipment")ax.set_xlabel("Index")# For plotting fitted values#?EMA_fit.fittedvalues.plot(ax=ax,?style='--',?color='red')EMA_fit.forecast(12).rename('EMS?Forecast').plot(ax=ax,?style='--',?marker='o',?color='blue',?legend=True)
1 2 3 4 | import numpy as np import pandas as pd import matplotlib.pyplot as plt from statsmodels.tsa.api import SimpleExpSmoothing, Holt |
?
什么是時間序列數(shù)據(jù)?
如何可視化和更深入地識別數(shù)據(jù)模式(如果有)?
介紹了可加性和可乘性時間序列模型。
研究了Python中分解時間序列的不同方法。
最后,我們學習了如何在Python中運行一些非常基本的方法,例如移動平均(MA),加權移動平均(WMA),指數(shù)平滑模型(ESM)及其變體,例如SESM和Hotl。
原文標題:
TIME SERIES FORECAST AND DECOMPOSITION – 101 GUIDE PYTHON
原文鏈接:
https://datasciencebeginners.com/2020/11/25/time-series-forecast-and-decomposition-101-guide-python/
譯者簡介
王闖(Chuck),臺灣清華大學資訊工程碩士。曾任奧浦諾管理咨詢公司數(shù)據(jù)分析主管,現(xiàn)任尼爾森市場研究公司數(shù)據(jù)科學經(jīng)理。

