Categorische verklarende variabelen

Introductie tot regressie met statsmodels in Python

Maarten Van den Broeck

Content Developer at DataCamp

Visdataset

  • Elke rij is één vis.
  • De dataset heeft 128 rijen.
  • Er zijn 4 soorten:
    • Brasem
    • Baars
    • Snoek
    • Voorn
species mass_g
Bream 242.0
Perch 5.9
Pike 200.0
Roach 40.0
... ...
Introductie tot regressie met statsmodels in Python

Visualiseren: 1 numeriek en 1 categorisch

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()

Een gefacetteerd histogram van aantallen vissen versus hun gewicht. Elk paneel toont een soort: brasem, baars, snoek of voorn.

Introductie tot regressie met statsmodels in Python

Samenvatting: gemiddelde massa per soort

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
Introductie tot regressie met statsmodels in Python

Lineaire regressie

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
Introductie tot regressie met statsmodels in Python

Model met of zonder intercept

Van de vorige slide: model met intercept

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

De coëfficiënten zijn relatief t.o.v. het intercept: $617.83 - 235.59 = 382.24!$

Model zonder intercept

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

Bij één categorische variabele zijn coëfficiënten de gemiddelden.

Introductie tot regressie met statsmodels in Python

Laten we oefenen!

Introductie tot regressie met statsmodels in Python

Preparing Video For Download...