状態空間法による時系列分析 statespace

statsmodels.tsa.statespaceには、状態空間法を用いた時系列分析に役立つクラスと関数が含まれています。

一般的な状態空間モデルは次の形式で表されます。

\[\begin{split}y_t & = Z_t \alpha_t + d_t + \varepsilon_t \\ \alpha_{t+1} & = T_t \alpha_t + c_t + R_t \eta_t \\\end{split}\]

ここで、\(y_t\) は時刻 \(t\) における観測ベクトルを、\(\alpha_t\) は時刻 \(t\) における(非観測)状態ベクトルを指し、不規則成分は次のように定義されます。

\[\begin{split}\varepsilon_t \sim N(0, H_t) \\ \eta_t \sim N(0, Q_t) \\\end{split}\]

方程式の残りの変数 (\(Z_t, d_t, H_t, T_t, c_t, R_t, Q_t\)) は、プロセスを記述する行列です。これらの変数名と次元は次のとおりです。

Z : design \((k\_endog \times k\_states \times nobs)\)

d : obs_intercept \((k\_endog \times nobs)\)

H : obs_cov \((k\_endog \times k\_endog \times nobs)\)

T : transition \((k\_states \times k\_states \times nobs)\)

c : state_intercept \((k\_states \times nobs)\)

R : selection \((k\_states \times k\_posdef \times nobs)\)

Q : state_cov \((k\_posdef \times k\_posdef \times nobs)\)

いずれかの行列が時間不変である場合(例えば、\(Z_t = Z_{t+1} ~ \forall ~ t\)の場合)、その最後の次元はサイズ nobs ではなく、サイズ \(1\) になる場合があります。

この一般的な形式は、最も普及している線形時系列モデルの多くをカプセル化し(下記参照)、欠損値のある観測値による推定、予測、インパルス応答関数など、非常に柔軟に対応できます。

例:AR(2) モデル

自己回帰モデルは、モデルを状態空間形式にするための良い導入例です。AR(2) モデルはしばしば次のように記述されることを思い出してください。

\[y_t = \phi_1 y_{t-1} + \phi_2 y_{t-2} + \epsilon_t, \quad \epsilon_t \sim N(0, \sigma^2)\]

これは、次のように状態空間形式にすることができます。

\[\begin{split}y_t & = \begin{bmatrix} 1 & 0 \end{bmatrix} \alpha_t \\ \alpha_{t+1} & = \begin{bmatrix} \phi_1 & \phi_2 \\ 1 & 0 \end{bmatrix} \alpha_t + \begin{bmatrix} 1 \\ 0 \end{bmatrix} \eta_t\end{split}\]

ここで

\[Z_t \equiv Z = \begin{bmatrix} 1 & 0 \end{bmatrix}\]

および

\[\begin{split}T_t \equiv T & = \begin{bmatrix} \phi_1 & \phi_2 \\ 1 & 0 \end{bmatrix} \\ R_t \equiv R & = \begin{bmatrix} 1 \\ 0 \end{bmatrix} \\ \eta_t \equiv \epsilon_{t+1} & \sim N(0, \sigma^2)\end{split}\]

このモデルには、\(\phi_1, \phi_2, \sigma^2\) の3つの未知パラメータがあります。

モデルと推定

以下は、statsmodels.tsa.statespace.api およびその結果クラスを介してアクセスできる、主な推定クラスです。

外生変数付き季節自己回帰和分移動平均(SARIMAX)

SARIMAX クラスは、推定のために状態空間バックエンドを使用して作成された本格的なモデルの一例です。SARIMAXtsa モデルと非常によく似た方法で使用できますが、加法的および乗法的な季節効果の推定、および任意のトレンド多項式を追加することにより、より広範囲のモデルで動作します。

sarimax.SARIMAX(endog[, exog, order, ...])

外生変数付き季節自己回帰和分移動平均モデル

sarimax.SARIMAXResults(model, params, ...[, ...])

SARIMAX モデルの適合結果を保持するクラス。

このモデルの使用例については、SARIMAX の例のノートブック、または以下の非常に短いコードスニペットを参照してください。

# Load the statsmodels api
import statsmodels.api as sm

