Skip to main content

9. GLMs in R continued

Packages

library(ggplot2)
library(effects)
library(cowplot)
library(MASS)
theme_set(theme_light())

Bird count data

We use data from a study on how abiotic factors affect species richness on the Indian subcontinent (Carroll, 1998; cited in Piegorsch and Bailer, 2005). The response Y is the number of bird species in 61 regions of 1 km². The predictor relief describes the altitudinal relief, the difference between the highest and lowest elevation in a region. It is log-transformed and shifted to positive values, \(\text{relief} = \log(\text{altitudinal relief}) + 1.75\), and takes four values, the mean of each of four relief classes:

dat <- read.table("Data/bird_counts.txt", sep = ";", header = TRUE)

ggplot(dat, aes(x = relief, y = Y)) +
  geom_point()

The number of bird species increases with relief, most strongly between the two highest relief classes. The spread also grows with relief: in the lowest class, the counts range from about 100 to 200, in the highest from about 150 to 550. Count models with a log link assume that the mean increases exponentially with the predictor, i.e. linearly on the log scale. We therefore also plot the counts on a log-scaled y-axis:

ggplot(dat, aes(x = relief, y = Y)) + 
  scale_y_continuous(trans='log') +
  geom_point()

Poisson regression

Model

The number of species can only take non-negative whole numbers (0, 1, 2, …), so we need a discrete response distribution. For counts, the Poisson distribution is the standard choice. Its mean must be positive, so we model it with a log link. The expected number of species is then always positive:

\[\text{E}[y] = e^{\beta_0 + \beta_1 x}\]

where \(x\) is relief. This gives the model:

\[y \sim \text{Poisson}(e^{\beta_0 + \beta_1 x})\]

Fitting the model

We fit the model with glm(), specifying the Poisson distribution and the log link with family = poisson(link = "log"). The log link is the default for the Poisson family, so family = poisson gives the same model:

bird.poisson <- glm(Y ~ relief, data = dat, family = poisson(link = "log"))
summary(bird.poisson)

Call:
glm(formula = Y ~ relief, family = poisson(link = "log"), data = dat)

Coefficients:
            Estimate Std. Error z value Pr(>|z|)    
(Intercept) 4.665888   0.021577  216.24   <2e-16 ***
relief      0.339559   0.008382   40.51   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for poisson family taken to be 1)

    Null deviance: 2921.1  on 60  degrees of freedom
Residual deviance: 1299.6  on 59  degrees of freedom
AIC: 1739.7

Number of Fisher Scoring iterations: 4

The coefficients are on the link (log) scale. We interpret them further below. The effect of relief is significant (p < 0.001), and adding it reduces the deviance from about 2900 (null deviance, intercept only) to about 1300 (residual deviance). The output also states that the dispersion parameter is taken to be 1. Whether this assumption holds is the topic of the next section.

Overdispersion

Dispersion

Dispersion describes how much the observed variance differs from the variance the model expects. In a Poisson distribution, the variance equals the mean: if the expected count is 150, the variance is also 150. The dispersion of a Poisson model is therefore fixed at 1. If the observed variance is larger than the mean, the data are overdispersed. If it is smaller, they are underdispersed. Overdispersion is common in ecological count data.

In our data, the variance is much larger than the mean in every relief class. In the lowest class, for example, the mean is about 155 species, but the variance is about 680.

Checking for overdispersion

The ratio of the residual deviance to the residual degrees of freedom gives a rough estimate of the dispersion. It should be close to 1. Values much larger than 1 (> 2) indicate overdispersion, values below about 0.6 underdispersion:

## Residual deviance: 1299.6  on 59  degrees of freedom
summary(bird.poisson)$deviance / summary(bird.poisson)$df.residual
[1] 22.02709

With a ratio of about 22, the Poisson model is clearly overdispersed. Overdispersion has two possible causes:

  1. The mean model is wrong, for example because predictors are missing, the relationship or link function is wrong, or there are outliers.
  2. The counts vary more than the Poisson distribution allows, even with a correct mean model.

Consequences

