含交互作用的一個模型

使用 Python 的 statsmodels 進行迴歸分析:中級

Maarten Van den Broeck

Content Developer at DataCamp

什麼是交互作用?

在魚類資料集中

  • 不同魚種的質量與長度比不同。
  • 長度對預期質量的影響會因魚種而異。

 

更一般地說

一個解釋變數對預期反應的影響,會隨另一個解釋變數的值而改變。

使用 Python 的 statsmodels 進行迴歸分析:中級

指定交互作用

無交互作用

response ~ explntry1 + explntry2

有交互作用(隱含)

response_var ~ explntry1 * explntry2

有交互作用(顯式)

response ~ explntry1 + explntry2 + explntry1:explntry2

無交互作用

mass_g ~ length_cm + species

有交互作用(隱含)

mass_g ~ length_cm * species

有交互作用(顯式)

mass_g ~ length_cm + species + length_cm:species
使用 Python 的 statsmodels 進行迴歸分析:中級

執行模型

mdl_mass_vs_both = ols("mass_g ~ length_cm * species", data=fish).fit()

print(mdl_mass_vs_both.params)
Intercept                    -1035.3476
species[T.Perch]               416.1725
species[T.Pike]               -505.4767
species[T.Roach]               705.9714
length_cm                       54.5500
length_cm:species[T.Perch]     -15.6385
length_cm:species[T.Pike]       -1.3551
length_cm:species[T.Roach]     -31.2307
使用 Python 的 statsmodels 進行迴歸分析:中級

係數更好理解

mdl_mass_vs_both_inter = ols("mass_g ~ species + species:length_cm + 0", data=fish).fit()

print(mdl_mass_vs_both_inter.params)
species[Bream]             -1035.3476
species[Perch]              -619.1751
species[Pike]              -1540.8243
species[Roach]              -329.3762
species[Bream]:length_cm      54.5500
species[Perch]:length_cm      38.9115
species[Pike]:length_cm       53.1949
species[Roach]:length_cm      23.3193
使用 Python 的 statsmodels 進行迴歸分析:中級

熟悉的數字

print(mdl_mass_vs_both_inter.params)
species[Bream]             -1035.3476
species[Perch]              -619.1751
species[Pike]              -1540.8243
species[Roach]              -329.3762
species[Bream]:length_cm      54.5500
species[Perch]:length_cm      38.9115
species[Pike]:length_cm       53.1949
species[Roach]:length_cm      23.3193
print(mdl_bream.params)
Intercept   -1035.3476
length_cm      54.5500
使用 Python 的 statsmodels 進行迴歸分析:中級

一起來練習吧!

使用 Python 的 statsmodels 進行迴歸分析:中級

Preparing Video For Download...