回帰診断¶

この例のファイルでは、実際の状況でいくつかのstatsmodels回帰診断検定をどのように使用するかを示しています。さらに多くの検定について学び、検定に関する詳細情報は回帰診断ページで確認できます。

ここで説明されているほとんどの検定は、注釈なしで数値のタプルのみを返すことに注意してください。出力の詳細な説明は、常にドキュメンテーション文字列とオンラインのstatsmodelsドキュメントに含まれています。プレゼンテーションの目的で、以下の例ではzip(name,test)構文を使用して、簡潔な説明を整形して表示しています。

回帰モデルを推定する¶

In [1]:
%matplotlib inline
In [2]:
from statsmodels.compat import lzip

import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
import statsmodels.stats.api as sms
import matplotlib.pyplot as plt

# Load data
url = "https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/master/csv/HistData/Guerry.csv"
dat = pd.read_csv(url)

# Fit regression model (using the natural log of one of the regressors)
results = smf.ols("Lottery ~ Literacy + np.log(Pop1831)", data=dat).fit()

# Inspect the results
print(results.summary())
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                Lottery   R-squared:                       0.348
Model:                            OLS   Adj. R-squared:                  0.333
Method:                 Least Squares   F-statistic:                     22.20
Date:                Wed, 28 Aug 2024   Prob (F-statistic):           1.90e-08
Time:                        14:30:40   Log-Likelihood:                -379.82
No. Observations:                  86   AIC:                             765.6
Df Residuals:                      83   BIC:                             773.0
Df Model:                           2                                         
Covariance Type:            nonrobust                                         
===================================================================================
                      coef    std err          t      P>|t|      [0.025      0.975]
-----------------------------------------------------------------------------------
Intercept         246.4341     35.233      6.995      0.000     176.358     316.510
Literacy           -0.4889      0.128     -3.832      0.000      -0.743      -0.235
np.log(Pop1831)   -31.3114      5.977     -5.239      0.000     -43.199     -19.424
==============================================================================
Omnibus:                        3.713   Durbin-Watson:                   2.019
Prob(Omnibus):                  0.156   Jarque-Bera (JB):                3.394
Skew:                          -0.487   Prob(JB):                        0.183
Kurtosis:                       3.003   Cond. No.                         702.
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

残差の正規性¶

ジャルク・ベラ検定

In [3]:
name = ["Jarque-Bera", "Chi^2 two-tail prob.", "Skew", "Kurtosis"]
test = sms.jarque_bera(results.resid)
lzip(name, test)
Out[3]:
[('Jarque-Bera', 3.393608024843182),
 ('Chi^2 two-tail prob.', 0.18326831231663226),
 ('Skew', -0.48658034311223486),
 ('Kurtosis', 3.003417757881634)]

オムニバス検定:

In [4]:
name = ["Chi^2", "Two-tail probability"]
test = sms.omni_normtest(results.resid)
lzip(name, test)
Out[4]:
[('Chi^2', 3.713437811597197), ('Two-tail probability', 0.15618424580304707)]

影響度検定¶

作成後、OLSInfluenceクラスのオブジェクトは、各観測値の影響度を評価するための属性やメソッドを保持します。例えば、次のようにしてDFbetasの最初の数行を計算し、抽出することができます:

In [5]:
from statsmodels.stats.outliers_influence import OLSInfluence

test_class = OLSInfluence(results)
test_class.dfbetas[:5, :]
Out[5]:
array([[-0.00301154,  0.00290872,  0.00118179],
       [-0.06425662,  0.04043093,  0.06281609],
       [ 0.01554894, -0.03556038, -0.00905336],
       [ 0.17899858,  0.04098207, -0.18062352],
       [ 0.29679073,  0.21249207, -0.3213655 ]])

dir(influence_test) と入力して他のオプションを探索してください。

レバレッジに関する有用な情報もプロットできます:

In [6]:
from statsmodels.graphics.regressionplots import plot_leverage_resid2

fig, ax = plt.subplots(figsize=(8, 6))
fig = plot_leverage_resid2(results, ax=ax)
No description has been provided for this image

その他のプロットオプションはグラフィックスページで確認できます。

多重共線性¶

条件数:

In [7]:
np.linalg.cond(results.model.exog)
Out[7]:
702.1792145490067

不均一分散性検定¶

ブリューシュ・ペイガン検定:

In [8]:
name = ["Lagrange multiplier statistic", "p-value", "f-value", "f p-value"]
test = sms.het_breuschpagan(results.resid, results.model.exog)
lzip(name, test)
Out[8]:
[('Lagrange multiplier statistic', 4.893213374094033),
 ('p-value', 0.0865869050235188),
 ('f-value', 2.503715946256477),
 ('f p-value', 0.08794028782672685)]

ゴールドフェルト-クヴァント検定

In [9]:
name = ["F statistic", "p-value"]
test = sms.het_goldfeldquandt(results.resid, results.model.exog)
lzip(name, test)
Out[9]:
[('F statistic', 1.1002422436378145), ('p-value', 0.38202950686925136)]

線形性¶

線形仕様が正しいという帰無仮説に対するハーヴィー・コリア乗数検定:

In [10]:
name = ["t value", "p value"]
test = sms.linear_harvey_collier(results)
lzip(name, test)
Out[10]:
[('t value', -1.0796490077759802), ('p value', 0.2834639247569222)]
In [ ]: