Skip to main content

Simulating GLMs

A generalized linear model (GLM) is more than a regression equation: it combines a probability distribution for the response with a model for how the expected response changes with explanatory variables. Three ingredients define a GLM:

  1. The response distribution specifies the probability distribution of the observations (e.g., Gaussian responses, binary outcomes, or counts), describing their possible values and associated probabilities. It also determines the expected value (or theoretical mean) of the response, which represents its average value over many repetitions: \[\mu_i = E(Y_i),\]

    where \(Y_i\) is the response variable for observation \(i\).

  2. The linear predictor combines explanatory variables and regression coefficients, typically as \[\eta_i = \beta_0 + \beta_1 x_{i1} + \cdots + \beta_p x_{ip}.\]

  3. The link function connects the expected response, \(\mu_i = E(Y_i)\), to the linear predictor: \[g(\mu_i) = \eta_i.\]

The choice of response distribution also determines how the variance relates to the mean. For example, a Gaussian model assumes constant variance, \(\operatorname{Var}(Y_i)=\sigma^2\), a Poisson model assumes that the variance equals the mean, \(\operatorname{Var}(Y_i)=\mu_i\), and a binomial model assumes that the variance depends on the success probability, \(\operatorname{Var}(Y_i)=n_i p_i(1-p_i)\). These relationships matter: they determine what kinds of variation the model expects at different fitted values, and they help explain why a model may fit poorly even when its mean relationship looks plausible.

In this lab, we use simulation to make these model components tangible. Starting with the familiar Gaussian linear model and then a logistic model, we generate data from known parameters, fit the model, and compare estimates and predictions with the values used to generate the data. We then turn to real data, where the true model is unknown: we simulate parameters from a fitted model to approximate the uncertainty of the coefficients, and we simulate new data from fitted models to check whether they can reproduce the observations. For these checks, we use Poisson, negative binomial, and binomial models, a Gaussian model with a log link, and a log-normal model. Finally, we use the DHARMa package to perform these simulation-based checks in a standardised way.

The central aim is to understand how the assumed response distribution shapes the variance and predictive behaviour of a GLM - not simply to learn the syntax of glm(). As you work through the examples, pay particular attention to how the spread of simulated responses changes with the fitted mean, and to what that reveals about the adequacy of each model.

Before simulating response data for GLMs, it is useful to review how probability distributions are represented in R. If you need a refresher on probability distributions in R, see Probability distributions.

Packages

library(ggplot2) # Visualization
library(DHARMa)  # Simulation-based residual diagnostics
library(arm)     # Simulating regression coefficients
library(MASS)    # Negative binomial GLM
theme_set(theme_light())

What we will use simulation for

In this lab, simulation serves two purposes:

  • Understanding uncertainty: see how much estimates and predictions vary. We approach this in two ways. First, we simulate data from a model with known parameters, which shows whether fitting recovers them and how uncertain the estimated mean and individual observations are. Second, since the true model is unknown for real data, we simulate parameters from a fitted model to approximate the uncertainty of coefficients and of quantities derived from them.
  • Model checking: simulate new data from a fitted model and compare them with the observations. Systematic differences reveal features that the model does not capture, such as overdispersion.
Table 21.1: Overview of the simulations in this lab.
Purpose Models We simulate From
Understanding uncertainty Linear (normal), logistic (Bernoulli) Data A model with known parameters
Understanding uncertainty Linear model with interaction Parameters A fitted model
Model checking Poisson, negative binomial, binomial, Gaussian with log link, log-normal; all checked again with DHARMa Data A fitted model

Understanding uncertainty

In this part, we use simulation to see how much estimates and predictions vary. We start with data simulated from models whose parameters we choose ourselves, first a linear model and then a logistic model. For both, we follow the same three steps:

  1. write the model as a data-generating process,
  2. choose “true” parameter values and simulate data from it,
  3. fit the model to the simulated data and compare the estimates with the truth.

Because we choose the parameters ourselves, we know the correct answer, which is never the case with real data. This allows us to check how well the model recovers the true parameters and how uncertain the estimates are, i.e. how much they would vary if we drew a new random sample from the same model. At the end of this part, we turn to real data, where the truth is unknown, and approximate this uncertainty by simulating parameters from a fitted model.

Linear model

We start with a model you already know: simple linear regression. The goal is not to learn anything new about OLS, but to introduce the three steps in a familiar setting before we apply them to GLMs.

To simulate data from a model, we first need to write down how the model generates the data. Let’s start with the familiar way of writing a linear regression and then rewrite it in a form that carries over to GLMs. In OLS, the response \(Y_i\) is the sum of an intercept \(\beta_0\), a slope \(\beta_1\) times the explanatory variable \(X_i\), and a normally distributed error term \(\epsilon_i\):

\[Y_i = \beta_0 + \beta_1X_i + \epsilon_i \tag{21.1}\]

\[\epsilon_i \sim \mathcal{N}(0, \sigma^2)\]

We can express the same model in the two steps that form the basis of a GLM.

Step 1: distribution of the response. Each observation \(Y_i\) is drawn from a normal distribution with its own mean \(\mu_i\) and a variance \(\sigma^2\) that is the same for all observations:

\[Y_i \sim \mathcal{N}(\mu_i, \sigma^2)\]

Step 2: model for the mean. The mean depends on the explanatory variable through the linear predictor \(\eta_i\). In the normal model, the mean simply equals the linear predictor (identity link):

\[\mu_i = \eta_i = \beta_0 + \beta_1X_i\]

Combining the two steps. Substituting the expression for \(\mu_i\) into the response distribution gives the distributional formulation of the model:

\[Y_i \sim \mathcal{N}(\beta_0 + \beta_1X_i, \sigma^2) \tag{21.2}\]

