メインコンテンツへスキップ
見出し画像

書記が数学やるだけ#634 時系列データの構成

    時系列データの大まかな構成について見ていく。


    問題


    画像


    説明

    大まかに「時系列データ=短期自己相関+周期的変動+トレンド+外因性+ホワイトノイズ」と分解できる。

    画像


    コレログラムは,自己相関係数とラグの関係を示したグラフである。

    画像


    解答

    時系列データをトレンド,季節性,それ以外(残差)で分けたグラフを示す。

    画像


    ここまでのデータのコードを以下に示す。

    参考:


    import numpy as np
    import pandas as pd
    from scipy import stats
    
    from matplotlib import pylab as plt
    import seaborn as sns
    %matplotlib inline
    sns.set()
    
    import statsmodels.api as sm


    データはあらかじめ「AirPassengers.csv」と用意しているものとする。

    data = pd.read_csv('AirPassengers.csv',
    index_col='ds',
    parse_dates=True,
    dtype='float')
    data.head()


    画像


    実際にプロットしてみる。

    ts = data['y']
    ts.plot()


    画像


    以降の計算ではstatsmodelsを用いる。

    res = sm.tsa.seasonal_decompose(ts)
    
    original = ts # オリジナルデータ
    trend = res.trend # トレンドデータ
    seasonal = res.seasonal # 季節性データ
    residual = res.resid # 残差データ
    
    plt.figure(figsize=(8, 8))
    
    #オリジナルデータのプロット
    plt.subplot(411)
    plt.plot(original)
    plt.ylabel('Original')
    
    #trend データのプロット
    plt.subplot(412)
    plt.plot(trend)
    plt.ylabel('Trend')
    
    #seasonalデータ のプロット
    plt.subplot(413)
    plt.plot(seasonal)
    plt.ylabel('Seasonality')
    
    #residual データのプロット
    plt.subplot(414)
    plt.plot(residual)
    plt.ylabel('Residuals')
    
    plt.tight_layout()


    画像


    次にコレログラムを示していく,まずは元の系列から。グラフから,自己相関がありそうだと目星がつく。

    fig = plt.figure(figsize=(8, 8))
    
    #自己相関(ACF)のグラフ
    ax1 = fig.add_subplot(211)
    sm.graphics.tsa.plot_acf(ts, lags=40, ax=ax1)
    
    #偏自己相関(PACF)のグラフ
    ax2 = fig.add_subplot(212)
    sm.graphics.tsa.plot_pacf(ts, lags=40, ax=ax2)
    
    plt.tight_layout()


    画像


    右上がりのトレンドを除去するために,今回は差分系列を用いることにする。

    #差分系列
    delts= np.diff(data['y'])
    plt.plot(delts)


    画像


    差分系列のコレログラムをみると,12おきにピークが見られることがわかる,これは季節変化によるものである。

    #差分系列でコレログラム作成
    fig = plt.figure(figsize=(8, 8))
    
    #自己相関(ACF)のグラフ
    ax1 = fig.add_subplot(211)
    sm.graphics.tsa.plot_acf(passengers_diff, lags=40, ax=ax1) #ACF計算とグラフ自動作成
    
    #偏自己相関(PACF)のグラフ
    ax2 = fig.add_subplot(212)
    sm.graphics.tsa.plot_pacf(passengers_diff, lags=40, ax=ax2) #PACF計算とグラフ自動作成
    
    plt.tight_layout() # グラフ間スキマ調整


    画像


    本記事のもくじはこちら:


    あなたへのおすすめ