# Load your dataset
endog = pd.read_csv('your/dataset/here.csv')

# We could fit an AR(2) model, described above
mod_ar2 = sm.tsa.SARIMAX(endog, order=(2,0,0))
# Note that mod_ar2 is an instance of the SARIMAX class

# Fit the model via maximum likelihood
res_ar2 = mod_ar2.fit()
# Note that res_ar2 is an instance of the SARIMAXResults class

# Show the summary of results
print(res_ar2.summary())

# We could also fit a more complicated model with seasonal components.
# As an example, here is an SARIMA(1,1,1) x (0,1,1,4):
mod_sarimax = sm.tsa.SARIMAX(endog, order=(1,1,1),
                             seasonal_order=(0,1,1,4))
res_sarimax = mod_sarimax.fit()

# Show the summary of results
print(res_sarimax.summary())

結果オブジェクトには、標準誤差、z 統計量、予測/予測など、他の statsmodels の結果オブジェクトから期待される多くの属性とメソッドがあります。

舞台裏では、SARIMAX モデルは、モデルの仕様に基づいて、設計および遷移行列(および場合によっては他の行列の一部)を作成します。

非観測成分

UnobservedComponents クラスは、別の状態空間モデルの例です。

structural.UnobservedComponents(endog[, ...])

単変量非観測成分時系列モデル

structural.UnobservedComponentsResults(...)

非観測成分モデルの適合結果を保持するクラス。

このモデルの使用例については、example notebook、または非観測成分モデルを使用して時系列をトレンドとサイクルに分解するノートブック、または以下の簡単なコードスニペットを参照してください。

# Load the statsmodels api
import statsmodels.api as sm

# Load your dataset
endog = pd.read_csv('your/dataset/here.csv')

# Fit a local level model
mod_ll = sm.tsa.UnobservedComponents(endog, 'local level')
# Note that mod_ll is an instance of the UnobservedComponents class

# Fit the model via maximum likelihood
res_ll = mod_ll.fit()
# Note that res_ll is an instance of the UnobservedComponentsResults class

# Show the summary of results
print(res_ll.summary())

# Show a plot of the estimated level and trend component series
fig_ll = res_ll.plot_components()

# We could further add a damped stochastic cycle as follows
mod_cycle = sm.tsa.UnobservedComponents(endog, 'local level', cycle=True,
                                        damped_cycle=True,
                                        stochastic_cycle=True)
res_cycle = mod_cycle.fit()

# Show the summary of results
print(res_cycle.summary())

# Show a plot of the estimated level, trend, and cycle component series
fig_cycle = res_cycle.plot_components()

外生変数付きベクトル自己回帰移動平均(VARMAX)

VARMAXクラスは、多変量状態空間モデルの一例です。

varmax.VARMAX(endog[, exog, order, trend, ...])

外生変数付きベクトル自己回帰移動平均モデル

varmax.VARMAXResults(model, params, ...[, ...])

VARMAXモデルのフィッティング結果を保持するクラス。

このモデルの使用例については、VARMAXの例のノートブックまたは以下の簡単なコードスニペットを参照してください。

# Load the statsmodels api
import statsmodels.api as sm

# Load your (multivariate) dataset
endog = pd.read_csv('your/dataset/here.csv')

# Fit a local level model
mod_var1 = sm.tsa.VARMAX(endog, order=(1,0))
# Note that mod_var1 is an instance of the VARMAX class

# Fit the model via maximum likelihood
res_var1 = mod_var1.fit()
# Note that res_var1 is an instance of the VARMAXResults class

# Show the summary of results
print(res_var1.summary())

# Construct impulse responses
irfs = res_ll.impulse_responses(steps=10)

動的因子モデル

Statsmodelsには、動的因子モデルをサポートする2つのクラス:DynamicFactorMQDynamicFactorがあります。これらのモデルにはそれぞれ長所がありますが、一般的にDynamicFactorMQクラスが推奨されます。これは、期待値最大化(EM)アルゴリズムを使用してパラメータをフィッティングするため、よりロバストであり、観測された数百の系列を含めることができるためです。さらに、どの変数がどの因子にロードされるかをカスタマイズできます。ただし、DynamicFactorがその機能をサポートしているのに対し、外生変数を含めることはまだサポートしていません。

