回歸到平均值

使用 Python 中的 statsmodels 進行回歸入門

Maarten Van den Broeck

Content Developer at DataCamp

概念

  • 反應值 = 擬合值 + 殘差
  • 「你解釋到的部分」+「你無法解釋的部分」
  • 殘差源自模型問題,亦源自基本隨機性
  • 極端情況常由隨機性造成
  • 「回歸到平均值」意指極端情況不會一直持續
使用 Python 中的 statsmodels 進行回歸入門

皮爾森的父子資料集

  • 1078 組父子配對
  • 高個爸爸會有高個兒子嗎?
father_height_cm son_height_cm
165.2 151.8
160.7 160.6
165.0 160.9
167.0 159.5
155.3 163.3
... ...
1 Adapted from https://www.rdocumentation.org/packages/UsingR/topics/father.son
使用 Python 中的 statsmodels 進行回歸入門

散佈圖

fig = plt.figure()
sns.scatterplot(x="father_height_cm",
                y="son_height_cm",
                data=father_son)
plt.axline(xy1=(150, 150),
           slope=1,
           linewidth=2,
           color="green")
plt.axis("equal")
plt.show()

兒子身高對父親身高的散佈圖,並有一條父子身高相同的參考線。父親越高,兒子也越高。

使用 Python 中的 statsmodels 進行回歸入門

加入回歸線

fig = plt.figure()

sns.regplot(x="father_height_cm",
            y="son_height_cm",
            data=father_son,
            ci = None, 
            line_kws={"color": "black"})

plt.axline(xy1 = (150, 150),
           slope=1,
           linewidth=2,
           color="green")

plt.axis("equal")
plt.show()

加上線性趨勢線的散佈圖。趨勢線比父子身高相同的參考線更平緩。

使用 Python 中的 statsmodels 進行回歸入門

執行回歸

mdl_son_vs_father = ols("son_height_cm ~ father_height_cm",
                        data = father_son).fit()
print(mdl_son_vs_father.params)
Intercept           86.071975
father_height_cm     0.514093
dtype: float64
使用 Python 中的 statsmodels 進行回歸入門

進行預測

really_tall_father = pd.DataFrame(
  {"father_height_cm": [190]})

mdl_son_vs_father.predict(
  really_tall_father)
183.7
really_short_father = pd.DataFrame(
  {"father_height_cm": [150]})

mdl_son_vs_father.predict(
  really_short_father)
163.2
使用 Python 中的 statsmodels 進行回歸入門

一起來練習吧!

使用 Python 中的 statsmodels 進行回歸入門

Preparing Video For Download...