類別解釋變數

使用 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

當只有 1 個類別變數時, 係數就是各組的平均數。

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

一起來練習吧!

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

Preparing Video For Download...