Interactive Python · Machine learning

Generalized Linear Models, the game

Linear regression assumes a normal, unbounded outcome. GLMs handle yes/no answers, counts and skewed amounts too. Play through the components, families and link functions.

~14 minIntermediatePython · statsmodels5 missions330 XP
Mission 1+50 XP✓ Complete

Beyond the straight line

Ordinary linear regression assumes a continuous outcome with normally distributed errors and constant variance. Real outcomes often break those rules: yes/no answers, counts of events, or positive, skewed amounts like insurance claims.

A generalized linear model (GLM) keeps the familiar linear predictor but adds two pieces so it can model these outcomes properly. Flip the cards to meet the three components.

🃏The three components
0 / 3
🧠Quick check
+20 XP

Which GLM is exactly ordinary linear regression?

Mission 2+60 XP✓ Complete

Match the family

Choose the distribution (family) that fits the outcome:

OutcomeFamilyUsual link
Continuous, any valueNormalIdentity
Yes / no (0 or 1)BinomialLogit
Counts (0, 1, 2…)PoissonLog
Positive and right-skewedGammaLog (or inverse)
⚡Which family?
1 / 6
correct on the first try
Mission 3+65 XP✓ Complete

Link function lab

The linear predictor η can be any number from −∞ to +∞. The inverse link turns it into a valid mean for the outcome: any number for Normal, a probability between 0 and 1 for Binomial, a non-negative count for Poisson.

🔗Link function lab
+65 XP
IdentityNormal: any real number
LogitBinomial: probability 0–1
LogPoisson: count ≥ 0
identity μ = ηlogit⁻¹: μ = 1/(1+e^−η)log⁻¹: μ = e^η
  • ✓Make the logit give a probability of exactly 0.5+25 XP
  • ✓Find a point where the identity link goes negative but logit and log stay positive+20 XP
  • ✓Push the log link past an expected count of 20+20 XP
Mission 4+50 XP✓ Complete

Code it in Python

The article’s example predicts loan default (loan_status: 1 = default) on a Kaggle credit-risk dataset with a Binomial GLM, which is logistic regression.

Step 1Load, encode and split

import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix

df = pd.read_csv("credit_risk_dataset.csv").dropna()
df = pd.get_dummies(df, columns=["person_home_ownership", "loan_intent",
                                 "loan_grade", "cb_person_default_on_file"],
                    drop_first=True, dtype=int)
train_df, test_df = train_test_split(df, test_size=0.2, random_state=42)

Step 2Fit a Binomial GLM

features = 
formula = "loan_status ~ " + " + ".join(features)
model = smf.glm(formula=formula, data=train_df, family=sm.families.Binomial()).fit()
print(model.summary())

Step 3Predict and evaluate

test_df["pred_prob"] = model.predict(test_df)
test_df["pred"] = (test_df["pred_prob"] > 0.5).astype(int)

print("Accuracy:", accuracy_score(test_df["loan_status"], test_df["pred"]))
print(confusion_matrix(test_df["loan_status"], test_df["pred"]))
🧠Quick check
+25 XP

family=sm.families.Binomial() turns the GLM into…

🧠Quick check
+25 XP

What does pred_prob > 0.5 do?

Final boss+105 XP✓ Defeated

Defeat the GLM Boss 🐲

Seven questions, three hearts.

Question 1 / 7
❤️❤️❤️

💥 The boss winsReview the missions above, then try again.

You’re a GLM Master!

Share on LinkedIn
What’s next

Keep levelling up

You learned why plain linear regression struggles with binary, count and skewed outcomes, the three components of a GLM, how to match an outcome to its family, what link functions do, and how to fit a logistic GLM in statsmodels.

Lv 1 Rookie0 / 330 XP