dynamic_factor_mq.DynamicFactorMQ(endog[, ...])

EMアルゴリズムを使用した動的因子モデル。月次/四半期データ用のオプション。

dynamic_factor_mq.DynamicFactorMQResults(...)

動的因子モデルのフィッティング結果

DynamicFactorMQクラスの例については、以下の簡単なコードスニペットを参照してください。

# Load the statsmodels api
import statsmodels.api as sm

# Load your dataset
endog = pd.read_csv('your/dataset/here.csv')

# Create a dynamic factor model
mod_dfm = sm.tsa.DynamicFactorMQ(endog, k_factors=1, factor_order=2)
# Note that mod_dfm is an instance of the DynamicFactorMQ class

# Fit the model via maximum likelihood, using the EM algorithm
res_dfm = mod_dfm.fit()
# Note that res_dfm is an instance of the DynamicFactorMQResults class

# Show the summary of results
print(res_ll.summary())

# Show a plot of the r^2 values from regressions of
# individual estimated factors on endogenous variables.
fig_dfm = res_ll.plot_coefficients_of_determination()

DynamicFactorクラスは、観測変数の数が少ないモデルに適しています。

dynamic_factor.DynamicFactor(endog, ...[, ...])

動的因子モデル

dynamic_factor.DynamicFactorResults(model, ...)

DynamicFactorモデルのフィッティング結果を保持するクラス。

DynamicFactorモデルの使用例については、動的因子モデルの例のノートブックを参照してください。

線形指数平滑モデル

ExponentialSmoothingクラスは、状態空間アプローチを使用した線形指数平滑モデルの実装です。

:このモデルはsm.tsa.statespace.ExponentialSmoothingで利用できます。これはsm.tsa.ExponentialSmoothingで利用可能なモデルと同じではありません。これらのクラス間の違いの詳細については、以下を参照してください。

exponential_smoothing.ExponentialSmoothing(endog)

線形指数平滑モデル

exponential_smoothing.ExponentialSmoothingResults(...)

線形指数平滑モデルのフィッティング結果

ごく簡単なコードスニペットを以下に示します。

# Load the statsmodels api
import statsmodels.api as sm

# Load your dataset
endog = pd.read_csv('your/dataset/here.csv')

# Simple exponential smoothing, denoted (A,N,N)
mod_ses = sm.tsa.statespace.ExponentialSmoothing(endog)
res_ses = mod_ses.fit()

# Holt's linear method, denoted (A,A,N)
mod_h = sm.tsa.statespace.ExponentialSmoothing(endog, trend=True)
res_h = mod_h.fit()

# Damped trend model, denoted (A,Ad,N)
mod_dt = sm.tsa.statespace.ExponentialSmoothing(endog, trend=True,
                                                damped_trend=True)
res_dt = mod_dt.fit()

# Holt-Winters' trend and seasonality method, denoted (A,A,A)
# (assuming that `endog` has a seasonal periodicity of 4, for example if it
# is quarterly data).
mod_hw = sm.tsa.statespace.ExponentialSmoothing(endog, trend=True,
                                                seasonal=4)
res_hw = mod_hw.fit()

Statsmodelsの指数平滑モデルクラス間の違い

sm.tsa.statespace.ExponentialSmoothingで利用可能なこのモデルクラスとsm.tsa.ExponentialSmoothingで利用可能なモデルクラスにはいくつかの違いがあります。

  • このモデルクラスは線形指数平滑モデルのみをサポートしますが、sm.tsa.ExponentialSmoothingは乗法モデルもサポートしています。

  • このモデルクラスは、指数平滑モデルを状態空間形式にし、カルマンフィルターを適用して状態を推定しますが、sm.tsa.ExponentialSmoothingは指数平滑再帰に基づいています。場合によっては、このモデルクラスでパラメータを推定すると、sm.tsa.ExponentialSmoothingを使用するよりも多少遅くなる可能性があります。

  • このモデルクラスは、ガウス誤差の仮定に基づいて、予測の信頼区間を生成できますが、sm.tsa.ExponentialSmoothingは信頼区間をサポートしていません。

  • このモデルクラスは、目的関数から初期値を集中させることをサポートしています。これにより、推定する初期状態が多い場合(たとえば、季節周期が大きい場合)にパフォーマンスを向上させることができます。

  • このモデルクラスは、状態空間モデルで利用可能な診断や固定パラメータなど、多くの高度な機能をサポートしています。

:このクラスは、「単一誤差源」(SSOE)の定式化ではなく、「複数誤差源」(MSOE)の状態空間定式化に基づいています。

カスタム状態空間モデル

状態空間モデルの真の力は、カスタムモデルの作成と推定を可能にすることです。通常、それは、状態空間表現、カルマンフィルタリング、および推定と結果出力のための最大尤度フィッティング機能をすべてバンドルする次の2つのクラスを拡張することによって行われます。

mlemodel.MLEModel(endog, k_states[, exog, ...])

最大尤度推定のための状態空間モデル

mlemodel.MLEResults(model, params, results)

状態空間モデルのフィッティング結果を保持するクラス。

mlemodel.PredictionResults(model, ...[, ...])

MLEモデルからの予測結果

カスタム状態空間モデルを作成および推定する基本的な例については、ローカル線形トレンドの例のノートブックを参照してください。より高度な例については、MLEModelおよびMLEResultsを拡張して構築されたSARIMAXおよびSARIMAXResultsクラスのソースコードを参照してください。

単純なケースでは、モデルはMLEModelクラスのみを使用して完全に構築できます。たとえば、上記のAR(2)モデルは、次のコードのみを使用して構築および推定できます。

import numpy as np
from scipy.signal import lfilter
import statsmodels.api as sm

# True model parameters
nobs = int(1e3)
true_phi = np.r_[0.5, -0.2]
true_sigma = 1**0.5

# Simulate a time series
np.random.seed(1234)
disturbances = np.random.normal(0, true_sigma, size=(nobs,))
endog = lfilter([1], np.r_[1, -true_phi], disturbances)

# Construct the model
class AR2(sm.tsa.statespace.MLEModel):
    def __init__(self, endog):
        # Initialize the state space model
        super(AR2, self).__init__(endog, k_states=2, k_posdef=1,
                                  initialization='stationary')

        # Setup the fixed components of the state space representation
        self['design'] = [1, 0]
        self['transition'] = [[0, 0],
                                  [1, 0]]
        self['selection', 0, 0] = 1

    # Describe how parameters enter the model
    def update(self, params, transformed=True, **kwargs):
        params = super(AR2, self).update(params, transformed, **kwargs)

        self['transition', 0, :] = params[:2]
        self['state_cov', 0, 0] = params[2]

    # Specify start parameters and parameter names
    @property
    def start_params(self):
        return [0,0,1]  # these are very simple

# Create and fit the model
mod = AR2(endog)
res = mod.fit()
print(res.summary())

これにより、次の要約表が生成されます。

                           Statespace Model Results
==============================================================================
Dep. Variable:                      y   No. Observations:                 1000
Model:                            AR2   Log Likelihood               -1389.437
Date:                Wed, 26 Oct 2016   AIC                           2784.874
Time:                        00:42:03   BIC                           2799.598
Sample:                             0   HQIC                          2790.470
                               - 1000
Covariance Type:                  opg
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
param.0        0.4395      0.030     14.730      0.000       0.381       0.498
param.1       -0.2055      0.032     -6.523      0.000      -0.267      -0.144
param.2        0.9425      0.042     22.413      0.000       0.860       1.025
===================================================================================
Ljung-Box (Q):                       24.25   Jarque-Bera (JB):                 0.22
Prob(Q):                              0.98   Prob(JB):                         0.90
Heteroskedasticity (H):               1.05   Skew:                            -0.04
Prob(H) (two-sided):                  0.66   Kurtosis:                         3.02
===================================================================================

Warnings:
[1] Covariance matrix calculated using the outer product of gradients (complex-step).

結果オブジェクトには、標準誤差、z 統計量、予測/予測など、他の statsmodels の結果オブジェクトから期待される多くの属性とメソッドがあります。

より高度な使用法も可能であり、パラメータ変換の指定や、より情報量の多い出力サマリーのためのパラメータ名の指定などが含まれます。

使用法の概要

すべての状態空間モデルは、一般的なStatsmodelsパターンに従います。

  1. 入力データセットを使用してモデルインスタンスを構築します。

  2. パラメータをモデルに適用します(たとえば、fitを使用して)、結果インスタンスを構築します。

  3. 結果インスタンスを操作して、推定されたパラメータを調べ、残差診断を探索し、予測、シミュレーション、またはインパルス応答を生成します。

このパターンの例を次に示します。

# Load in the example macroeconomic dataset
dta = sm.datasets.macrodata.load_pandas().data
# Make sure we have an index with an associated frequency, so that
# we can refer to time periods with date strings or timestamps
dta.index = pd.date_range('1959Q1', '2009Q3', freq='QS')

# Step 1: construct an SARIMAX model for US inflation data
model = sm.tsa.SARIMAX(dta.infl, order=(4, 0, 0), trend='c')

# Step 2: fit the model's parameters by maximum likelihood
results = model.fit()

# Step 3: explore / use results

# - Print a table summarizing estimation results
print(results.summary())

# - Print only the estimated parameters
print(results.params)

# - Create diagnostic figures based on standardized residuals:
#   (1) time series graph
#   (2) histogram
#   (3) Q-Q plot
#   (4) correlogram
results.plot_diagnostics()

# - Examine diagnostic hypothesis tests
# Jarque-Bera: [test_statistic, pvalue, skewness, kurtosis]
print(results.test_normality(method='jarquebera'))
# Goldfeld-Quandt type test: [test_statistic, pvalue]
print(results.test_heteroskedasticity(method='breakvar'))
# Ljung-Box test: [test_statistic, pvalue] for each lag
print(results.test_serial_correlation(method='ljungbox'))

# - Forecast the next 4 values
print(results.forecast(4))

# - Forecast until 2020Q4
print(results.forecast('2020Q4'))

# - Plot in-sample dynamic prediction starting in 2005Q1
#   and out-of-sample forecasts until 2010Q4 along with
#   90% confidence intervals
predict_results = results.get_prediction(start='2005Q1', end='2010Q4', dynamic=True)
predict_df = predict_results.summary_frame(alpha=0.10)
fig, ax = plt.subplots()
predict_df['mean'].plot(ax=ax)
ax.fill_between(predict_df.index, predict_df['mean_ci_lower'],
                predict_df['mean_ci_upper'], alpha=0.2)

# - Simulate two years of new data after the end of the sample
print(results.simulate(8, anchor='end'))

# - Impulse responses for two years
print(results.impulse_responses(8))

推定/フィルタリング/平滑化のための基本的なメソッドと属性

状態空間モデルで最もよく使用されるメソッドは次のとおりです。

  • fit - 最大尤度法によってパラメータを推定し、結果オブジェクトを返します(このオブジェクトは、推定されたパラメータでカルマンフィルタリングと平滑化も実行します)。これは最も一般的に使用されるメソッドです。

  • smooth - カルマンフィルタリングと平滑化を実行した後、特定のパラメータベクトルに関連付けられた結果オブジェクトを返します。

  • loglike - 特定のパラメータベクトルを使用してデータの対数尤度を計算します。

状態空間モデルの便利な属性は次のとおりです。

  • param_names - モデルで使用されるパラメータの名前。

  • state_names - (観測されない)状態ベクトルの要素の名前

  • start_params - 数値的な最大尤度最適化の開始値として使用される初期パラメータ推定値

あまり使用されないその他のメソッドは次のとおりです

  • filter - カルマンフィルタリングのみを実行した後の、パラメータの特定のベクトルに関連付けられた結果オブジェクトを返します (平滑化は行いません)

  • simulation_smoother - シミュレーション平滑化を実行できるオブジェクトを返します

出力と事後推定のメソッドと属性