This distributional form is the one to remember (Equation 21.2). Every GLM in the following sections is built from the same two steps: only the distribution in step 1 changes (binomial, Poisson, negative binomial), and in step 2 a link function \(g(\mu_i) = \eta_i\) takes the place of the identity.

Let’s set up a simulated linear regression scenario with known parameter values. These values play the role of the unknown population parameters. In a real study we would never know them. Here they serve as the benchmark against which we can judge our estimates. We specify the sample size, the true regression coefficients (intercept and slope), and the standard deviation of the random error. We also generate values for the explanatory variable \(X\), drawing them uniformly between -1 and 1:

set.seed(42)  # makes the simulation reproducible
n <- 1000     # sample size
b0 <- 0.2     # true value for the intercept
b1 <- 0.5     # true value for the slope
sigma <- 0.2  # standard deviation of random error
X <- runif(n, -1, 1) # X is set to range from -1 to 1

Then, we simulate the response variable \(Y\) by adding normally distributed random errors to the linear predictor (Equation 21.1). Note that rnorm() takes the standard deviation \(\sigma\), not the variance.

Y <- b0 + b1*X + rnorm(n, 0, sigma)

Equivalently, we can draw directly from a normal distribution with the linear predictor as its mean and \(\sigma\) as its standard deviation (Equation 21.2):

Y <- rnorm(n, b0 + b1*X, sigma)
plot(X, Y, pch=16, col=adjustcolor("deepskyblue3", alpha.f = 0.3))

Both lines of code produce data from the same model: adding \(\mathcal{N}(0, \sigma^2)\) noise to the linear predictor is the same as drawing from a normal distribution centred on the linear predictor. The second version, however, generalises directly to GLMs, for example rpois(n, exp(b0 + b1*X)) for counts.

Recovering the parameters

Now fit a linear model to the simulated response. Note that the residual standard error reported in the R output estimates the residual standard deviation \(\sigma\):

lmd <- lm(Y ~ X)
summary(lmd)

Call:
lm(formula = Y ~ X)

Residuals:
     Min       1Q   Median       3Q      Max 
-0.57156 -0.13133 -0.00289  0.13665  0.71317 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 0.204523   0.006332   32.30   <2e-16 ***
X           0.502068   0.010860   46.23   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.2001 on 998 degrees of freedom
Multiple R-squared:  0.6817,    Adjusted R-squared:  0.6814 
F-statistic:  2137 on 1 and 998 DF,  p-value: < 2.2e-16

Compare the estimates with the values we used to simulate the data:

Table 21.2: True and estimated parameters of the simulated linear model.
Parameter True value Estimate
Intercept \(\beta_0\) 0.2 0.205
Slope \(\beta_1\) 0.5 0.502
Residual SD \(\sigma\) 0.2 0.2

The estimates are close to, but not identical with, the true values. With a different seed (or without set.seed()), you would obtain a slightly different sample and slightly different estimates. This sampling variability is exactly what standard errors and confidence intervals describe.

Checking confidence and prediction intervals

So far we have looked at the uncertainty in the estimated parameters. When we use the fitted model to make predictions, this uncertainty carries over to the predicted values. We need to distinguish two questions: How precisely do we know the average response at a given value of \(X\)? And within what range do we expect a new individual observation to fall? The first answer only reflects the uncertainty in \(\beta_0\) and \(\beta_1\). The second additionally includes the random scatter of individual observations around the mean, which we set with \(\sigma\) when simulating the data.

The aim of this section is to check whether confidence and prediction intervals really do what they claim. With real data, we have to trust them; with simulated data, we can test them against the truth. We will check two things: whether the confidence band contains the true mean line, and whether about 95% of new observations fall inside the prediction band.

In R, predict() returns both intervals (default is level = 0.95):

  • With interval = "confidence", predict() returns fitted mean responses together with confidence limits that represent uncertainty in the estimated mean response.
  • With interval = "prediction", the limits additionally include the residual variation of an individual future observation, so prediction intervals are wider than confidence intervals for the mean.
df <- data.frame(
  X, Y,
  predict(lmd, interval = "confidence"),
  predict(lmd, interval = "prediction")[, 2:3]
)
names(df)[3:7] <- c("fit", "conf_lwr", "conf_upr", "pred_lwr", "pred_upr")

ggplot(df, aes(x = X, y = Y)) +
  geom_point(col = "deepskyblue3") +
  geom_line(aes(y=fit), col='black') +
  geom_ribbon(aes(ymin=pred_lwr, ymax=pred_upr, fill="Prediction band"), alpha = 0.3) +
  geom_ribbon(aes(ymin=conf_lwr, ymax=conf_upr, fill="Confidence band"), alpha = 0.6) +
  geom_abline(intercept = b0, slope = b1, colour = "red", linetype = "dashed") +
  scale_fill_manual(name = NULL, values = c("Prediction band" = "gray70", "Confidence band" = "gray40"))

The red dashed line is the true mean, \(\beta_0 + \beta_1X\), which we only know because we simulated the data. Here it lies entirely within the confidence band: the confidence interval captures the uncertainty about where the mean is. The confidence band is narrow because \(n = 1000\) observations pin down the mean well. The prediction band stays wide because no amount of data removes the scatter \(\sigma\) of individual observations around the mean.

For a 95% prediction interval, we expect about 95% of new observations to fall within the interval. We can check this by generating new observations from the true model and calculating the proportion that fall within the prediction intervals.

The code below simulates 1000 new observations at the same values of \(X\). For each new observation, the comparison returns TRUE if it falls within the prediction interval and FALSE otherwise. Because R treats TRUE as 1 and FALSE as 0, the mean of these values is the proportion of observations within the interval:

Y_new <- rnorm(n, b0 + b1*X, sigma)
coverage <- mean(Y_new >= df$pred_lwr & Y_new <= df$pred_upr)
coverage
[1] 0.939