If the mean model is correct, the coefficient estimates are still consistent. But overdispersion leads to:

  • underestimated standard errors, and therefore too narrow confidence intervals and too small p-values,
  • overly complex models in model selection, because predictors appear significant too easily.

Remedies

If the mean model is wrong, improve it first. If the extra variation remains, use a model that allows the variance to be larger than the mean:

  1. Quasi-Poisson: keeps the Poisson mean model but estimates the dispersion from the data (quasi-likelihood).
  2. Negative binomial: uses a different distribution with an additional variance parameter.

The next section fits both models to the bird data.

Models for overdispersed counts

Quasi-Poisson

The quasi-Poisson model keeps the mean model of the Poisson regression but allows the variance to be larger than the mean. The variance is proportional to the mean, \(\text{Var}(y) = \phi \mu\), where the dispersion parameter \(\phi\) is estimated from the data. In R, we only change the family to quasipoisson:

bird.quasip <- glm(Y ~ relief, data = dat, family = quasipoisson)
summary(bird.quasip)

Call:
glm(formula = Y ~ relief, family = quasipoisson, data = dat)

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  4.66589    0.09953  46.878  < 2e-16 ***
relief       0.33956    0.03866   8.782 2.64e-12 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for quasipoisson family taken to be 21.27853)

    Null deviance: 2921.1  on 60  degrees of freedom
Residual deviance: 1299.6  on 59  degrees of freedom
AIC: NA

Number of Fisher Scoring iterations: 4

The coefficient estimates are identical to the Poisson model. The dispersion parameter is estimated at about 21 instead of being fixed at 1. It is computed from the Pearson residuals, so it differs slightly from the deviance ratio above. The standard errors are multiplied by \(\sqrt{\phi}\), i.e. they are about 4.6 times larger, and the tests use the t-distribution. The effect of relief remains significant. Because the quasi-Poisson model is not based on a full probability distribution, it has no likelihood and therefore no AIC.

Negative binomial

The negative-binomial model replaces the Poisson distribution with a distribution that has an additional parameter \(\theta\) for the variance. The variance increases with the square of the mean, \(\text{Var}(y) = \mu + \mu^2/\theta\). The smaller \(\theta\), the larger the overdispersion. We fit the model with glm.nb() from the MASS package, which estimates \(\theta\) together with the coefficients:

bird.nb <- glm.nb(Y ~ relief, data = dat, link = log)
summary(bird.nb)

Call:
glm.nb(formula = Y ~ relief, data = dat, link = log, init.theta = 11.71533906)

Coefficients:
            Estimate Std. Error z value Pr(>|z|)    
(Intercept)  4.72453    0.08796  53.714  < 2e-16 ***
relief       0.31269    0.03893   8.032 9.59e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for Negative Binomial(11.7153) family taken to be 1)

    Null deviance: 134.313  on 60  degrees of freedom
Residual deviance:  61.519  on 59  degrees of freedom
AIC: 681.88

Number of Fisher Scoring iterations: 1

              Theta:  11.72 
          Std. Err.:  2.21 

 2 x log-likelihood:  -675.879 

The estimated \(\theta\) is about 12. The coefficients differ slightly from the Poisson model, because the negative-binomial distribution weights the observations differently. The standard errors are similar to those of the quasi-Poisson model. The ratio of residual deviance to degrees of freedom is now close to 1, so the negative-binomial distribution accounts for the extra variation. Unlike the quasi-Poisson model, it is a full probability model and has an AIC.

Comparing the models

To compare the three models, we look at the effect of relief and its 95% confidence interval. We back-transform both with exp(), so they give the factor by which the expected number of species changes per unit of relief (see interpreting coefficients):

# Poisson
coeffs <- exp(coef(bird.poisson))
coeffs_ci <- exp(confint(bird.poisson))
cbind(coeffs, coeffs_ci)
                coeffs      2.5 %     97.5 %
(Intercept) 106.259866 101.846790 110.836066
relief        1.404328   1.381446   1.427589
# quasi-Poisson
coeffs <- exp(coef(bird.quasip))
coeffs_ci <- exp(confint(bird.quasip))
cbind(coeffs, coeffs_ci)
                coeffs     2.5 %     97.5 %
