ตัวแปรอธิบายแบบกลุ่ม

การถดถอยเบื้องต้นด้วย statsmodels ใน Python

Maarten Van den Broeck

Content Developer at DataCamp

ชุดข้อมูลปลา

  • แต่ละแถวแทนปลาหนึ่งตัว
  • ชุดข้อมูลมี 128 แถว
  • มีปลา 4 สายพันธุ์:
    • Common Bream
    • European Perch
    • Northern Pike
    • Common Roach
species mass_g
Bream 242.0
Perch 5.9
Pike 200.0
Roach 40.0
... ...
การถดถอยเบื้องต้นด้วย statsmodels ใน Python

การแสดงผลตัวแปรตัวเลข 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

การถดถอยเบื้องต้นด้วย statsmodels ใน Python

สถิติสรุป: ค่าเฉลี่ยมวลตามสายพันธุ์

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
การถดถอยเบื้องต้นด้วย statsmodels ใน Python

การถดถอยเชิงเส้น

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
การถดถอยเบื้องต้นด้วย statsmodels ใน Python

โมเดลแบบมีหรือไม่มี intercept

จากสไลด์ก่อนหน้า โมเดลที่มี 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

สัมประสิทธิ์เป็นค่าสัมพัทธ์กับ intercept: $617.83 - 235.59 = 382.24!$

โมเดลที่ไม่มี 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

ในกรณีที่มีตัวแปรกลุ่มเพียงตัวเดียว สัมประสิทธิ์คือค่าเฉลี่ย

การถดถอยเบื้องต้นด้วย statsmodels ใน Python

มาฝึกกันเถอะ!

การถดถอยเบื้องต้นด้วย statsmodels ใน Python

Preparing Video For Download...