回归到均值

使用 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 改编自 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 进行回归入门

Passons à la pratique !

使用 Python 中的 statsmodels 进行回归入门

Preparing Video For Download...