公式:使用 R 風格公式擬合模型

自 0.5.0 版起,statsmodels 允許使用者使用 R 風格的公式擬合統計模型。在內部,statsmodels 使用 patsy 套件將公式和資料轉換為模型擬合中使用的矩陣。公式框架非常強大;本教學僅觸及表面。公式語言的完整描述可以在 patsy 文件中找到

載入模組和函數

[1]:
import numpy as np  # noqa:F401  needed in namespace for patsy
import statsmodels.api as sm

匯入慣例

您可以從 statsmodels.formula.api 顯式匯入

[2]:
from statsmodels.formula.api import ols

或者,您可以使用主要 statsmodels.apiformula 命名空間。

[3]:
sm.formula.ols
[3]:
<bound method Model.from_formula of <class 'statsmodels.regression.linear_model.OLS'>>

或者您可以使用以下慣例

[4]:
import statsmodels.formula.api as smf

這些名稱只是存取每個模型的 from_formula 類別方法的便捷方式。例如,請參閱

[5]:
sm.OLS.from_formula
[5]:
<bound method Model.from_formula of <class 'statsmodels.regression.linear_model.OLS'>>

所有小寫模型都接受 formuladata 參數,而大寫模型則採用 endogexog 設計矩陣。formula 接受一個字串,該字串使用 patsy 公式描述模型。data 採用 pandas 資料框架或任何其他為變數名稱定義 __getitem__ 的資料結構,例如結構化陣列或變數字典。

dir(sm.formula) 將列印可用的模型列表。

與公式相容的模型具有以下通用呼叫簽名:(formula, data, subset=None, *args, **kwargs)

使用公式的 OLS 迴歸

首先,我們擬合 入門 頁面上描述的線性模型。下載資料、子集欄位並逐項刪除以移除遺失的觀測值

[6]:
dta = sm.datasets.get_rdataset("Guerry", "HistData", cache=True)
[7]:
df = dta.data[["Lottery", "Literacy", "Wealth", "Region"]].dropna()
df.head()
[7]:
樂透 識字率 財富 區域
0 41 37 73
1 38 51 22
2 66 13 61
3 80 46 76
4 79 69 83

擬合模型

[8]:
mod = ols(formula="Lottery ~ Literacy + Wealth + Region", data=df)
res = mod.fit()
print(res.summary())
                            OLS Regression Results
==============================================================================
Dep. Variable:                Lottery   R-squared:                       0.338
Model:                            OLS   Adj. R-squared:                  0.287
Method:                 Least Squares   F-statistic:                     6.636
Date:                Thu, 03 Oct 2024   Prob (F-statistic):           1.07e-05
Time:                        15:49:16   Log-Likelihood:                -375.30
No. Observations:                  85   AIC:                             764.6
Df Residuals:                      78   BIC:                             781.7
Df Model:                           6
Covariance Type:            nonrobust
===============================================================================
                  coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------
Intercept      38.6517      9.456      4.087      0.000      19.826      57.478
Region[T.E]   -15.4278      9.727     -1.586      0.117     -34.793       3.938
Region[T.N]   -10.0170      9.260     -1.082      0.283     -28.453       8.419
Region[T.S]    -4.5483      7.279     -0.625      0.534     -19.039       9.943
Region[T.W]   -10.0913      7.196     -1.402      0.165     -24.418       4.235
Literacy       -0.1858      0.210     -0.886      0.378      -0.603       0.232
Wealth          0.4515      0.103      4.390      0.000       0.247       0.656
==============================================================================
Omnibus:                        3.049   Durbin-Watson:                   1.785
Prob(Omnibus):                  0.218   Jarque-Bera (JB):                2.694
Skew:                          -0.340   Prob(JB):                        0.260
Kurtosis:                       2.454   Cond. No.                         371.
==============================================================================

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

類別變數

檢視上面列印的摘要,請注意 patsy 確定 *Region* 的元素是文字字串,因此將 *Region* 視為類別變數。patsy 的預設值也包括截距,因此我們自動捨棄了一個 *Region* 類別。

如果 *Region* 是一個我們希望明確視為類別的整數變數,我們可以使用 C() 運算子來實現

[9]:
res = ols(formula="Lottery ~ Literacy + Wealth + C(Region)", data=df).fit()
print(res.params)
Intercept         38.651655
C(Region)[T.E]   -15.427785
C(Region)[T.N]   -10.016961
C(Region)[T.S]    -4.548257
C(Region)[T.W]   -10.091276
Literacy          -0.185819
Wealth             0.451475
dtype: float64

Patsy 針對類別變數的高階功能在以下位置討論:Patsy:類別變數的對比編碼系統

運算子

我們已經看到「~」將模型的左側與右側分隔開來,「+」則將新的欄位新增至設計矩陣。

移除變數