一般的に使用されるメソッドは次のとおりです

  • summary - モデル適合統計、推定パラメータ、およびその他の要約出力を示すテーブルを作成します

  • predict - インサンプル予測とアウトオブサンプル予測を計算します (点推定のみ)

  • get_prediction - 信頼区間を含むインサンプル予測とアウトオブサンプル予測を計算します

  • forecast - アウトオブサンプル予測を計算します (点推定のみ) (これはpredictの便利なラッパーです)

  • get_forecast - 信頼区間を含むアウトオブサンプル予測を計算します (これはget_predictionの便利なラッパーです)

  • simulate - 状態空間モデルに従って新しいデータをシミュレートします

  • impulse_responses - 状態空間モデルからインパルス応答を計算します

一般的に使用される属性は次のとおりです

  • params - 推定パラメータ

  • bse - 推定パラメータの標準誤差

  • pvalues - 推定パラメータに関連付けられた p 値

  • llf - 推定されたパラメータでのデータの対数尤度

  • ssemse、およびmae - 二乗誤差の合計、平均二乗誤差、平均絶対誤差

  • 次の情報基準: aicaiccbic、およびhquc

  • fittedvalues - モデルからの適合値 (これらは一歩先の予測であることに注意してください)

  • resid - モデルからの残差 (これらは一歩先の予測誤差であることに注意してください)

観測されない状態の推定値と共分散

観測されたデータに基づいて条件付きの観測されない状態ベクトルの推定値を計算すると役立つ場合があります。これらは、結果オブジェクトstatesで利用でき、次の要素が含まれています

  • states.filtered - 状態ベクトルのフィルタリングされた (片側) 推定値。時点 t における状態ベクトルの推定値は、時点 t までの観測データに基づいています。

  • states.smoothed - 状態ベクトルの平滑化された (両側) 推定値。時点 t における状態ベクトルの推定値は、サンプル内のすべての観測データに基づいています。

  • states.filtered_cov - 状態ベクトルのフィルタリングされた (片側) 共分散

  • states.smoothed_cov - 状態ベクトルの平滑化された (両側) 共分散

これらの各要素は、Pandas のDataFrameオブジェクトです。

例として、UnobservedComponentsコンポーネントクラスを介して推定された「ローカルレベル + 季節」モデルでは、経時的な系列の基礎となるレベルと季節的な動きの推定値を取得できます。

fig, axes = plt.subplots(3, 1, figsize=(8, 8))

# Retrieve monthly retail sales for clothing
from pandas_datareader.data import DataReader
clothing = DataReader('MRTSSM4481USN', 'fred', start='1992').asfreq('MS')['MRTSSM4481USN']

# Construct a local level + seasonal model
model = sm.tsa.UnobservedComponents(clothing, 'llevel', seasonal=12)
results = model.fit()

# Plot the data, the level, and seasonal
clothing.plot(ax=axes[0])
results.states.smoothed['level'].plot(ax=axes[1])
results.states.smoothed['seasonal'].plot(ax=axes[2])

残差診断

組み込みであるかカスタムであるかに関係なく、状態空間モデルの推定後、モデルが基礎となる統計的仮定に適合するかどうかを評価するのに役立つ 3 つの診断テストを利用できます。これらのテストは次のとおりです

同じ目的のために、回帰残差の標準的なプロットが多数用意されています。これらは、コマンドplot_diagnosticsを使用して生成できます。

更新または異なるデータセットへの推定パラメータの適用

結果オブジェクトから推定されたパラメータを、更新または異なるデータセットに適用するために使用できる 3 つの方法があります

  • append - 現在のサンプルの終わり後に続く追加の観測値が追加された新しい結果オブジェクトを取得します (したがって、新しい結果オブジェクトには、現在のサンプルと追加の観測値の両方が含まれます)

  • extend - 現在のサンプルの終わりに続く追加の観測値に対する新しい結果オブジェクトを取得します (したがって、新しい結果オブジェクトには、新しい観測値のみが含まれますが、現在のサンプルは含まれません)

  • apply - まったく異なるデータセットの新しい結果オブジェクトを取得します

時系列データに対する 1 つのクロスバリデーション演習では、トレーニングサンプル (時点 t までの観測) に基づいてモデルのパラメータを適合させ、テストサンプル (観測t+1t+2、…)を使用してモデルの適合度を評価します。これは、applyまたはextendのいずれかを使用すると便利に実行できます。次の例では、extendメソッドを使用します。