Here, 94% of the new observations fall within the prediction interval, close to the expected 95%.

TipKey points
  • A statistical model can be read as a recipe for generating data.
  • Simulating from known parameters lets us check whether a model recovers them, and how precisely.
  • Writing the model as \(Y_i \sim \text{Distribution}(\mu_i)\) with \(g(\mu_i) = \eta_i\) is the common framework for all GLMs that follow.
  • Confidence intervals describe the uncertainty about the mean; prediction intervals additionally include the scatter of individual observations.

Logistic regression

We now simulate a binary response (0 or 1). As with the linear model (Equation 21.2), we build the model in two steps: a distribution for the response and a model for its mean.

Step 1: distribution of the response. Each observation \(Y_i\) is either 0 or 1, so we use a Bernoulli distribution (a binomial distribution with a single trial) with success probability \(p_i\):

\[Y_i \sim \operatorname{Bernoulli}(p_i)\]

Its mean is \(p_i\) and its variance is \(p_i(1-p_i)\). Unlike the normal model, there is no separate variance parameter.

Step 2: model for the mean. The mean \(p_i\) must lie between 0 and 1, but the linear predictor \(\eta_i\) can take any value. The logit link connects the two:

\[\operatorname{logit}(p_i) = \log\frac{p_i}{1-p_i} = \eta_i = \beta_0 + \beta_1X_i\]

Combined. Solving step 2 for \(p_i\) with the inverse logit and substituting into step 1 gives the full model:

\[Y_i \sim \operatorname{Bernoulli}\left(\operatorname{logit}^{-1}(\beta_0 + \beta_1X_i)\right) \tag{21.3}\]

Compared with Equation 21.2, the normal distribution is replaced by a Bernoulli distribution, and the identity link by the logit link. Here, \(\operatorname{logit}^{-1}(\eta) = \frac{1}{1 + e^{-\eta}}\) is the inverse of the logit function. It maps any value of the linear predictor to a probability between 0 and 1. In R, it is available as plogis().

As with the linear model, we first choose the sample size, the true intercept and slope, and draw \(X\) uniformly between -1 and 1. Unlike the linear model, there is no \(\sigma\) to set: the variance of a binary response follows from its probability. We use a steeper slope so that the S-shaped curve is clearly visible:

set.seed(3) # reproducible sample
n <- 1000 # sample size
b0 <- 1   # true value for the intercept
b1 <- 10  # true value for the slope
X <- runif(n, -1, 1) # X ranges from -1 to 1

Then, we simulate the response following Equation 21.3. Inside the call, plogis() converts the linear predictor into probabilities \(p_i\), and rbinom() with size = 1 draws a 0 or 1 for each observation from a Bernoulli distribution with that probability:

Y <- rbinom(n, size = 1, prob = plogis(b0 + b1*X))

Recovering the parameters

Now fit a logistic regression to the simulated response. Note that the coefficients are on the logit scale, the same scale on which we set the true values:

glmd <- glm(Y ~ X, family=binomial(link='logit'))
summary(glmd)

Call:
glm(formula = Y ~ X, family = binomial(link = "logit"))

Coefficients:
            Estimate Std. Error z value Pr(>|z|)    
(Intercept)   1.1170     0.1733   6.447 1.14e-10 ***
X            10.2414     0.7826  13.086  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 1371.37  on 999  degrees of freedom
Residual deviance:  300.16  on 998  degrees of freedom
AIC: 304.16

Number of Fisher Scoring iterations: 8

Compare the estimates with the values we used to simulate the data:

Table 21.3: True and estimated parameters of the simulated logistic model.
Parameter True value Estimate
Intercept \(\beta_0\) 1 1.117
Slope \(\beta_1\) 10 10.241

As with the linear model, the estimates scatter around the true values, but less tightly: the standard error of the slope is 0.78. Estimating a relationship from binary data is generally less precise than estimating it from continuous data. A binary observation carries much less information than a continuous one, especially where \(p_i\) is close to 0 or 1, which is the case for most observations with a steep slope like \(\beta_1 = 10\).

The plot shows the simulated 0/1 observations, the fitted probability curve with its 95% confidence band, and the true probability curve, \(\operatorname{logit}^{-1}(\beta_0 + \beta_1X)\), which we only know because we simulated the data. Unlike for lm(), predict() has no interval argument for a GLM. We therefore compute the band on the logit scale, where the estimates are approximately normal, and transform its limits with plogis(). This keeps the band between 0 and 1:

pr <- predict(glmd, se.fit = TRUE)  # fit and standard error on the logit scale
ds.sim <- data.frame(X = X, Y_sim = Y,
                     Y_fit = plogis(pr$fit),
                     conf_lwr = plogis(pr$fit - 1.96 * pr$se.fit),
                     conf_upr = plogis(pr$fit + 1.96 * pr$se.fit),
                     p_true = plogis(b0 + b1*X))
ggplot(ds.sim, aes(x = X)) +
  geom_point(aes(y = Y_sim), alpha = 0.1, col = "deepskyblue3") +
  geom_ribbon(aes(ymin = conf_lwr, ymax = conf_upr), fill = "gray50", alpha = 0.3) +
  geom_line(aes(y = Y_fit), col = "black") +
  geom_line(aes(y = p_true), col = "red", linetype = "dashed") +
  labs(y = "Probability / observed Y")

The fitted curve (black) closely follows the true curve (red dashed), which lies within the confidence band. The band is narrowest where \(p_i\) is close to 0 or 1 and widest around \(p_i = 0.5\), in the steep part of the curve. Note that the observations themselves are only 0 or 1; the model describes how the probability of observing a 1 changes with \(X\).

As for the linear model, the confidence band describes the uncertainty in the estimated mean. A prediction interval, however, is not meaningful for a binary response. A new observation is either 0 or 1, so at a given \(X\) its uncertainty is fully described by the Bernoulli distribution (step 1): \(Y_i\) is 1 with probability \(p_i\) and 0 otherwise. Prediction intervals become useful again for counts, as in the following sections.