「-」符號可用於移除欄位/變數。例如,我們可以透過以下方式從模型中移除截距

[10]:
res = ols(formula="Lottery ~ Literacy + Wealth + C(Region) -1 ", data=df).fit()
print(res.params)
C(Region)[C]    38.651655
C(Region)[E]    23.223870
C(Region)[N]    28.634694
C(Region)[S]    34.103399
C(Region)[W]    28.560379
Literacy        -0.185819
Wealth           0.451475
dtype: float64

乘法交互作用

「:」會將一個新的欄位新增至設計矩陣,其中包含其他兩個欄位的交互作用。「*」也會包括相乘的個別欄位

[11]:
res1 = ols(formula="Lottery ~ Literacy : Wealth - 1", data=df).fit()
res2 = ols(formula="Lottery ~ Literacy * Wealth - 1", data=df).fit()
print(res1.params, "\n")
print(res2.params)
Literacy:Wealth    0.018176
dtype: float64

Literacy           0.427386
Wealth             1.080987
Literacy:Wealth   -0.013609
dtype: float64

運算子還有許多其他可能性。請參閱 patsy 文件以瞭解更多資訊。

函數

您可以將向量化函數套用至模型中的變數

[12]:
res = smf.ols(formula="Lottery ~ np.log(Literacy)", data=df).fit()
print(res.params)
Intercept           115.609119
np.log(Literacy)    -20.393959
dtype: float64

定義自訂函數

[13]:
def log_plus_1(x):
    return np.log(x) + 1.0


res = smf.ols(formula="Lottery ~ log_plus_1(Literacy)", data=df).fit()
print(res.params)
Intercept               136.003079
log_plus_1(Literacy)    -20.393959
dtype: float64

呼叫命名空間中的任何函數都可用於公式。

將公式用於尚未(尚未)支援的模型

即使給定的 statsmodels 函數不支援公式,您仍然可以使用 patsy 的公式語言來產生設計矩陣。然後,這些矩陣可以作為 endogexog 參數饋送到擬合函數中。

產生 numpy 陣列

[14]:
import patsy

f = "Lottery ~ Literacy * Wealth"
y, X = patsy.dmatrices(f, df, return_type="matrix")
print(y[:5])
print(X[:5])
[[41.]
 [38.]
 [66.]
 [80.]
 [79.]]
[[1.000e+00 3.700e+01 7.300e+01 2.701e+03]
 [1.000e+00 5.100e+01 2.200e+01 1.122e+03]
 [1.000e+00 1.300e+01 6.100e+01 7.930e+02]
 [1.000e+00 4.600e+01 7.600e+01 3.496e+03]
 [1.000e+00 6.900e+01 8.300e+01 5.727e+03]]

產生 pandas 資料框架

[15]:
f = "Lottery ~ Literacy * Wealth"
y, X = patsy.dmatrices(f, df, return_type="dataframe")
print(y[:5])
print(X[:5])
   Lottery
0     41.0
1     38.0
2     66.0
3     80.0
4     79.0
   Intercept  Literacy  Wealth  Literacy:Wealth
0        1.0      37.0    73.0           2701.0
1        1.0      51.0    22.0           1122.0
2        1.0      13.0    61.0            793.0
3        1.0      46.0    76.0           3496.0
4        1.0      69.0    83.0           5727.0
[16]:
print(sm.OLS(y, X).fit().summary())
                            OLS Regression Results
==============================================================================
Dep. Variable:                Lottery   R-squared:                       0.309
Model:                            OLS   Adj. R-squared:                  0.283
Method:                 Least Squares   F-statistic:                     12.06
Date:                Thu, 03 Oct 2024   Prob (F-statistic):           1.32e-06
Time:                        15:49:16   Log-Likelihood:                -377.13
No. Observations:                  85   AIC:                             762.3
Df Residuals:                      81   BIC:                             772.0
Df Model:                           3
Covariance Type:            nonrobust
===================================================================================
                      coef    std err          t      P>|t|      [0.025      0.975]
-----------------------------------------------------------------------------------
Intercept          38.6348     15.825      2.441      0.017       7.149      70.121
Literacy           -0.3522      0.334     -1.056      0.294      -1.016       0.312
Wealth              0.4364      0.283      1.544      0.126      -0.126       0.999
Literacy:Wealth    -0.0005      0.006     -0.085      0.933      -0.013       0.012
==============================================================================
Omnibus:                        4.447   Durbin-Watson:                   1.953
Prob(Omnibus):                  0.108   Jarque-Bera (JB):                3.228
Skew:                          -0.332   Prob(JB):                        0.199
Kurtosis:                       2.314   Cond. No.                     1.40e+04
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 1.4e+04. This might indicate that there are
strong multicollinearity or other numerical problems.

上次更新時間:2024 年 10 月 03 日