# Load in the example macroeconomic dataset
dta = sm.datasets.macrodata.load_pandas().data
# Make sure we have an index with an associated frequency, so that
# we can refer to time periods with date strings or timestamps
dta.index = pd.date_range('1959Q1', '2009Q3', freq='QS')

# Separate inflation data into a training and test dataset
training_endog = dta['infl'].iloc[:-1]
test_endog = dta['infl'].iloc[-1:]

# Fit an SARIMAX model for inflation
training_model = sm.tsa.SARIMAX(training_endog, order=(4, 0, 0))
training_results = training_model.fit()

# Extend the results to the test observations
test_results = training_results.extend(test_endog)

# Print the sum of squared errors in the test sample,
# based on parameters computed using only the training sample
print(test_results.sse)

データ改訂の影響の理解

状態空間モデルの結果は、データ修正(ニュース)がモデルパラメータに与える影響を理解するために使用できるnewsメソッドを公開します。

news.NewsResults(news_results, モデル, ...[, ...])

データ修正とニュースが関心のある変数の推定に与える影響

追加のオプションとツール

すべての状態空間モデルには、次のオプションとツールがあります。

一部のパラメータを固定して残りを推定する

fit_constrainedメソッドを使用すると、一部のパラメータを既知の値に固定し、残りを最尤法によって推定できます。 これの例は次のとおりです。

# Construct a model
model = sm.tsa.SARIMAX(endog, order=(1, 0, 0))

# To find out the parameter names, use:
print(model.param_names)

# Fit the model with a fixed value for the AR(1) coefficient:
results = model.fit_constrained({'ar.L1': 0.5})

または、fix_paramsコンテキストマネージャーを使用できます。

# Construct a model
model = sm.tsa.SARIMAX(endog, order=(1, 0, 0))

# Fit the model with a fixed value for the AR(1) coefficient using the
# context manager
with model.fix_params({'ar.L1': 0.5}):
    results = model.fit()

低メモリオプション

観測されたデータセットが非常に大きい場合や、モデルの状態ベクトルが高次元である場合(たとえば、長期的な季節効果を考慮する場合)、デフォルトのメモリ要件が大きすぎる可能性があります。このため、fitfilter、およびsmoothメソッドは、オプションのlow_memory=True引数を受け入れます。これにより、メモリ要件を大幅に削減し、モデルの適合を高速化できます。

low_memory=Trueを使用する場合、すべての結果オブジェクトが利用できるわけではないことに注意してください。ただし、残差診断、インサンプル(非動的)予測、およびアウトオブサンプル予測はすべて引き続き利用できます。

低レベルの状態空間表現とカルマンフィルター

カスタムモデルの作成はほぼ常にMLEModelMLEResultsを拡張することによって行われますが、これらのクラスの背後にある上部構造を理解すると役立つ場合があります。

最尤推定では、モデルの尤度関数を評価する必要があり、状態空間形式のモデルの場合、尤度関数はカルマンフィルターを実行した副産物として評価されます。

MLEModelで使用される2つのクラスがあり、状態空間モデルとカルマンフィルターの仕様を容易にします。 それらは、RepresentationKalmanFilterです。

Representationクラスは、状態空間モデル表現が定義される部分です。簡単に言うと、状態空間行列(designobs_interceptなど。上記の状態空間モデルの紹介を参照)を保持し、それらの操作を可能にします。

FrozenRepresentationは、任意の時点での状態空間表現の「スナップショット」を取得するという点で、最も基本的な結果型のクラスです。利用可能な属性の完全なリストについては、クラスドキュメントを参照してください。

representation.Representation(k_endog, k_states)

時系列プロセスの状態空間表現

representation.FrozenRepresentation(model)

フローズン状態空間モデル

KalmanFilterクラスは、フィルタリング機能を提供するRepresentationのサブクラスです。状態空間表現行列が構築されると、filterメソッドを呼び出すことができ、FilterResultsインスタンスが生成されます。FilterResultsFrozenRepresentationのサブクラスです。

