tab <- table(smoke = bw$smoke, low = bw$low)
tab low
smoke 0 1
no 86 29
yes 44 30
Linear regression models a continuous response with normal errors. Many outcomes in medicine are events or counts. A baby has a low birthweight or a normal birthweight. A patient has 0, 1, 2 or 30 seizures in a month.
A generalised linear model (GLM) keeps the linear predictor of Chapter 14. It changes two parts: the distribution of the response, and the scale on which the predictors add. Bliss, Fisher, Berkson, Nelder and Wedderburn made these models between 1934 and 1972 (Chapter 1).
The birthwt data in the MASS package come from 189 births at Baystate Medical Center, Massachusetts, in 1986 (Hosmer and Lemeshow, Applied Logistic Regression, Wiley). Earlier chapters used the birthweight in grams as the response. Clinicians use a cut-off. The WHO defines low birthweight as less than 2500 g. These babies have a higher risk of death and disease in infancy. The variable low is 1 for such a baby and 0 for all other babies.
The variable lwt_kg is the weight of the mother at her last menstrual period. We changed its units from pounds to kilograms.
tab <- table(smoke = bw$smoke, low = bw$low)
tab low
smoke 0 1
no 86 29
yes 44 30
Does smoking in pregnancy increase the risk of a low-birthweight baby, after we adjust for the weight of the mother?
Of the 74 mothers who smoked, 30 had a low-birthweight baby. This is a risk of 40.5%. Of the 115 mothers who did not smoke, 29 had one, a risk of 25.2%. The risk ratio is 1.61.
The odds are the risk divided by its complement, \(p/(1 - p)\). The odds are 0.682 for smokers and 0.337 for non-smokers. The odds ratio is 2.02, so smokers have two times the odds of a low-birthweight baby. Logistic regression works on the scale of odds, and its coefficients are log odds ratios.
The table does not include the weight of the mother. On average, lighter mothers have lighter babies. If smokers and non-smokers have different weights, the table mixes the two effects. We must have a model with both predictors.
Weight is continuous, so we divide it into five groups of equal size. In each group, we calculate the proportion of low-birthweight babies.
grp <- bw |>
mutate(band = ntile(lwt_kg, 5)) |>
group_by(band) |>
summarise(lwt_kg = mean(lwt_kg), n = n(), p = mean(low)) |>
mutate(log_odds = log(p / (1 - p)))
grp# A tibble: 5 × 5
band lwt_kg n p log_odds
<int> <dbl> <int> <dbl> <dbl>
1 1 44.2 38 0.526 0.105
2 2 51.3 38 0.237 -1.17
3 3 55.8 38 0.237 -1.17
4 4 62.1 38 0.342 -0.654
5 5 81.6 37 0.216 -1.29
Figure 20.1 shows the five proportions on two scales. On the left, we fit a straight line to the 0/1 outcomes by least squares. This line goes below 0 for heavy mothers. At 140 kg, it predicts a probability of -0.149, which is not possible. The S-shaped logistic curve stays between 0 and 1, and at 140 kg it predicts 0.034.
On the right, we change each proportion to its log odds. With 37 or 38 births in a group, the points scatter, but they decrease as the weight increases. On this scale, a straight line has no limits, and on the left it becomes the S-shaped curve. Bliss had this idea in 1934: change the proportion to a different scale, then fit a straight line.
grid <- tibble(lwt_kg = seq(35, 150, length.out = 200)) |>
mutate(linear = predict(lin, pick(lwt_kg)),
logistic = predict(logi, pick(lwt_kg), type = "response"),
log_odds = predict(logi, pick(lwt_kg)))
p_prob <- ggplot(grp, aes(lwt_kg, p)) +
geom_hline(yintercept = 0, colour = "grey80") +
geom_line(data = grid, aes(y = linear), colour = "grey40", linetype = "dashed") +
geom_line(data = grid, aes(y = logistic), colour = "firebrick", linewidth = 1) +
geom_point(aes(size = n), colour = "steelblue") +
scale_size_area(max_size = 4, guide = "none") +
labs(x = "mother's weight (kg)", y = "proportion low birthweight", title = "Probability")
p_logit <- ggplot(grp, aes(lwt_kg, log_odds)) +
geom_line(data = grid, colour = "firebrick", linewidth = 1) +
geom_point(aes(size = n), colour = "steelblue") +
scale_size_area(max_size = 4, guide = "none") +
labs(x = "mother's weight (kg)", y = "log odds", title = "Log odds")
p_prob + p_logit
Nelder and Wedderburn (1972) wrote all models of this type with three parts.
| Response | Family | Usual link | R |
|---|---|---|---|
| Continuous, normal errors | gaussian | identity, \(\mu\) | glm(y ~ x), same as lm() |
| 0/1, or \(k\) out of \(n\) | binomial | logit, \(\ln\{\mu/(1-\mu)\}\) | glm(y ~ x, family = binomial) |
| Count | poisson | log, \(\ln \mu\) | glm(y ~ x, family = poisson) |
Linear regression is the first row. Its link is the identity, and its errors are normal.
For a 0/1 outcome, \(\mu_i\) is the probability \(p_i\) that \(y_i = 1\). The logistic model is
\[ \ln\frac{p_i}{1 - p_i} = \beta_0 + \beta_1\,\text{smoke}_i + \beta_2\,\text{weight}_i . \]
Each coefficient is a change in log odds. The exponential \(e^{\beta_1}\) is the odds ratio for smokers against non-smokers at the same weight. The model assumes that the outcomes are independent and that the log odds are linear in the predictors. You do not check for a normal distribution or a constant variance. The variance of a 0/1 outcome is \(p_i(1 - p_i)\), and \(p_i\) comes from the model.
Least squares does not apply to 0/1 outcomes. Maximum likelihood chooses the \(\beta\) that give the highest probability to the observed outcomes. The log-likelihood is
\[ \ell(\beta) = \sum_i \big[\,y_i \ln p_i + (1 - y_i)\ln(1 - p_i)\,\big]. \]
There is no formula for the maximum. In 1935, Fisher found it by repetition for Bliss’s beetles, and glm() uses the same method today. The method is iteratively reweighted least squares (IRLS). It has four steps:
X <- model.matrix(~ smoke + lwt_kg, data = bw)
y <- bw$low
beta <- rep(0, ncol(X))
steps <- list()
for (it in 1:6) {
eta <- drop(X %*% beta)
p <- plogis(eta) # inverse logit
w <- p * (1 - p)
z <- eta + (y - p) / w # working response
beta <- coef(lm(z ~ X - 1, weights = w))
steps[[it]] <- setNames(beta, colnames(X))
}
bind_rows(steps, .id = "iteration")# A tibble: 6 × 4
iteration `(Intercept)` smokeyes lwt_kg
<chr> <dbl> <dbl> <dbl>
1 1 0.304 0.586 -0.0218
2 2 0.591 0.674 -0.0287
3 3 0.622 0.677 -0.0294
4 4 0.622 0.677 -0.0294
5 5 0.622 0.677 -0.0294
6 6 0.622 0.677 -0.0294
fit <- glm(low ~ smoke + lwt_kg, family = binomial, data = bw)
coef(fit)(Intercept) smokeyes lwt_kg
0.62199682 0.67667325 -0.02937462
After four steps, the IRLS estimates do not change. They agree with glm() to all the printed digits.
summary(fit)
Call:
glm(formula = low ~ smoke + lwt_kg, family = binomial, data = bw)
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.62200 0.79592 0.781 0.4345
smokeyes 0.67667 0.32470 2.084 0.0372 *
lwt_kg -0.02937 0.01342 -2.188 0.0287 *
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 234.67 on 188 degrees of freedom
Residual deviance: 224.34 on 186 degrees of freedom
AIC: 230.34
Number of Fisher Scoring iterations: 4
cf <- coef(summary(fit))
ci_log <- confint(fit)
ci <- exp(ci_log)
or_smoke <- exp(coef(fit)["smokeyes"])
or_10kg <- exp(10 * coef(fit)["lwt_kg"])
ci_10kg <- exp(10 * ci_log["lwt_kg", ])Estimate: the coefficient on the log-odds scale. For smokeyes it is 0.677. The odds ratio is \(e^{0.677} = 1.97\). At the same weight, smokers have 1.97 times the odds of a low-birthweight baby. The unadjusted odds ratio from the table was 2.02, so the weight of the mother changes the estimate by a small amount.lwt_kg row of Estimate: -0.0294 per kg. For 10 kg more, the odds ratio is 0.75. Heavier mothers have lower odds.Std. Error: the standard error, from the curvature of the log-likelihood at its maximum.z value: the estimate divided by its standard error. The value of \(p\) sets the binomial variance, so the model does not estimate a \(\sigma\). For this reason R calls the ratio z and compares it with the normal curve, as in the large-sample z-test of Chapter 4. This is the Wald test.Pr(>|z|): 0.0372 for smoking and 0.0287 for weight. Both are below 0.05.Dispersion parameter for binomial family taken to be 1: the variance is \(p(1 - p)\), with no extra factor.Null deviance: 234.67 on 188 degrees of freedom (df). It measures the distance between the data and a model with only an intercept.Residual deviance: 224.34 on 186 df. For 0/1 data, the deviance is \(-2\) times the log-likelihood. It has the same function as the residual sum of squares.AIC: the deviance plus 2 for each coefficient. It compares models that you fit to the same data. A smaller AIC shows a better model.Number of Fisher Scoring iterations: the number of IRLS steps.The profile likelihood gives confidence intervals for the odds ratios:
exp(cbind(OR = coef(fit), ci_log)) OR 2.5 % 97.5 %
(Intercept) 1.8626437 0.4134732 9.5328864
smokeyes 1.9673220 1.0417154 3.7335464
lwt_kg 0.9710526 0.9441368 0.9954935
The 95% interval for the smoking odds ratio is 1.04 to 3.73. It does not contain 1. For each 10 kg increase in the weight of the mother, the interval is 0.56 to 0.96.
The F-test compared two nested linear models by their residual sums of squares (Chapter 15). For a GLM, we compare the deviances of the two models. If the smaller model is true, the decrease in deviance follows a chi-square distribution. Its df is the number of extra coefficients in the larger model.
no_smoke <- update(fit, . ~ . - smoke)
lrt <- anova(no_smoke, fit, test = "Chisq")
lrtAnalysis of Deviance Table
Model 1: low ~ lwt_kg
Model 2: low ~ smoke + lwt_kg
Resid. Df Resid. Dev Df Deviance Pr(>Chi)
1 187 228.69
2 186 224.34 1 4.35 0.03701 *
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Smoking decreases the deviance by 4.35 on 1 df, with p = 0.037. The Wald p-value was 0.0372. The two tests agree here. With small samples or large effects, the two tests can disagree. Then the likelihood ratio test is more accurate.
pred <- expand_grid(lwt_kg = seq(35, 115, length.out = 200), smoke = factor(c("no", "yes"))) |>
mutate(p = predict(fit, pick(everything()), type = "response"))
cols <- c(no = "steelblue", yes = "firebrick")
ggplot(pred, aes(lwt_kg, p, colour = smoke)) +
geom_line(linewidth = 1) +
geom_rug(data = filter(bw, low == 1), aes(lwt_kg, low), sides = "t", alpha = 0.5, inherit.aes = FALSE) +
geom_rug(data = filter(bw, low == 0), aes(lwt_kg, low), sides = "b", alpha = 0.5, inherit.aes = FALSE) +
scale_colour_manual(values = cols) +
labs(x = "mother's weight (kg)", y = "P(low birthweight)", colour = "smoked")
The epil data in MASS come from a clinical trial of the anti-epileptic drug progabide. Thall and Vail used these data in Biometrics (1990). Before randomisation, the 59 patients with epilepsy recorded their seizures for 8 weeks (base). Then the patients received progabide or a placebo. They recorded their seizures for four more periods of 2 weeks. We add the four periods to get one count of seizures in 8 weeks for each patient.
Does progabide decrease the number of seizures, after we adjust for the baseline count of each patient?
A count cannot be negative, and its spread increases with its mean. The Poisson GLM uses a log link:
\[ \ln \mu_i = \beta_0 + \beta_1\,\text{progabide}_i + \beta_2 \ln(\text{base}_i) + \beta_3 \ln(\text{age}_i). \]
Each \(e^{\beta}\) is a rate ratio. We use the logs of the baseline count and of age, so that their effects also multiply.
pois <- glm(seizures ~ trt + log(base) + log(age), family = poisson, data = ep)
pc <- coef(summary(pois))
pc Estimate Std. Error z value Pr(>|z|)
(Intercept) -2.72002314 0.42664526 -6.3753741 1.825169e-10
trtprogabide -0.01759081 0.04817951 -0.3651098 7.150294e-01
log(base) 1.22521697 0.03252287 37.6724692 1.402824e-310
log(age) 0.58777978 0.10992308 5.3471916 8.932944e-08
The rate ratio for progabide is 0.983, with p = 0.715. The Poisson model finds no effect of the drug. It gives age a p-value of 8.93e-08, and this p-value is too small.
In a Poisson distribution, the variance is equal to the mean. A binomial outcome has the variance \(p(1 - p)\). The GLM uses these variances to calculate the standard errors. Real counts have a larger variance when patients differ in ways that the predictors do not measure. This condition is overdispersion. Section 4 of the GLM playground shows its effect on the standard errors.
ep_sum# A tibble: 2 × 4
trt n mean var
<fct> <int> <dbl> <dbl>
1 placebo 28 34.4 1234.
2 progabide 31 31.8 2903.
c(deviance = deviance(pois), df = df.residual(pois), ratio = deviance(pois) / df.residual(pois)) deviance df ratio
556.39225 55.00000 10.11622
In the placebo group, the mean count is 34.4 and the variance is 1234. A residual deviance near its df shows a good fit. Here the deviance is 556 on 55 df, 10 times larger than its df. So the Poisson standard errors are too small.
Two models correct this. The quasi-Poisson model keeps the coefficients. It multiplies the variance by an estimated dispersion factor \(\phi\) (Wedderburn’s quasi-likelihood, Chapter 1). R estimates \(\phi\) from the data, so R shows t values. The negative binomial model, MASS::glm.nb(), adds a parameter so that the variance increases faster than the mean.
quasi <- update(pois, family = quasipoisson)
negbin <- glm.nb(formula(pois), data = ep)
p_age <- c(poisson = pc["log(age)", 4],
quasipoisson = coef(summary(quasi))["log(age)", 4],
negbin = coef(summary(negbin))["log(age)", 4])
p_age poisson quasipoisson negbin
8.932944e-08 1.135103e-01 3.374329e-01
coef(summary(negbin))["trtprogabide", ] # negative binomial: progabide Estimate Std. Error z value Pr(>|z|)
-0.26274433 0.14939411 -1.75873286 0.07862289
The estimated dispersion is \(\hat\phi =\) 11.1, so the quasi-Poisson standard errors are \(\sqrt{\hat\phi} =\) 3.3 times the Poisson standard errors. The p-value for age increases from 8.9e-08 to 0.11, and to 0.34 with the negative binomial model. The negative binomial model gives a rate ratio for progabide of 0.77, with p = 0.079. When we include the overdispersion, the data neither confirm nor exclude an effect of the drug.
Before you use the p-values of a Poisson GLM, or of a binomial GLM with grouped counts (\(k\) out of \(n\)), compare the residual deviance with its df. For 0/1 outcomes, as in the birthweight model, the deviance does not follow a chi-square distribution, and this check does not apply.
The links and the variance functions of a GLM follow from one form of distribution. The GLM playground of the course lets you change the link and the variance assumption on real data.
The normal, binomial and Poisson distributions share one form. A distribution is in the exponential family if we can write its probability (or density) as
\[ f(y;\, \theta, \phi) = \exp\left\{ \frac{y\,\theta - b(\theta)}{\phi} + c(y, \phi) \right\}. \]
Here \(\theta\) is the natural parameter, \(b(\theta)\) is the cumulant function and \(\phi\) is the dispersion. The term \(c(y, \phi)\) does not contain \(\theta\). To put a distribution in this form, take the log of \(f\) and find the term that multiplies \(y\). That term is \(\theta\).
For the Poisson distribution with mean \(\mu\),
\[ \log f(y) = y \log \mu - \mu - \log y!\,. \]
The term that multiplies \(y\) is \(\log \mu\), so \(\theta = \log \mu\). Then \(\mu = e^{\theta}\), so \(b(\theta) = e^{\theta}\), \(\phi = 1\) and \(c(y, \phi) = -\log y!\).
For a 0/1 outcome with \(P(Y = 1) = \mu\),
\[ \log f(y) = y \log \mu + (1 - y) \log(1 - \mu) = y \log\frac{\mu}{1 - \mu} + \log(1 - \mu). \]
The term that multiplies \(y\) is the logit, so \(\theta = \log\{\mu/(1 - \mu)\}\). We solve for \(\mu = e^{\theta}/(1 + e^{\theta})\). Then \(-\log(1 - \mu) = \log(1 + e^{\theta})\), so \(b(\theta) = \log(1 + e^{\theta})\) and \(\phi = 1\).
For the normal distribution with mean \(\mu\) and variance \(\sigma^2\),
\[ \log f(y) = \frac{y\mu - \mu^2/2}{\sigma^2} - \frac{y^2}{2\sigma^2} - \tfrac{1}{2}\log(2\pi\sigma^2). \]
So \(\theta = \mu\), \(b(\theta) = \theta^2/2\) and \(\phi = \sigma^2\). The normal distribution is the only one of the three with a free dispersion.
The log-likelihood of one observation is \(\ell(\theta) = \{y\theta - b(\theta)\}/\phi + c(y, \phi)\). Its derivative with respect to \(\theta\) is the score:
\[ \frac{\partial \ell}{\partial \theta} = \frac{y - b'(\theta)}{\phi}, \qquad \frac{\partial^2 \ell}{\partial \theta^2} = -\frac{b''(\theta)}{\phi}. \]
Two identities hold for any regular likelihood. The total probability \(\int f\,dy = 1\) for every \(\theta\). We differentiate both sides with respect to \(\theta\), once and then twice:
\[ E\!\left[\frac{\partial \ell}{\partial \theta}\right] = 0, \qquad E\!\left[\frac{\partial^2 \ell}{\partial \theta^2}\right] + E\!\left[\left(\frac{\partial \ell}{\partial \theta}\right)^2\right] = 0. \]
The first identity gives \(E[Y] - b'(\theta) = 0\), so \(\mu = E[Y] = b'(\theta)\). In the second identity, \(E[(\partial \ell/\partial \theta)^2] = \text{Var}(Y)/\phi^2\). So \(\text{Var}(Y) = \phi\, b''(\theta)\).
For the Poisson, \(b(\theta) = e^{\theta}\), and both derivatives equal \(e^{\theta} = \mu\). This is why the Poisson variance is equal to its mean. For a 0/1 outcome, \(b'(\theta) = e^{\theta}/(1 + e^{\theta}) = \mu\) and \(b''(\theta) = \mu(1 - \mu)\). We write \(b''(\theta)\) as a function of \(\mu\) and call it the variance function \(V(\mu)\). Then \(\text{Var}(Y) = \phi\, V(\mu)\).
| Family | \(\theta\) | \(b(\theta)\) | \(V(\mu)\) | \(\phi\) | Canonical link | R |
|---|---|---|---|---|---|---|
| Normal | \(\mu\) | \(\theta^2/2\) | \(1\) | \(\sigma^2\) | identity | gaussian |
| Poisson | \(\log \mu\) | \(e^{\theta}\) | \(\mu\) | \(1\) | log | poisson |
| Bernoulli | \(\log\{\mu/(1-\mu)\}\) | \(\log(1 + e^{\theta})\) | \(\mu(1 - \mu)\) | \(1\) | logit | binomial |
| Gamma | \(-1/\mu\) | \(-\log(-\theta)\) | \(\mu^2\) | \(1/\text{shape}\) | inverse | Gamma |
R stores \(V(\mu)\) and the link in each family object:
poisson()$variance(c(0.5, 2, 10)) # V(mu) = mu[1] 0.5 2.0 10.0
binomial()$variance(c(0.1, 0.5, 0.9)) # V(mu) = mu (1 - mu)[1] 0.09 0.25 0.09
binomial()$linkfun(c(0.1, 0.5, 0.9)) # logit(mu) = theta[1] -2.197225 0.000000 2.197225
The canonical link sets the linear predictor equal to the natural parameter: \(g(\mu) = \theta\). From the table, the canonical links are the identity, the log and the logit. These are the default links of gaussian(), poisson() and binomial().
With the canonical link, \(\theta_i = \mathbf{x}_i^\top \beta\). The log-likelihood of the full sample is
\[ \ell(\beta) = \frac{1}{\phi} \sum_i \left\{ y_i\, \mathbf{x}_i^\top \beta - b(\mathbf{x}_i^\top \beta) \right\} + \text{const}. \]
We differentiate with respect to \(\beta\). The derivative of \(b(\mathbf{x}_i^\top \beta)\) is \(b'(\theta_i)\,\mathbf{x}_i = \mu_i\,\mathbf{x}_i\). The maximum likelihood estimate solves the score equations
\[ \frac{\partial \ell}{\partial \beta} = \frac{1}{\phi}\, X^\top (y - \mu) = 0 . \]
Least squares solves \(X^\top (y - X\beta) = 0\). The score equations have the same form, with \(\mu\) in place of \(X\beta\). The second derivative is \(-X^\top W X/\phi\), with \(W = \text{diag}\{V(\mu_i)\}\). This matrix is negative definite when \(X\) has full rank, so the log-likelihood has one maximum.
We check the score equations on the birthweight model:
X <- model.matrix(fit)
drop(t(X) %*% (bw$low - fitted(fit))) # X^T (y - mu) at the estimate (Intercept) smokeyes lwt_kg
-4.509393e-12 3.386180e-14 -2.696153e-10
c(observed = sum(bw$low), fitted = sum(fitted(fit)))observed fitted
59 59
All three sums are 0 to the precision of the computer. The intercept row says \(\sum_i (y_i - \mu_i) = 0\). So with the canonical link and an intercept, the fitted values add up to the observed total. Here both totals are 59 low-birthweight babies.
For any link, the IRLS weight is \(w_i = 1/\{V(\mu_i)\, g'(\mu_i)^2\}\). For the canonical link, \(g'(\mu) = 1/V(\mu)\), so the weight becomes \(w_i = V(\mu_i)\). For the logit, the weight is \(\mu_i(1 - \mu_i)\). This is the weight p * (1 - p) in the IRLS loop of the formal solution above.
Bliss’s probit link (Chapter 1) is \(g(\mu) = \Phi^{-1}(\mu)\). It is not canonical for the binomial, because \(\Phi^{-1}(\mu) \ne \theta\). glm() fits it with the same IRLS algorithm and the general weights. The score equations then have a different form, and the fitted total no longer equals the observed total.
probit_fit <- update(fit, family = binomial(link = "probit"))
c(observed = sum(bw$low), logit = sum(fitted(fit)), probit = sum(fitted(probit_fit)))observed logit probit
59.00000 59.00000 58.94511
c(AIC_logit = AIC(fit), AIC_probit = AIC(probit_fit)) AIC_logit AIC_probit
230.3407 230.2236
The probit fit gives a total of 58.95 against 59 observed. The two links fit these data almost equally well: the AIC values are 230.3 and 230.2. Both links give valid models, and the canonical link gives simpler score equations and a log-likelihood with one maximum.
glm(). The deviance replaces the residual sum of squares, and the likelihood ratio test replaces the F-test.