Simulating parameters from a fitted model

In the previous sections, we could see the sampling variability of the estimates, because we knew the true model and could, in principle, draw new samples from it. With real data, we only have one sample. We can, however, approximate the sampling distribution of the coefficients from the fitted model and draw parameter values from it. Note the difference from the previous sections: we now simulate parameters, not data. This is particularly useful for quantities calculated from several coefficients, such as a slope that depends on an interaction term. The earnings–height example and the simulation-based approach follow Gelman and Hill (2007).

heights <- read.csv("data/heights.csv")
ht.lm <- lm(log.earn ~ height+male+height:male, data=heights)
summary(ht.lm)

Call:
lm(formula = log.earn ~ height + male + height:male, data = heights)

Residuals:
    Min      1Q  Median      3Q     Max 
-4.2375 -0.3380  0.1504  0.5674  2.2595 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept)  8.693956   0.934868   9.300   <2e-16 ***
height       0.012565   0.014432   0.871    0.384    
male        -0.122068   1.365947  -0.089    0.929    
height:male  0.008396   0.020232   0.415    0.678    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.8938 on 1055 degrees of freedom
Multiple R-squared:  0.08348,   Adjusted R-squared:  0.08088 
F-statistic: 32.03 on 3 and 1055 DF,  p-value: < 2.2e-16

The arm package provides sim() to draw approximate simulations of regression coefficients from their estimated sampling distribution.

set.seed(42)
n.sims <- 1000
ht.sim <- arm::sim(ht.lm, n.sims)
head(ht.sim@coef)
     (Intercept)       height       male  height:male
[1,]    8.452707  0.016696116  0.7157237 -0.004231103
[2,]    8.996681  0.007387804  1.2300630 -0.009496369
[3,]    7.441125  0.032158615  1.6862939 -0.018822979
[4,]    9.019794  0.007354699 -1.6660958  0.030949328
[5,]   10.156505 -0.010249467 -2.2204522  0.040164109
[6,]    8.718143  0.012826482 -1.2844322  0.025367751
ggplot(data.frame(b = ht.sim@coef[, 2]), aes(b)) +
  geom_histogram(fill = "deepskyblue3", bins = 30) +
  labs(x = "Height slope for women", y = "Count")

Because of the interaction, the height coefficient in the regression table is only the slope for women. The slope for men is the sum of the height and height:male coefficients. The regression table gives a standard error for each coefficient separately, but not for their sum. With the simulated coefficients, however, we can simply add the two coefficients in each simulation and take the 2.5% and 97.5% quantiles of the result:

height.for.men.coef <- ht.sim@coef[,2] + ht.sim@coef[,4]
ci_men <- quantile(height.for.men.coef, c(0.025, 0.975))
ci_men
        2.5%        97.5% 
-0.008289864  0.047410124 

The 95% interval for the slope among men ranges from about -0.008 to 0.047 on the log scale. Because the response is log earnings, this means that each additional inch of height is associated with a change in earnings of roughly -1 to 5%. The interval includes zero, so the data are also consistent with no effect of height among men. We obtained this interval simply by adding the simulated coefficients, without any formula for its standard error.

Model checking

In the linear and logistic examples, we simulated data from a model we defined ourselves and checked whether fitting recovers the true parameters. With real data, the true model is unknown, so this comparison is not possible. We can, however, reverse the direction: fit a model to the observed data, simulate new data from the fitted model, and check whether the simulated data look like the observations. If the model describes the data well, the observations should look like just another simulated dataset. Systematic differences, for example observations that scatter much more widely than the simulations, reveal features the model does not capture.

Table 21.4: Two ways of using simulation.
Linear and logistic examples This section
Starting point True parameters that we choose Observed data
Simulate from The true model The fitted model
Compare Estimates with true parameters Simulated data with observed data
Question Does the model recover the truth? Can the model reproduce the observed data?

Poisson regression for count data

We use bird counts as an example. As before (Equation 21.2, Equation 21.3), we build the model in two steps: a distribution for the response and a model for its mean.

Step 1: distribution of the response. The counts are non-negative integers, so we use a Poisson distribution with mean \(\lambda_i\):

\[Y_i \sim \operatorname{Poisson}(\lambda_i)\]

The Poisson distribution has a single parameter: its variance equals its mean, \(\operatorname{Var}(Y_i) = \lambda_i\). As in the logistic model, there is no separate variance parameter.

Step 2: model for the mean. The mean \(\lambda_i\) must be positive, but the linear predictor \(\eta_i\) can take any value. The log link connects the two:

\[\log(\lambda_i) = \eta_i = \beta_0 + \beta_1X_i\]

Combined. Solving step 2 for \(\lambda_i\) with the exponential function and substituting into step 1 gives the full model:

\[Y_i \sim \operatorname{Poisson}\left(\exp(\beta_0 + \beta_1X_i)\right) \tag{21.4}\]

Compared with Equation 21.3, the Bernoulli distribution is replaced by a Poisson distribution, and the logit link by the log link. The assumption that the variance equals the mean is strong, and simulation lets us check whether the data support it.

First, we fit a Poisson regression to the bird-count data.

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

# Run GLM on bird count data
glmd <- glm(Y ~ relief, data=dat, family=poisson(link = "log"))

# Extract fitted values
dat$Y_fit <- fitted(glmd)

# Model summary
summary(glmd)

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

Then, we simulate new counts from the fitted model, following Equation 21.4. This time, the estimated coefficients take the role of the true parameters. We thereby treat them as fixed and ignore their uncertainty. We could include it by first drawing parameter values from the fitted model, as in the height–earnings example, and then simulating data for each draw. For model checking, however, ignoring this uncertainty is usually a minor simplification compared with the discrepancies we are looking for. We simulate at the observed values of relief, so that the simulated and observed data share the same design and differ only in the variation of the response that the model expects:

