分类型自变量

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

Maarten Van den Broeck

Content Developer at DataCamp

鱼类数据集

  • 每行代表一条鱼。
  • 数据集共有 128 行。
  • 有 4 种鱼:
    • 鲤科鲤鱼(Bream)
    • 欧洲河鲈(Perch)
    • 北方狗鱼(Pike)
    • 普通鲫鱼(Roach)
species mass_g
Bream 242.0
Perch 5.9
Pike 200.0
Roach 40.0
... ...
使用 Python 中的 statsmodels 进行回归入门

可视化:1 个数值 + 1 个分类变量

import matplotlib.pyplot as plt
import seaborn as sns

sns.displot(data=fish,
            x="mass_g",
            col="species",
            col_wrap=2,
            bins=9)

plt.show()

按物种分面的鱼体重直方图。每个面板对应一种:bream、perch、pike、roach。

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

汇总统计:各物种平均质量

summary_stats = fish.groupby("species")["mass_g"].mean()
print(summary_stats)
species
Bream    617.828571
Perch    382.239286
Pike     718.705882
Roach    152.050000
Name: mass_g, dtype: float64
使用 Python 中的 statsmodels 进行回归入门

线性回归

from statsmodels.formula.api import ols 
mdl_mass_vs_species = ols("mass_g ~ species", data=fish).fit()

print(mdl_mass_vs_species.params)
Intercept           617.828571
species[T.Perch]   -235.589286
species[T.Pike]     100.877311
species[T.Roach]   -465.778571
使用 Python 中的 statsmodels 进行回归入门

含/不含截距的模型

上一页的含截距模型

mdl_mass_vs_species = ols(
  "mass_g ~ species", data=fish).fit()

print(mdl_mass_vs_species.params)
Intercept           617.828571
species[T.Perch]   -235.589286
species[T.Pike]     100.877311
species[T.Roach]   -465.778571

系数相对于截距: $617.83 - 235.59 = 382.24!$

无截距模型

mdl_mass_vs_species = ols(
  "mass_g ~ species + 0", data=fish).fit()

print(mdl_mass_vs_species.params)
species[Bream]    617.828571
species[Perch]    382.239286
species[Pike]     718.705882
species[Roach]    152.050000

单个分类变量时, 系数就是各组均值。

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

Passons à la pratique !

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

Preparing Video For Download...