(Intercept) 106.259866 87.187307 128.808562
relief        1.404328  1.301813   1.514927
# negative-binomial
coeffs <- exp(coef(bird.nb))
coeffs_ci <- exp(confint(bird.nb))
cbind(coeffs, coeffs_ci)
                coeffs     2.5 %     97.5 %
(Intercept) 112.677003 95.549671 133.298947
relief        1.367104  1.271319   1.471155

All three models estimate a similar effect of about 1.4. The confidence intervals, however, differ: the interval of the Poisson model is about four times narrower than those of the other two models. Ignoring the overdispersion makes the estimate look more precise than it is.

The quasi-Poisson model has no AIC, but we can compare the Poisson and the negative-binomial model:

AIC(bird.poisson, bird.nb)
             df       AIC
bird.poisson  2 1739.6620
bird.nb       3  681.8786

The negative-binomial model has a much lower AIC, so it describes the data far better than the Poisson model, despite its additional parameter.

Residual analysis

As for logistic regression, we check count models with standardized Pearson residuals. They divide the raw residual by the standard deviation that the model expects at each fitted value. If the variance assumption of the model holds, they scatter around 0 without a pattern, mostly between -2 and 2. We compare the residuals of all three models:

dat$fitted_pois <- fitted(bird.poisson)
dat$resid_pois <- rstandard(bird.poisson, type = "pearson")
dat$fitted_quasip <- fitted(bird.quasip)
dat$resid_quasip <- rstandard(bird.quasip, type = "pearson")
dat$fitted_nb <- fitted(bird.nb)
dat$resid_nb <- rstandard(bird.nb, type = "pearson")

plot_pois <- ggplot(dat, aes(x = fitted_pois, y = resid_pois)) +
  geom_hline(yintercept = 0) +
  geom_hline(yintercept = c(-2, 2), linetype = "dashed") +
  geom_point() +
  labs(x = "Fitted counts", y = "Pearson residuals", title = "Poisson")

plot_quasip <- ggplot(dat, aes(x = fitted_quasip, y = resid_quasip)) +
  geom_hline(yintercept = 0) +
  geom_hline(yintercept = c(-2, 2), linetype = "dashed") +
  geom_point() +
  labs(x = "Fitted counts", y = "Pearson residuals", title = "Quasi-Poisson")

plot_nb <- ggplot(dat, aes(x = fitted_nb, y = resid_nb)) +
  geom_hline(yintercept = 0) +
  geom_hline(yintercept = c(-2, 2), linetype = "dashed") +
  geom_point() +
  labs(x = "Fitted counts", y = "Pearson residuals",
       title = "Negative binomial")

cowplot::plot_grid(plot_pois, plot_quasip, plot_nb, ncol = 3)

Because relief takes only four values, the residuals form four columns. For the Poisson model, 34 of the 61 residuals fall outside -2 to 2, with values from about -10 to 12: the counts vary much more than the Poisson distribution expects.

The quasi-Poisson residuals are the Poisson residuals divided by \(\sqrt{\phi}\). The pattern is therefore identical, only the scale is smaller, and most residuals now lie between -2 and 2. For the negative-binomial model, 1 residual falls outside this range.

Both models account for most of the overdispersion. In both, however, the residuals still spread more at high than at low fitted values: the variance increases with the mean somewhat faster than either model assumes.

Interpreting coefficients

All three models use a log link, so their coefficients are multiplicative when back-transformed to the response scale, as for the log-transformed ozone in the chapter on linear regression. With a one-unit increase in \(x\), the expected count is multiplied by \(e^{\beta_1}\).

For the negative-binomial model, we back-transform the coefficients with exp(), and their confidence intervals, computed with confint(), in the same way:

exp(coef(bird.nb))
(Intercept)      relief 
 112.677003    1.367104 
exp(confint(bird.nb))
                2.5 %     97.5 %
(Intercept) 95.549671 133.298947
relief       1.271319   1.471155