set.seed(42)          # makes the simulation reproducible
b0 <- coef(glmd)[1]   # estimated intercept
b1 <- coef(glmd)[2]   # estimated slope
X <- dat$relief       # observed predictor values

Y_sim <- rpois(length(X), lambda = exp(b0 + b1*X))

As in the logistic model, the simulation works through Equation 21.4 from the inside out: exp() converts the linear predictor into the mean count \(\lambda_i\) (step 2), and rpois() draws a count from a Poisson distribution with that mean (step 1). The result is one dataset of the same size as the observed one, as the model would generate it. We plot both side by side (the points are jittered horizontally, because relief only takes four values):

ds <- rbind(data.frame(relief = X, Y = dat$Y, data = "Observed"),
            data.frame(relief = X, Y = Y_sim, data = "Simulated"))
ggplot(ds, aes(x = relief, y = Y)) +
  geom_jitter(width = 0.1, height = 0, alpha = 0.6, col = "deepskyblue3") +
  geom_line(data = dat, aes(y = Y_fit), col = "red") +
  facet_wrap(~ data) +
  labs(y = "Bird count")

Both datasets follow the same mean (red line), but the observed counts scatter much more widely around it than the simulated ones. A single simulated dataset could be a coincidence, so we repeat the simulation many times. R’s simulate() function does exactly what we did above: it takes the fitted model, computes the mean at the observed predictor values, and draws new responses from the model’s distribution, here rpois(). It also works for any other fitted GLM. Each column of Y_sims is one simulated dataset:

n_sim <- 1000
Y_sims <- simulate(glmd, nsim = n_sim)
dim(Y_sims)
[1]   61 1000

For each observation, the 2.5% and 97.5% quantiles of its 1000 simulated counts give a 95% interval: the range in which the model expects the count to fall. This is a prediction interval obtained by simulation. If the model is adequate, about 95% of the observed counts should fall inside it:

dat$sim_lwr <- apply(Y_sims, 1, quantile, probs = 0.025)
dat$sim_upr <- apply(Y_sims, 1, quantile, probs = 0.975)
coverage <- mean(dat$Y >= dat$sim_lwr & dat$Y <= dat$sim_upr)
coverage
[1] 0.442623
ggplot(dat, aes(x = relief)) +
  geom_errorbar(aes(ymin = sim_lwr, ymax = sim_upr), width = 0.3, col = "gray50") +
  geom_line(aes(y = Y_fit), col = "red") +
  geom_jitter(aes(y = Y), width = 0.1, height = 0, col = "deepskyblue3") +
  labs(y = "Bird count")

Only 44% of the observed counts fall within the 95% interval of the simulations. The Poisson model captures the mean trend, but it strongly underestimates the variance of the data.

Negative binomial model

The Poisson model in the previous section showed clear signs of overdispersion: the observed counts vary much more than the model expects. Overdispersion is common in count data, because the Poisson distribution has no separate variance parameter. Its variance is fixed to its mean, \(\operatorname{Var}(Y_i) = \lambda_i\), regardless of how variable the data actually are.

One option is a quasi-Poisson model, which scales the variance by a constant, \(\operatorname{Var}(Y_i) = c\lambda_i\). Because it is not based on a full probability distribution, however, we cannot simulate from it, and measures such as the AIC are not available. Here, we use a negative binomial model instead. It keeps the same two-step structure and only changes step 1.

Step 1: distribution of the response. We replace the Poisson distribution with a negative binomial distribution with mean \(\mu_i\) and dispersion parameter \(\theta\):

\[Y_i \sim \operatorname{NegBin}(\mu_i, \theta)\]

Its variance, \(\operatorname{Var}(Y_i) = \mu_i + \mu_i^2/\theta\), is larger than its mean. The additional parameter \(\theta\) is estimated from the data: the smaller \(\theta\), the larger the variance. As \(\theta \to \infty\), the negative binomial approaches the Poisson distribution.

Step 2: model for the mean. This step is unchanged from the Poisson model:

\[\log(\mu_i) = \eta_i = \beta_0 + \beta_1X_i\]

Combined.

\[Y_i \sim \operatorname{NegBin}\left(\exp(\beta_0 + \beta_1X_i), \theta\right) \tag{21.5}\]

We fit the model with glm.nb() from the MASS package, which estimates \(\theta\) together with the coefficients:

