Statistical modeling with Python · Lesson 11 of 16
GLMs explained: family and link function
What a generalized linear model is: a family for the outcome plus a link function. See that linear regression is a Gaussian GLM, and when to use each family.
Linear regression assumes the outcome can be any number and scatters around the line in a bell shape. Many outcomes are not like that: passed or failed is 0 or 1; number of doctor visits is a whole number that cannot go below 0. A generalized linear model (GLM) keeps the easy part of regression (a weighted sum of predictors) and adds two choices to fit such outcomes.
- Family: the probability distribution of the outcome. Gaussian (normal) for measurements, Binomial for yes/no, Poisson for counts, Gamma for positive skewed amounts such as costs.
- Link function: how the weighted sum connects to the average outcome. The sum
b0 + b1·x1 + …can be any number, so the link squeezes it into the allowed range: the logit link keeps probabilities between 0 and 1, the log link keeps counts above 0.
In statsmodels every GLM is fitted the same way: smf.glm(formula, data, family=...). Each family comes with its usual (canonical) link.
import statsmodels.api as sm
for fam in [sm.families.Gaussian(), sm.families.Binomial(),
sm.families.Poisson(), sm.families.Gamma()]:
print(f"{type(fam).__name__:<9} default link: {type(fam.link).__name__}")Gaussian default link: Identity Binomial default link: Logit Poisson default link: Log Gamma default link: InversePower
The table to remember:
- Measurement (score, weight, price) →
Gaussian, identity link → this is ordinary linear regression. - Yes / no, 0 / 1 →
Binomial, logit link → logistic regression (Logistic regression in Python (GLM)). - Counts (0, 1, 2, …) →
Poisson, log link → Poisson regression (Poisson regression for count data in Python). - Positive, right-skewed amounts (insurance claims, waiting times) →
Gamma. Its default link is the inverse (InversePower), but analysts usually choose the log link:sm.families.Gamma(link=sm.families.links.Log()).
Linear regression is a Gaussian GLM
Fit the same model with ols and with glm and a Gaussian family: the coefficients are identical. The GLM reports the deviance instead of the sum of squared residuals; for the Gaussian family they are the same number.
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("students.csv")
ols = smf.ols("score ~ hours + absences", data=df).fit()
glm = smf.glm("score ~ hours + absences", data=df,
family=sm.families.Gaussian()).fit()
print(pd.DataFrame({"ols": ols.params, "glm": glm.params}).round(4))
print(f"sum of squared residuals: {ols.ssr:.1f}")
print(f"GLM deviance: {glm.deviance:.1f}")ols glm Intercept 38.8443 38.8443 hours 3.5416 3.5416 absences -2.2179 -2.2179 sum of squared residuals: 21898.9 GLM deviance: 21898.9
What a link function does
The logit link is log(p / (1 − p)), the log of the odds. It turns a probability between 0 and 1 into any number; its inverse, the logistic function 1 / (1 + e^(−z)), turns any number back into a probability. That is why a logistic model can never predict 120% or −5%.
import numpy as np
p = np.array([0.1, 0.5, 0.8, 0.99])
odds = p / (1 - p)
z = np.log(odds) # the logit link
print("odds: ", odds.round(3))
print("logit:", z.round(3))
back = 1 / (1 + np.exp(-z)) # the inverse link
print("back: ", back.round(3))odds: [ 0.111 1. 4. 99. ] logit: [-2.197 0. 1.386 4.595] back: [0.1 0.5 0.8 0.99]
The log link does the same for counts: the model works with log(mean), which can be any number, and exp() turns it back into a positive mean. Because exp(a + b) = exp(a) × exp(b), effects in log-link models multiply instead of add, which you will use to read Poisson coefficients as rate ratios.
llf) and AIC, which you will use to compare models.✎ Exercise
Fit score ~ hours with smf.glm and a Gaussian family, and print the coefficients (3 decimals) and the deviance (1 decimal).
Hint: smf.glm("score ~ hours", data=df, family=sm.families.Gaussian()).fit()
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("students.csv")
# your code here
Expected output:
Intercept 29.936 hours 3.512 dtype: float64 deviance: 25451.9
Show a solution
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("students.csv")
glm = smf.glm("score ~ hours", data=df, family=sm.families.Gaussian()).fit()
print(glm.params.round(3))
print(f"deviance: {glm.deviance:.1f}")Intercept 29.936 hours 3.512 dtype: float64 deviance: 25451.9
Check yourself
1. Which family fits an outcome that is 1 if a customer bought and 0 otherwise?
Yes/no outcomes follow a Binomial (Bernoulli) distribution: that GLM is logistic regression.
2. Why does a logistic model use the logit link?
The linear part can be any number; the inverse of the logit maps it into 0 to 1.
3. A GLM with a Gaussian family and identity link is…
Same coefficients, same fit: OLS is a special case of the GLM.