With a one-unit increase in relief, we expect the number of bird species to increase by a factor of about 1.37 (95% CI: 1.27 to 1.47), i.e. by about 37%.

Pseudo-\(R^2\)

As in the previous lab, we measure the goodness of fit with a pseudo-\(R^2\). It compares the residual deviance of the model with the null deviance of a model with only an intercept:

\[ \text{pseudo-}R^2 = 1 - \frac{\text{residual deviance}}{\text{null deviance}} \]

Like the \(R^2\) of a linear regression, it ranges from 0 (no improvement over the intercept-only model) to 1 (perfect fit). We compute it for the quasi-Poisson and the negative-binomial model:

pseudo_r2 <- 1 - bird.quasip$deviance / bird.quasip$null.deviance
pseudo_r2
[1] 0.5551062
pseudo_r2_nb <- 1 - bird.nb$deviance / bird.nb$null.deviance
pseudo_r2_nb
[1] 0.541972

In both models, relief explains a little more than half of the deviance. The quasi-Poisson model has the same deviances as the Poisson model, because it only changes the variance, not the fit. Its pseudo-\(R^2\) is therefore the same as for the Poisson model.

Visualizing the fitted models

Effects package

To plot the fitted curve with its confidence band, we use effect() from the effects package, as in the previous lab. It predicts the expected number of species along a sequence of relief values and returns the fitted values (fit) with their confidence limits (lower, upper) on the response scale. The result is a table that we can print or use for further calculations. Here, we use the quasi-Poisson model:

efct <- effect("relief", mod = bird.quasip, xlevels = list(relief = seq(0, 4, length.out = 100)))
efct <- as.data.frame(efct)
head(efct)
      relief      fit       se    lower    upper
1 0.00000000 106.2599 10.57639 87.07084 129.6779
2 0.04040404 107.7277 10.56825 88.52691 131.0931
3 0.08080808 109.2159 10.55831 90.00660 132.5249
4 0.12121212 110.7246 10.54654 91.51026 133.9734
5 0.16161616 112.2542 10.53293 93.03821 135.4390
6 0.20202020 113.8049 10.51746 94.59080 136.9219
p <- ggplot() +
  geom_point(data = dat, aes(x = relief, y = Y)) +
  geom_ribbon(data = efct, aes(x = relief, ymin = lower, ymax = upper), alpha = 0.3) +
  geom_line(data = efct, aes(x = relief, y = fit))
print(p)

The fitted curve increases exponentially with relief, and the confidence band widens with the expected number of species. The sequence of relief values runs from 0 to 4 and thus extends slightly beyond the observed range (about 0.6 to 3.6). There, the curve is an extrapolation.

Fitted values with ggplot

For a quick visual comparison, geom_smooth() fits the model directly within ggplot(). With method = "glm", we pass the family through method.args. For the negative-binomial model, we use method = "glm.nb" from the MASS package:

plot1 <- ggplot(dat, aes(x = relief, y = Y)) +
                geom_point() +
                geom_smooth(method = "glm", method.args=list(family = "poisson"), col = "red")

plot2 <- ggplot(dat, aes(x = relief, y = Y)) +
                geom_point() +
                geom_smooth(method = "glm", method.args=list(family = "quasipoisson"), col = "red")

plot3 <- ggplot(dat, aes(x = relief, y = Y)) +
                geom_point() +
                geom_smooth(method = "glm.nb", method.args=list(link = "log"), col = "red")

cowplot::plot_grid(plot1, plot2, plot3, ncol = 3)

The three fitted curves are almost identical, but the confidence bands differ. The band of the Poisson model is very narrow, because the model ignores the overdispersion. The quasi-Poisson and negative-binomial models have wider bands that reflect the actual variation in the data. geom_smooth() is convenient for plotting, but unlike effect(), it does not return the fitted values and confidence limits as a table.

References

Carroll, S.S., 1998. Modelling abiotic indicators when obtaining spatial predictions of species richness. Environmental and Ecological Statistics 5, 257–276.
Piegorsch, W.W., Bailer, A.J., 2005. Analyzing environmental data. Wiley, Chichester. https://doi.org/10.1002/0470012234