fit_nb <- glm.nb(Y ~ relief, data = dat, link = "log")
summary(fit_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 coefficients are similar to those of the Poisson model, so both models describe the same mean trend. The difference lies in the estimated dispersion, \(\hat\theta =\) 11.7, which allows for much more variation around the mean.

We simulate from the fitted model following Equation 21.5, again at the observed values of relief. In rnbinom(), the dispersion parameter \(\theta\) is called size:

set.seed(42)
b0 <- coef(fit_nb)[1]  # estimated intercept
b1 <- coef(fit_nb)[2]  # estimated slope
theta <- fit_nb$theta  # estimated dispersion parameter
X <- dat$relief        # observed predictor values

Y_sim <- rnbinom(length(X), size = theta, mu = exp(b0 + b1*X))

To check the model, we repeat the simulation with simulate() and compute the 95% interval for each observation, exactly as for the Poisson model:

Y_sims_nb <- simulate(fit_nb, nsim = n_sim)
dat$nb_lwr <- apply(Y_sims_nb, 1, quantile, probs = 0.025)
dat$nb_upr <- apply(Y_sims_nb, 1, quantile, probs = 0.975)
coverage_nb <- mean(dat$Y >= dat$nb_lwr & dat$Y <= dat$nb_upr)
coverage_nb
[1] 0.9180328
ggplot(dat, aes(x = relief)) +
  geom_errorbar(aes(ymin = nb_lwr, ymax = nb_upr), width = 0.3, col = "gray50") +
  geom_line(aes(y = fitted(fit_nb)), col = "red") +
  geom_jitter(aes(y = Y), width = 0.1, height = 0, col = "deepskyblue3") +
  labs(y = "Bird count")

Now 92% of the observed counts fall within the 95% interval of the simulations, compared with 44% for the Poisson model. The negative binomial model reproduces not only the mean trend but also the variability of the data. The AIC points in the same direction (Poisson: 1740, negative binomial: 682).

Binomial model with several trials

Our next example is a dose–response experiment. At each log dose, a group of \(n_i\) individuals was exposed to a drug, and the number of dead individuals was recorded. Unlike the binary response in the logistic regression section, each observation is now a count of “successes” out of several trials.

Step 1: distribution of the response. The number of dead individuals \(Y_i\) out of \(n_i\) follows a binomial distribution with death probability \(p_i\):

\[Y_i \sim \operatorname{Binomial}(n_i, p_i)\]

Its mean is \(n_i p_i\) and its variance \(n_i p_i(1-p_i)\). The number of trials \(n_i\) is known from the data, so, as for the Bernoulli distribution, there is no separate variance parameter to estimate.

Step 2: model for the mean. As in the logistic regression section, the logit link connects the probability to the linear predictor:

\[\operatorname{logit}(p_i) = \eta_i = \beta_0 + \beta_1X_i\]

Combined.

\[Y_i \sim \operatorname{Binomial}\left(n_i, \operatorname{logit}^{-1}(\beta_0 + \beta_1X_i)\right) \tag{21.6}\]

The model in Equation 21.3 is the special case with a single trial, \(n_i = 1\). In glm(), we specify a binomial response with several trials as cbind(successes, failures):

dat <- read.table("data/logistic.txt", sep = "\t", header = TRUE)

glmd <- glm(cbind(dead, n - dead) ~ logdose, data = dat,
            family = binomial(link = "logit"))
summary(glmd)

Call:
glm(formula = cbind(dead, n - dead) ~ logdose, family = binomial(link = "logit"), 
    data = dat)

Coefficients:
            Estimate Std. Error z value Pr(>|z|)    
(Intercept)  -1.5980     0.1555  -10.27   <2e-16 ***
logdose       2.3179     0.1699   13.64   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 311.241  on 50  degrees of freedom
Residual deviance:  72.387  on 49  degrees of freedom
AIC: 223.39

Number of Fisher Scoring iterations: 4

We simulate from the fitted model following Equation 21.6, at the observed doses and with the observed number of trials per group:

set.seed(42)
b0 <- coef(glmd)[1]  # estimated intercept
b1 <- coef(glmd)[2]  # estimated slope
X <- dat$logdose     # observed predictor values

Y_sim <- rbinom(nrow(dat), size = dat$n, prob = plogis(b0 + b1*X))

We repeat the simulation with simulate(). For a binomial model with several trials, each simulated dataset is a two-column matrix of successes and failures, so we extract the first column (the number of dead):

sims <- simulate(glmd, nsim = n_sim)
Y_sims <- sapply(sims, function(x) x[, 1])

dat$sim_lwr <- apply(Y_sims, 1, quantile, probs = 0.025)
dat$sim_upr <- apply(Y_sims, 1, quantile, probs = 0.975)
coverage_bin <- mean(dat$dead >= dat$sim_lwr & dat$dead <= dat$sim_upr)
coverage_bin
[1] 0.9607843
ggplot(dat, aes(x = logdose)) +
  geom_errorbar(aes(ymin = sim_lwr / n, ymax = sim_upr / n), width = 0.05, col = "gray50") +
  geom_line(aes(y = fitted(glmd)), col = "red") +
  geom_point(aes(y = dead / n), col = "deepskyblue3") +
  labs(x = "Log dose", y = "Proportion dead")

Because the number of trials differs between groups, the plot shows proportions (dead / \(n_i\)). Here, 96% of the observations fall within the 95% interval of the simulations, close to the expected 95%. Unlike the Poisson model, this model passes the check: the observed variation is consistent with what the binomial distribution expects. A check that reveals no problem is informative, too.

Gaussian error model with a log link

Here, we model ozone concentration as a function of temperature (airquality dataset). Ozone increases non-linearly with temperature and cannot be negative. One option is a normal distribution combined with a log link.

Step 1: distribution of the response. As in the linear model, the response is normally distributed with a constant variance:

\[Y_i \sim \mathcal{N}(\mu_i, \sigma^2)\]

Step 2: model for the mean. Unlike the linear model, the log link connects the mean to the linear predictor, so the mean increases exponentially with temperature:

\[\log(\mu_i) = \eta_i = \beta_0 + \beta_1X_i\]

Combined.

\[Y_i \sim \mathcal{N}\left(\exp(\beta_0 + \beta_1X_i), \sigma^2\right) \tag{21.7}\]

Compared with Equation 21.2, only the link has changed. The model thus assumes a curved mean but the same scatter around it at all temperatures.

airquality <- na.omit(airquality)
glmd <- glm(Ozone ~ Temp, data = airquality, family = gaussian(link = "log"))
summary(glmd)

Call:
glm(formula = Ozone ~ Temp, family = gaussian(link = "log"), 
    data = airquality)

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) -1.175464   0.539822  -2.178   0.0316 *  
Temp         0.061241   0.006215   9.854   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for gaussian family taken to be 524.3711)

    Null deviance: 121802  on 110  degrees of freedom
Residual deviance:  57155  on 109  degrees of freedom
AIC: 1014.1

Number of Fisher Scoring iterations: 5

The residual standard deviation \(\sigma\) is not part of the coefficients. We obtain it from the estimated dispersion, which for the Gaussian model is the residual variance \(\sigma^2\). We then simulate following Equation 21.7:

set.seed(42)
b0 <- coef(glmd)[1]                       # estimated intercept
b1 <- coef(glmd)[2]                       # estimated slope
sigma <- sqrt(summary(glmd)$dispersion)   # estimated residual SD
X <- airquality$Temp                      # observed predictor values

Y_sim <- rnorm(nrow(airquality), mean = exp(b0 + b1*X), sd = sigma)

We repeat the simulation with simulate() and compute the 95% interval for each observation:

Y_sims <- simulate(glmd, nsim = n_sim)
airquality$sim_lwr <- apply(Y_sims, 1, quantile, probs = 0.025)
airquality$sim_upr <- apply(Y_sims, 1, quantile, probs = 0.975)
coverage_gauss <- mean(airquality$Ozone >= airquality$sim_lwr &
                       airquality$Ozone <= airquality$sim_upr)
coverage_gauss
[1] 0.954955
ggplot(airquality, aes(x = Temp)) +
  geom_ribbon(aes(ymin = sim_lwr, ymax = sim_upr), fill = "gray50", alpha = 0.3) +
  geom_line(aes(y = fitted(glmd)), col = "red") +
  geom_point(aes(y = Ozone), col = "deepskyblue3") +
  geom_hline(yintercept = 0, linetype = "dashed") +
  labs(x = "Temperature (°F)", y = "Ozone (ppb)")

With 95% of the observations inside the 95% interval, the model seems to pass the check. The plot, however, reveals two problems. First, the interval has the same width at all temperatures: at low temperatures it is much wider than the scatter of the data and extends below zero, while at high temperatures the observations scatter more widely around the mean. Second, the model produces impossible values: 9% of all simulated ozone concentrations are negative. Both problems arise from step 1, the assumption of a constant variance. The overall coverage alone would not have shown this, so it is important to look at where the observations deviate from the simulations. A better model needs a distribution whose variance increases with the mean.

Log-transforming the response

A simple and common alternative to a Gaussian error model with a log link is to log-transform the response and fit a linear model with lm(). This changes step 1, not only the link:

Step 1: distribution of the response. The logarithm of the response is normally distributed:

\[\log(Y_i) \sim \mathcal{N}(\eta_i, \sigma^2)\]

This means that \(Y_i\) itself follows a log-normal distribution. The error is additive on the log scale and thus multiplicative on the original scale: the scatter increases with the mean, and \(Y_i\) can never be negative.

Step 2: model for the mean. The linear predictor describes the mean of the log-transformed response (identity link on the log scale):

\[\eta_i = \beta_0 + \beta_1X_i\]

Combined.

\[\log(Y_i) \sim \mathcal{N}(\beta_0 + \beta_1X_i, \sigma^2) \tag{21.8}\]

Note the difference from Equation 21.7. The GLM with log link models the log of the mean, \(\log(E[Y_i]) = \eta_i\). The linear model on \(\log(Y_i)\) models the mean of the logs, \(E[\log(Y_i)] = \eta_i\). Back-transformed, \(\exp(\eta_i)\) is therefore the median of \(Y_i\), not its mean. The mean is \(\exp(\eta_i + \sigma^2/2)\).

To simulate, we draw from the normal distribution on the log scale and back-transform with exp():

fit_ln <- lm(log(Ozone) ~ Temp, data = airquality)
summary(fit_ln)

Call:
lm(formula = log(Ozone) ~ Temp, data = airquality)

Residuals:
     Min       1Q   Median       3Q      Max 
-2.14417 -0.32555  0.02066  0.34234  1.49100 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) -1.848518   0.455080  -4.062  9.2e-05 ***
Temp         0.067673   0.005807  11.654  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.5804 on 109 degrees of freedom
Multiple R-squared:  0.5548,    Adjusted R-squared:  0.5507 
F-statistic: 135.8 on 1 and 109 DF,  p-value: < 2.2e-16
set.seed(42)
sigma_ln <- summary(fit_ln)$sigma   # residual SD on the log scale
Y_sim <- exp(rnorm(nrow(airquality), mean = fitted(fit_ln), sd = sigma_ln))

simulate() works for lm() too, but it would return simulated values of \(\log(Y_i)\), so we back-transform them:

Y_sims <- exp(simulate(fit_ln, nsim = n_sim))
airquality$ln_lwr <- apply(Y_sims, 1, quantile, probs = 0.025)
airquality$ln_upr <- apply(Y_sims, 1, quantile, probs = 0.975)
coverage_ln <- mean(airquality$Ozone >= airquality$ln_lwr &
                    airquality$Ozone <= airquality$ln_upr)
coverage_ln
[1] 0.9459459
ggplot(airquality, aes(x = Temp)) +
  geom_ribbon(aes(ymin = ln_lwr, ymax = ln_upr), fill = "gray50", alpha = 0.3) +
  geom_line(aes(y = exp(fitted(fit_ln))), col = "red") +
  geom_point(aes(y = Ozone), col = "deepskyblue3") +
  geom_hline(yintercept = 0, linetype = "dashed") +
  labs(x = "Temperature (°F)", y = "Ozone (ppb)")

With 95% of the observations inside the 95% interval, the coverage is similar to that of the Gaussian model, but the shape of the interval follows the data more closely: it is narrow at low temperatures, widens with the mean, and never falls below zero. At the highest temperatures, however, the upper limit lies far above all observations, so the log-normal model now somewhat overestimates the variance there. The red line shows the back-transformed fit, \(\exp(\hat\eta_i)\), which is the median ozone concentration. The mean is higher by a factor of \(\exp(\hat\sigma^2/2) =\) 1.18, a common pitfall when back-transforming predictions.

