Skip to main content

20  Generalised linear models: logistic and Poisson regression

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

20.1 The problem

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?

20.2 Intuitive solution

20.2.1 Count

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.

20.2.2 Draw

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.

Show code
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
Figure 20.1: Proportion of low-birthweight babies in five groups of mother’s weight (MASS::birthwt), on the probability scale (left) and the log-odds scale (right). On the probability scale, the least-squares line (grey, dashed) goes below 0, and the logistic curve (red) stays between 0 and 1. On the log-odds scale, the model is a straight line.

20.3 Formal solution

20.3.1 Three parts of a GLM

Nelder and Wedderburn (1972) wrote all models of this type with three parts.

  1. The response \(y_i\) has a distribution from the exponential family, with mean \(\mu_i\).
  2. The predictors combine in a linear predictor, \(\eta_i = \beta_0 + \beta_1 x_{i1} + \dots + \beta_p x_{ip}\).
  3. A link function \(g\) connects the two: \(g(\mu_i) = \eta_i\).
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.

20.3.2 Logistic regression

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.

20.3.3 Fit by maximum likelihood

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:

  1. Start with an estimate of \(\beta\), for example all zeros.
  2. Calculate the “working response” \(z_i = \eta_i + (y_i - p_i)/w_i\) and the weight \(w_i = p_i(1 - p_i)\).
  3. Fit a weighted least-squares regression of \(z\) on the predictors.
  4. Do steps 2 and 3 again with the new \(\beta\). Stop when \(\beta\) does not change.
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.

20.3.4 Read the output

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
Show code
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.

20.3.5 The likelihood ratio test

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")
lrt
Analysis 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.

Show code
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")
Figure 20.2: Fitted probability of a low-birthweight baby against mother’s weight, for smokers (red) and non-smokers (blue). The ticks at the top (y = 1) and bottom (y = 0) are the individual births. The two curves are parallel on the log-odds scale and differ by the log odds ratio for smoking.

20.4 Poisson regression for counts

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.

20.5 Overdispersion

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.

20.7 Summary

  • A GLM has three parts: a distribution for the response, a linear predictor and a link function. Linear regression is the GLM with a normal distribution and the identity link.
  • Logistic regression models the log odds of a 0/1 outcome. The exponential of each coefficient is an odds ratio.
  • Maximum likelihood fits a GLM by iteratively reweighted least squares, in the R function glm(). The deviance replaces the residual sum of squares, and the likelihood ratio test replaces the F-test.
  • Poisson regression models counts with a log link. A deviance much larger than its df shows overdispersion, and a quasi-Poisson or negative binomial model then gives correct standard errors.