Activity: GLM & Logistic Regression
Generalized linear models
In-class Activity 15: Generalized Linear Models
Today’s Objectives
- Fit a linear model to count data and watch it predict something impossible
- Say why the week-6 log transformation is a fix, but not the same model
- Check that a Gaussian GLM reproduces
lm()exactly - Fit a Poisson GLM, measure overdispersion, and say what it does to your p-values
- Fit a negative binomial GLM and confirm it fixed the problem
- Find a count where the Poisson is the right model, on your own
- Fit a logistic regression on a binary response and interpret an odds ratio
📥 Script skeleton (.R) 📥 Galápagos data 📥 Ant data 📥 Guppy data
- Save the skeleton as
scripts/15_glm_logistic_regression.R, and the three csv files in yourdata/folder.
- All of today’s code is right here in this activity. Type it into your script as we go and run it chunk by chunk. The skeleton has the plumbing — libraries and the data reads — and nothing else.
- Section 8 has no code here. By then you will have run the same chain three times, so you do it once more on your own.
- The Q boxes are things to think about, not inline homework. They are not graded.
- The write-up at the bottom is practice for the homework. Do it, but it is not handed in.
- Hand in the 🎟️ exit ticket at the bottom of this page, with your script. The script must run top to bottom (Ctrl/Cmd + Shift + Enter) with no errors.
Today is a chain of models where each one fails for a different reason, and the failure is the content. Before each model, say out loud whether you expect it to work — then look at the diagnostic, not the p-value.
invisible(NULL) lines in the skeleton
Every section ends with invisible(NULL). It is a bumper. Press Ctrl/Cmd + Enter on a section’s last real line and your cursor jumps to the next line that has code on it — without the bumper, that is the next section, way down past the next heading. With it, the cursor stops right there and you keep your place. It does nothing and prints nothing.
Keep the plots plain today — no labels, colors, or themes. The goal is to read them. The one exception is the final figure in section 12, which is practice for the homework figure.
Where this fits
For the last three weeks every model has been a linear model — one-way ANOVA, factorial, and the redux. All of them assume the residuals are normal with constant variance. That is a fine assumption for body mass or growth rate.
It is a bad assumption for a count. A count is a whole number, it cannot go below zero, and its variance usually grows with its mean. Today is what you do instead.
A generalized linear model keeps the linear part and swaps out two things:
| Component | What it is | Example |
|---|---|---|
| Random | the response’s distribution | Poisson for counts |
| Systematic | the predictors | log(area_km2) |
| Link | connects the mean to the predictors | log for counts, logit for binary |
| Response looks like | Family |
|---|---|
| continuous, symmetric | gaussian — this is just lm() |
| counts | poisson |
| counts, variance > mean | negative binomial (glm.nb) |
| binary — present/absent | binomial(link = "logit") |
| positive, continuous, skewed | Gamma |
🧩 Block 1 — The linear model runs out (after lecture Part 1)
Sections 1–3: meet the count data, fit a linear model to it on purpose, then try the fix you already know.
Section 1 · The data
Written for you in the skeleton — run it and read it.
# ---- 1 The data ------------------------------------------
g_df <- read_csv("data/galapagos_species_area.csv")
g_df
g_df %>%
summarise(n = n(), min = min(n_species), max = max(n_species))You have seen this dataset before. In week 6 you fitted \(\log_{10}(S) \sim \log_{10}(A)\) to these same 17 islands and used them for the influential-point demonstration. Same islands, same question — today the response gets treated as what it actually is, a count.
✏️ Q1: n_species runs from 7 to 325 and area_km2 spans four orders of magnitude. Which of the two needs a log more urgently, and why?
Section 2 · Fit a linear model anyway
▶ Type this yourself:
# ---- 2 Fit a linear model anyway -------------------------
ggplot(g_df, aes(x = n_species)) +
geom_histogram(binwidth = 25)
ggplot(g_df, aes(x = area_km2, y = n_species)) +
geom_point()🔮 Predict first: for a normal distribution the variance has nothing to do with the mean. Before you run the next chunk — guess the mean of
n_species, then guess its variance.
▶ Type this yourself:
g_df %>%
summarise(
mean_spp = mean(n_species),
var_spp = var(n_species),
ratio = var_spp / mean_spp
)▶ Type this yourself:
lm_raw <- lm(n_species ~ area_km2, data = g_df)
summary(lm_raw)
shapiro.test(residuals(lm_raw))
check_heteroscedasticity(lm_raw)▶ Type this yourself — now ask the model to predict the smallest island:
predict(lm_raw,
newdata = data.frame(area_km2 = 0.518),
interval = "prediction")✏️ Q2: Write down the mean, the variance, and the ratio. What does a ratio over 100 tell you about the shape of this response?
✏️ Q3: Which assumption failed, and which one came back fine? Be careful here — do not report a violation the test did not find.
✏️ Q4: Look at that prediction interval. What is its lower bound, and what would that mean in the field?
✏️ Q5: The p-value for area_km2 is about 0.016. Did this model earn the right to that number?
💡 Key idea: this is the moment the linear-model toolkit runs out — and notice how it ran out. The variance was fine. What broke is that the normal distribution has no lower bound, so the model is free to predict −111 plant species. No amount of extra data fixes that; it is the distribution that is wrong.
Section 3 · You already know one fix
In week 6 you handled this with logs. Do it again and see how well it works.
▶ Type this yourself:
# ---- 3 You already know one fix --------------------------
lm_log <- lm(log10(n_species) ~ log10(area_km2), data = g_df)
summary(lm_log)
shapiro.test(residuals(lm_log))
check_heteroscedasticity(lm_log)R² rises from 0.33 to 0.59, normality goes from p = 0.002 to p = 0.48, and the slope 0.331 is the species–area exponent z. The transformation works.
So why is there anything left to teach? Run this:
▶ Type this yourself:
c(arithmetic = mean(g_df$n_species),
geometric = exp(mean(log(g_df$n_species))))✏️ Q6: Those two numbers are 119.3 and 73.6. lm() on a logged response back-transforms to the second one. Which of the two did you think you were modelling?
✏️ Q7: No island here has zero species. Suppose one did. What does log10(0) return, and what would you have to do to the data to carry on?
✏️ Q8: A count is a whole number. log10(n_species) is not. Is that a problem in practice here — and can you say why it is more of a problem for small counts than large ones?
💡 Key idea: the transformation is not wrong, it is a different question.
lm(log(Y) ~ X)models the mean of the log; a GLM with a log link models the log of the mean. Those back-transform to the geometric and the arithmetic mean — 73.6 against 119.3 here. Hold that thought; it explains a number in section 5.
🧩 Block 2 — Three families, one question (after lecture Parts 2–4)
Sections 4–7: Gaussian (the sanity check), Poisson (fails), negative binomial (works).
Section 4 · A Gaussian GLM is the same linear model
Before trusting glm() with an unfamiliar distribution, check that it reproduces the one you already know.
🔮 Predict first: a Gaussian GLM with an identity link is a linear model. Will the coefficients be identical, or just similar?
▶ Type this yourself:
# ---- 4 A Gaussian GLM is the same linear model -----------
lm_model <- lm(n_species ~ log(area_km2), data = g_df)
gauss_model <- glm(n_species ~ log(area_km2), data = g_df,
family = gaussian(link = "identity"))
round(cbind(lm = coef(lm_model), glm = coef(gauss_model)), 6)
all.equal(coef(lm_model), coef(gauss_model))
Anova(gauss_model, type = "III", test = "F")✏️ Q9: Identical, or just close? What did all.equal() return?
✏️ Q10: So if a Gaussian GLM is just lm() again, what is glm() actually adding? (What did you have to name in the glm() call that lm() never asked for?)
✏️ Q11: summary(gauss_model) reports a dispersion parameter. Compare it to the residual mean square from anova(lm_model). What is it?
💡 Key idea:
lm()is the special case ofglm()where the family is Gaussian and the link is the identity. Everything that follows changes exactly those two arguments. You are not learning a new model — you are learning two knobs on the one you already have.
Section 5 · Poisson GLM — the obvious choice, and it fails
Poisson is the distribution for counts. It has only one parameter, which means its mean and its variance are forced to be the same number. Remember the ratio from Q2.
🔮 Predict first: the Poisson insists variance = mean. Your ratio was over 100. Will the overdispersion check come back clean?
▶ Type this yourself:
# ---- 5 Poisson GLM - the obvious choice, and it fails ----
poiss_model <- glm(n_species ~ log(area_km2), data = g_df,
family = poisson(link = "log"))
summary(poiss_model)
Anova(poiss_model, type = "III", test = "LR")A Poisson GLM cannot use an F-test — the variance is pinned to the mean, so there is no \(\sigma^2\) to put in the denominator. We use a likelihood ratio test instead.
✏️ Q12: The slope is 0.2875. In section 3 the log–log slope was 0.331. Both are “the log slope” and they are different numbers. Which quantity is each one about?
✏️ Q13: \(e^{0.2875} = 1.333\). Finish this sentence: “every e-fold increase in island area multiplies expected richness by …”. Now do it for a doubling of area (\(2^{0.2875}\)).
Section 6 · Measure the overdispersion
▶ Type this yourself:
# ---- 6 Measure the overdispersion ------------------------
check_overdispersion(poiss_model)
set.seed(123)
sim_poiss <- simulateResiduals(poiss_model, n = 1000)
plot(sim_poiss)✏️ Q14: What is the dispersion ratio, and what number was it supposed to be?
✏️ Q15: Look at the DHARMa Q-Q plot. Which three tests printed on it are significant?
✏️ Q16: shapiro.test(residuals(poiss_model)) will run and give you a number. Why is that number meaningless?
💡 Key idea: R will not stop you from running a test that does not apply to the model you fitted. Check the diagnostic that matches the model, not the one you learned first.
Section 7 · Negative binomial — the one that works
The negative binomial adds a second parameter, theta (θ), which lets the variance exceed the mean: \(\operatorname{Var}(Y) = \mu + \mu^2/\theta\).
▶ Type this yourself:
# ---- 7 Negative binomial - the one that works ------------
nb_model <- glm.nb(n_species ~ log(area_km2), data = g_df)
summary(nb_model)
c(theta = nb_model$theta)
check_overdispersion(nb_model)
Anova(nb_model, type = "III", test = "LR")
AIC(poiss_model, nb_model)▶ Type this yourself — put the two sets of standard errors side by side:
cbind(estimate = round(coef(poiss_model), 4),
SE_poisson = round(summary(poiss_model)$coefficients[, 2], 4),
SE_negbin = round(summary(nb_model)$coefficients[, 2], 4))✏️ Q17: Compare the two slopes, then the two standard errors. Which barely moved, and which moved six-fold?
✏️ Q18: The Poisson LR χ² was about 979; the negative binomial’s is about 24. Did the conclusion change? Did the honesty of it change?
✏️ Q19: AIC drops by nearly 500. Nothing was added to the model but permission for the variance to be bigger than the mean. What does that tell you about how badly the Poisson was fitting?
✏️ Q20: Draw the fit: plot n_species against area_km2 on a log x-axis and add the NB fit. Why is the fitted line a curve on the raw count scale — the distribution, or the link?
🧩 Block 3 — Does every count need this? (after lecture Part 4)
Section 8 is yours with no code at all.
Section 8 · A different count — you write this one
No code on this page. You have now run the chain three times. Run it once more without the script in front of you, on a different dataset.
Gotelli & Ellison counted ant species in 22 New England bogs, and recorded each bog’s latitude and elevation_m.
Question: does ant species richness change with latitude and elevation?
Work through:
- Read
data/gotelli_ant_species.csvand compute the variance-to-mean ratio ofn_ant_species. - Fit the Poisson GLM with both predictors.
check_overdispersion()on it.- Fit the negative binomial version too. Look at
theta, and compare the two AICs. - Decide which one you would report, and read the latitude coefficient on the count scale.
💡 Hint: the only things that change from sections 5–7 are the formula and the data. If you get stuck, read what you typed, not this page.
✏️ Q21: The raw variance-to-mean ratio is about 2.0. On the Galápagos logic that looks like trouble. What did check_overdispersion() actually say once the predictors were in the model?
✏️ Q22: What value of theta did glm.nb() return, and which direction did the AIC move? What is glm.nb() telling you?
✏️ Q23: So overdispersion is a property of what — the data, or the model? Explain using the fact that the raw ratio was 2.0 and the fitted dispersion was not.
✏️ Q24: Rewrite this sentence so it is correct: “Count data require a negative binomial model.”
✏️ Q25: Read the latitude slope as a percentage change per degree (\(e^{\beta} - 1\)). Which direction does ant richness go as you move north?
🧩 Block 4 — A binary response (after lecture Parts 5–6)
Section 9 · Logistic regression
A count was one kind of non-normal response. A yes/no is another. Logistic regression models the probability of a 1, using the logit link to stretch probability (stuck between 0 and 1) onto a scale that runs from −∞ to +∞:
\[\log\left(\frac{\pi}{1-\pi}\right) = \beta_0 + \beta_1 x\]
Whitlock & Schluter’s guppy experiment: 160 guppies were each held at a cold temperature for one of four durations, and whether the fish died was recorded. mortality is 1 for died, 0 for survived; exposure_min is the duration in minutes.
Written for you in the skeleton:
# ---- 9 Logistic regression -------------------------------
guppy_df <- read_csv("data/guppy_cold_death.csv")
guppy_df %>%
count(exposure_min, mortality) %>%
pivot_wider(names_from = mortality, values_from = n,
names_prefix = "mortality_")▶ Type this yourself:
ggplot(guppy_df, aes(x = exposure_min, y = mortality)) +
geom_jitter(height = 0.03, width = 0.3)🔮 Predict first: longer in the cold is worse for a fish. Will the slope be positive or negative?
▶ Type this yourself:
guppy_model <- glm(mortality ~ exposure_min, data = guppy_df,
family = binomial(link = "logit"))
summary(guppy_model)▶ Type this yourself — the likelihood ratio test, against a model with no predictor:
null_model <- glm(mortality ~ 1, data = guppy_df,
family = binomial(link = "logit"))
anova(null_model, guppy_model, test = "Chisq")▶ Type this yourself — the odds ratio, three ways:
exp(coef(guppy_model))
exp(confint(guppy_model, "exposure_min"))
model_parameters(guppy_model, exponentiate = TRUE)
tidy(guppy_model, exponentiate = TRUE, conf.int = TRUE)▶ Type this yourself — goodness of fit:
r2(guppy_model)
pR2(guppy_model)
hoslem.test(guppy_model$y, fitted(guppy_model), g = 4)▶ Type this yourself — the fitted probability curve:
pred_df <- data.frame(
exposure_min = seq(min(guppy_df$exposure_min),
max(guppy_df$exposure_min), length.out = 100)
)
pred_df$prob <- predict(guppy_model, newdata = pred_df, type = "response")
ggplot() +
geom_jitter(data = guppy_df, aes(x = exposure_min, y = mortality),
height = 0.03, width = 0.3) +
geom_line(data = pred_df, aes(x = exposure_min, y = prob))▶ Type this yourself — the dose at which half the fish die (LD50):
-coef(guppy_model)[1] / coef(guppy_model)[2]✏️ Q26: Report the slope and the odds ratio with its CI. Does the CI include 1, and why does that matter more than whether it includes 0?
✏️ Q27: Say what the odds ratio means about guppies and cold — in fish, not in log-odds. “For every extra minute of exposure, the odds of dying …”
✏️ Q28: For the Hosmer–Lemeshow test you want a non-significant p-value. Why is that backwards from every other test you have run this semester?
✏️ Q29: r2() reports a pseudo-R². Why “pseudo” — what can’t you compute here that you could in a regression?
✏️ Q30: Your LD50 should be about 6.9 minutes. Find that point on your curve and check it against the raw counts at 3 and 8 minutes. Does it look right?
✏️ Q31: Every fish was assigned to one of only four exposure times. Does that break the model? (It does not — but say what it does let you do that a fully continuous predictor would not.)
💡 Key idea: the link function is doing the work in both halves of today. A
loglink keeps predicted counts above zero; alogitlink keeps predicted probabilities between 0 and 1. In both cases the linear part of the model is unchanged — you are still fitting a straight line, just on a scale where a straight line cannot predict something impossible.
Write-up (practice for the homework)
Answer these in your script as # comments after ANSWER:. Not handed in.
Section 10 · Report the count models
✏️ Q32: Fill in both count datasets:
test statistic p dispersion
GALAPAGOS
lm / Gaussian F -
Poisson LR chisq
negative binomial LR chisq
ANTS
Poisson LR chisq
negative binomial LR chisq
✏️ Q33: Two or three sentences reporting the Galápagos negative binomial result, with your own statistic, df, and p. Say which model you fitted and why that one.
✏️ Q34: Someone reports the Poisson p-value for the Galápagos slope. What have they done wrong, and in which direction is their answer wrong?
✏️ Q35: You fitted the same two families to two count datasets and reported a different one each time. In one sentence, what was the piece of output that decided it — the same piece of output both times?
Section 11 · Report the logistic model
✏️ Q36: Slope, odds ratio and its 95% CI, the LR test result, a pseudo-R², and the LD50.
✏️ Q37: One sentence an ecologist would actually write about cold exposure and guppy survival.
Section 12 · The final figure
One publication-quality figure. Pick either the NB fit of n_species on area_km2, or the logistic curve from section 9. Show the raw data under the fitted line. Proper axis labels, a real theme, readable sizing. Treat it like the homework figure. Export it with ggsave().
# ---- 12 The final figure ---------------------------------
# ... your plot here, then:
# ggsave("figures/15_glm_fit.pdf", width = 7, height = 5)✏️ Q38: Why would a straight line from lm() have been the wrong shape for the figure you chose? Name the impossible value it would have predicted.
🎟️ Exit ticket
📥 Download the exit ticket (.docx)
Hand this in on Canvas before you leave. It is how I know you ran the code, so every answer comes from your own output. Upload two files:
scripts/15_glm_logistic_regression.R. It must run top to bottom with no errors.- The exit ticket with these three answers.
✏️ E1. Section 2: write the mean, variance and variance/mean ratio of n_species. What does a ratio over 100 tell you?
✏️ E2. Section 2: which lm() assumption failed, and which one came back fine?
✏️ E3. The lm() p-value for area is 0.016. Did that model earn it? One sentence.
Points: 3, one per answer. No script that runs, no points.
Homework
Homework 5 — Generalized Linear Models
Social spider colonies: 17 communal webs, the number of spiders in each against the web’s height above the ground. One count response, one continuous predictor — and three models that give three different answers, one of which is “there is no relationship.” You decide which model you were entitled to and defend it, then run a sensitivity check on the one colony that is pulling against the trend.
Data: social_spider_colonies.csv — Whitlock & Schluter, The Analysis of Biological Data, Ch. 17, practice problem 15.
Start a new script for it — do not add it to 15_glm_logistic_regression.R.
Review and checkpoint
At this point you should be able to:
Run your whole script top to bottom with Ctrl/Cmd + Shift + Enter. It must run clean.
💡 Key idea: the chain you ran today — fit it, check the diagnostic that matches the model, change one assumption, refit — is the whole method. Next week the thing you change is not the distribution but the error structure, with random effects.