Log-transforming has two limitations: it does not work with zeros, since \(\log(0)\) is undefined, and the coefficients describe effects on the log scale of the response. A GLM with a distribution whose variance increases with the mean, such as the Gamma distribution (family = Gamma(link = "log")), avoids both and models the mean directly.

Standardised checks with DHARMa

All checks in this section followed the same pattern: simulate many datasets from the fitted model and see where each observation falls within its simulated values. The DHARMa package (Hartig, 2026) automates this and puts the result on a common scale. For each observation, it computes a scaled residual: the proportion of simulated values that are smaller than the observed value.

  • A residual of 0.5 means that the observation lies in the middle of what the model expects.
  • A residual close to 0 or 1 means that the observation is more extreme than almost all simulations.

Our coverage check is a special case of this: an observation lies within the 95% interval of the simulations exactly when its scaled residual is between 0.025 and 0.975. If the model is correct, the scaled residuals are uniformly distributed between 0 and 1, whatever the type of model: counts, binary data, proportions, or continuous data. Deviations from a uniform distribution reveal problems with the model.

We start again with the bird counts. simulateResiduals() simulates from the fitted model and computes the scaled residuals:

birds <- read.table("data/bird_counts.txt", sep = ";", header = TRUE)
fit_poisson <- glm(Y ~ relief, data = birds, family = poisson(link = "log"))

set.seed(42)
res_poisson <- simulateResiduals(fit_poisson, n = 1000)

# share of residuals between 0.025 and 0.975 (= coverage of the 95% interval)
mean(res_poisson$scaledResiduals >= 0.025 & res_poisson$scaledResiduals <= 0.975)
[1] 0.442623

The share of residuals between 0.025 and 0.975 matches the coverage we computed by hand. plot() shows two diagnostic plots. The left panel is a QQ plot of the scaled residuals against a uniform distribution; the points should lie on the diagonal. It also reports three tests: for uniformity (KS test), dispersion, and outliers. The right panel shows the residuals against the model predictions. Their 25%, 50% and 75% quantiles should lie at 0.25, 0.5 and 0.75 across the whole range of predictions. Because relief only takes four values here, DHARMa shows one boxplot per value; for continuous predictions, it draws quantile lines instead (see the ozone example below). Deviations are marked in red:

plot(res_poisson)

The residuals are far from uniform: many of them are close to 0 or 1, because many observations lie outside the range of the simulations. All three tests are significant, and three of the four boxplots deviate from the expected quartiles. testDispersion() compares the variance of the observed data with that of the simulated data directly:

testDispersion(res_poisson)


    DHARMa nonparametric dispersion test via sd of residuals fitted vs.
    simulated

data:  simulationOutput
dispersion = 25.662, p-value < 2.2e-16
alternative hypothesis: two.sided

The observed variance (red line) lies far outside the distribution of the simulated variances: the Poisson model is overdispersed. The same check for the negative binomial model:

fit_negbin <- glm.nb(Y ~ relief, data = birds, link = "log")
res_negbin <- simulateResiduals(fit_negbin, n = 1000)
plot(res_negbin)

The residuals of the negative binomial model are close to uniform, and the tests no longer indicate a problem.

DHARMa is particularly useful for detecting where a model fails. For the ozone data, the overall coverage of the Gaussian model with log link looked fine, but the plot revealed that the variance does not match the data. The right panel of the DHARMa plot shows this directly:

fit_gauss <- glm(Ozone ~ Temp, data = airquality, family = gaussian(link = "log"))
res_gauss <- simulateResiduals(fit_gauss, n = 1000)
plot(res_gauss)

The quantile lines in the right panel deviate from their expected values, and DHARMa highlights them as significant. For low fitted values, the residuals cluster around the middle, because the model expects more scatter than the data show. For high fitted values, the residuals spread out more. DHARMa also works for the log-normal model fitted with lm():

res_ln <- simulateResiduals(fit_ln, n = 1000)
plot(res_ln)

The log-normal model performs better, although the quantile test still indicates some deviation, consistent with the too-wide interval at high temperatures that we saw in the plot above.

Finally, the binomial dose–response model:

drug <- read.table("data/logistic.txt", sep = "\t", header = TRUE)
fit_binom <- glm(cbind(dead, n - dead) ~ logdose, data = drug,
                 family = binomial(link = "logit"))
res_binom <- simulateResiduals(fit_binom, n = 1000)
plot(res_binom)

As in our own check, the model shows no clear problems.

Table 21.5: Summary of the model checks.
Data Model Result of the check
Bird counts Poisson Overdispersion: data vary much more than the model expects
Bird counts Negative binomial No clear problems
Dose–response Binomial No clear problems
Ozone Gaussian, log link Variance does not match: too large at low, too small at high values; negative simulated values
Ozone Log-normal (lm() on log scale) Better, but variance overestimated at high temperatures

DHARMa does not replace looking at the simulations, but it makes the checks comparable across models and adds formal tests. Note that DHARMa only checks the fitted model against the data. It cannot tell us whether the estimates are close to the true parameters; for that, we need simulations from a known model, as in the first part of this lab.

TipKey points
  • To check a fitted model, simulate new data from it and compare them with the observations. If the model is adequate, the observations look like just another simulated dataset.
  • The response distribution (step 1) determines how much variation the model expects. A model can describe the mean trend well and still fail because its variance does not match the data, as for the Poisson model.
  • An overall measure such as coverage can hide problems. Look at where the observations deviate from the simulations, for example with DHARMa’s residual plots.

References

Gelman, A., Hill, J., 2007. Data analysis using regression and multilevel/hierarchical models, Analytical methods for social research. Cambridge University Press, Cambridge. https://doi.org/10.1017/CBO9780511790942
Hartig, F., 2026. DHARMa: Residual diagnostics for hierarchical (multi-level / mixed) regression models. https://doi.org/10.32614/CRAN.package.DHARMa