FilterResultsクラスは、状態空間モデルのフリーズされた表現(設計、遷移などの行列、モデルの次元など)を保持するだけでなく、filtered stateや対数尤度を含むフィルタリング出力も保持します(利用可能な結果の完全なリストについては、クラスドキュメントを参照してください)。また、インサンプル予測またはアウトオブサンプル予測を可能にするpredictメソッドも提供します。同様のメソッドであるpredictは、信頼区間を含む追加の予測または予測結果を提供します。

kalman_filter.KalmanFilter(k_endog, k_states)

カルマンフィルターを使用した時系列プロセスの状態空間表現

kalman_filter.FilterResults(model)

状態空間モデルにカルマンフィルターを適用した結果。

kalman_filter.PredictionResults(results, ...)

状態空間モデルのインサンプルおよびアウトオブサンプル予測の結果

KalmanSmootherクラスは、スムージング機能を提供するKalmanFilterのサブクラスです。状態空間表現行列が構築されると、filterメソッドを呼び出すことができ、SmootherResultsインスタンスが生成されます。SmootherResultsFilterResultsのサブクラスです。

SmootherResultsクラスは、FilterResultsからのすべての出力を保持しますが、smoothed stateや対数尤度を含むスムージング出力も含まれます(利用可能な結果の完全なリストについては、クラスドキュメントを参照してください)。時刻tでの「フィルター処理された」出力は、時刻tまでの観測を条件とした推定値を指しますが、「平滑化された」出力は、データセット内の観測のセット全体を条件とした推定値を指します。

kalman_smoother.KalmanSmoother(k_endog, k_states)

カルマンフィルターとスムーザーを使用した時系列プロセスの状態空間表現。

kalman_smoother.SmootherResults(model)

状態空間モデルにカルマンスムーザーおよび/またはフィルターを適用した結果。

SimulationSmootherクラスは、シミュレーションとシミュレーションスムージング機能を提供するKalmanSmootherのサブクラスです。simulation_smootherメソッドを呼び出すことができ、SimulationSmoothResultsインスタンスが生成されます。

SimulationSmoothResultsクラスには、状態ベクトルの結合事後分布からドローするためにシミュレーションスムージングを実行できるsimulateメソッドがあります。これは、ギブスサンプリングによる状態空間モデルのベイズ推定に役立ちます。

simulation_smoother.SimulationSmoother(...)

カルマンフィルターとスムーザー、およびシミュレーションスムーザーを備えた時系列プロセスの状態空間表現。

simulation_smoother.SimulationSmoothResults(...)

状態空間モデルにカルマンスムーザーおよび/またはフィルターを適用した結果。

cfa_simulation_smoother.CFASimulationSmoother(model)

"Cholesky Factor Algorithm"(CFA)シミュレーションスムーザー

状態空間ツール

状態空間モデリングまたはSARIMAXクラスで使用されるさまざまなツールがあります

tools.companion_matrix(polynomial)

コンパニオン行列を作成します

tools.diff(series[, k_diff, ...])

ゼロ番目の軸に沿って、系列を単純にまたは季節的に差分します。

tools.is_invertible(polynomial[, threshold])

多項式が可逆かどうかを判断します。

tools.constrain_stationary_univariate(...)

オプティマイザーで使用される制約のないパラメータを、尤度評価で使用される制約のあるパラメータに変換します

tools.unconstrain_stationary_univariate(...)

尤度評価で使用される制約のあるパラメータを、オプティマイザーで使用される制約のないパラメータに変換します

tools.constrain_stationary_multivariate(...)

オプティマイザーで使用される制約のないパラメータを、ベクトル自己回帰の尤度評価で使用される制約のあるパラメータに変換します。

tools.unconstrain_stationary_multivariate(...)

尤度評価で使用される制約のあるパラメータを、オプティマイザーで使用される制約のないパラメータに変換します

tools.validate_matrix_shape(name, shape, ...)

時間とともに変化する可能性のある行列の形状を検証するか、例外を発生させます

tools.validate_vector_shape(name, shape, ...)

時間変動する可能性のあるベクトルの形状を検証し、問題があれば例外を発生させます。


最終更新日: 2024年10月03日