
Working with mgcv::gfam() models in gratia
Source:vignettes/articles/gfam-support.Rmd
gfam-support.RmdThis article shows how {gratia} works with models fitted using
mgcv::gfam(). This family lets groups of observations
follow different distributions in the same model. It covers plotting
shared and family-specific smooths, predicting and simulating responses
for each family, and checking the fitted model. A simulated example with
binary and count observations illustrates these operations.
An example with binary and count responses
Suppose one bird survey records whether a species was detected, while
another counts how many birds of that species were seen. Both surveys
can help describe how records vary with woodland cover. We fit them
together using mgcv::gfam() and assign a binomial or
Poisson family to each observation. gratia uses those assignments for
predictions, simulations and checks of the fitted model.
The two surveys provide separate observations. For a single response with zeros and positive values, a delta model estimates the probability of a positive response and the distribution of the positive values. See the worked delta-model example.
We simulate fixed-effort surveys at independent sites. The log odds of detection and the log expected count have different intercepts but share the same smooth response to woodland cover. Sharing the curve assumes that a change in cover has the same effect on log odds and log expected count. We compare this assumption with survey-specific curves below.
The example uses {mgcv} for fitting, {dplyr} to summarise results and {ggplot2} for plots.
We generate 300 detection records and 300 count records, then plot
the observations against woodland cover for each survey. The shared
habitat() function supplies the curved effect on both
linear predictors.
set.seed(241)
survey <- data.frame(
woodland = runif(600),
source = factor(rep(c("Detection", "Count"), each = 300),
levels = c("Detection", "Count"))
)
survey$family_id <- as.integer(survey$source)
habitat <- function(x) 1.8 * sin(pi * x) - 0.8 * x
eta <- ifelse(survey$source == "Detection", -1.3, 0.2) +
habitat(survey$woodland)
survey$observed <- ifelse(survey$source == "Detection",
rbinom(600, size = 1, prob = plogis(eta)),
rpois(600, lambda = exp(eta)))
ggplot(survey, aes(woodland, observed)) +
geom_point(alpha = 0.25) +
facet_wrap(~ source, scales = "free_y") +
labs(x = "Proportion of woodland", y = "Survey response")
The binary panel contains only zero and one. The count panel has a
wider range and variance that grows with the mean. A binomial family
with one trial and a Poisson family are appropriate for the simulated
surveys. For real counts, extra variation may require nb()
instead of Poisson; residual checks help assess that choice.
Fit a shared smooth with different response families
The first response column holds the observation and the second gives
its family’s position in the list. Family 1 is binomial and family 2 is
Poisson. The factor source gives each survey its own
intercept, and s(woodland) gives both linear predictors the
same smooth. REML estimates its smoothness.
joint <- gam(cbind(observed, family_id) ~ source + s(woodland, k = 10),
data = survey, family = gfam(list(binomial(), poisson())), method = "REML")
draw(joint, parametric = FALSE)
A change of d in the smooth multiplies both detection odds and expected count by \exp(d). The fitted smooth rises towards intermediate cover and then declines, as in the simulation. To recover the fitted detection probability or expected count, add the survey’s intercept to the smooth and apply that family’s inverse link.
The mgcv grouped-family documentation explains the response encoding and how to share terms.
Sharing a smooth can improve precision if its assumption is reasonable. A model with different smooths provides a useful comparison when the surveys have enough information to estimate them:
separate <- gam(cbind(observed, family_id) ~ source +
s(woodland, by = source, k = 10),
data = survey, family = gfam(list(binomial(), poisson())), method = "REML")
draw(separate, parametric = FALSE)
Both fitted curves peak at intermediate woodland cover. The wider intervals for the binary survey show that its curve is estimated less precisely. If survey effort varies and the expected count is proportional to effort, use a log-effort offset for the Poisson observations. Model the effect of effort on detection probability separately.
Predict the appropriate quantity for each survey
Prediction rows must identify their distribution. This matters even
if their covariates are identical. We generate the same cover grid for
both surveys and pass family_index explicitly.
Response-scale fitted_samples() applies each row’s inverse
link to every shared coefficient draw.
grid <- expand.grid(woodland = seq(0, 1, length.out = 80),
source = levels(survey$source))
grid$source <- factor(grid$source, levels = levels(survey$source))
index <- as.integer(grid$source)
means <- fitted_samples(joint, data = grid, family_index = index,
n_draws = 200, seed = 242)
intervals <- means |>
group_by(.row) |>
summarise(estimate = median(.fitted), lower = quantile(.fitted, 0.025),
upper = quantile(.fitted, 0.975), .groups = "drop")
curves <- bind_cols(grid, intervals |> select(-.row))
ggplot(curves, aes(woodland, estimate)) +
geom_ribbon(aes(ymin = lower, ymax = upper), alpha = 0.2) +
geom_line() +
facet_wrap(~ source, scales = "free_y") +
labs(x = "Proportion of woodland", y = "Expected survey response")
The curves show detection probabilities and expected counts, with pointwise intervals. Each coefficient draw is used for both surveys, so the intervals come from predictions that share the same woodland effect in each draw.
To compare these means with mgcv’s own predictions, supply both
columns of the response expression in the prediction data.
family_id selects the response family; the placeholder
observed value is ignored during prediction:
native_grid <- transform(grid, observed = 0, family_id = index)
head(data.frame(grid, expected = predict(joint, native_grid, type = "response")))
#> woodland source expected
#> 1 0.00000000 Detection 0.2491972
#> 2 0.01265823 Detection 0.2586062
#> 3 0.02531646 Detection 0.2682335
#> 4 0.03797468 Detection 0.2780466
#> 5 0.05063291 Detection 0.2879976
#> 6 0.06329114 Detection 0.2980352Use simulate() to draw future observations at these
cover values, holding the fitted coefficients and any other distribution
parameters fixed. These draws show variation in individual observations.
Use posterior_samples() to include coefficient uncertainty
in the draws as well.
replicates <- simulate(joint, data = grid, family_index = index,
nsim = 200, seed = 243)
future <- data.frame(grid, lower = apply(replicates, 1, quantile, 0.025),
upper = apply(replicates, 1, quantile, 0.975))
future |>
filter(woodland > 0.49, woodland < 0.51)
#> woodland source lower upper
#> 1 0.4936709 Detection 0 1.000
#> 2 0.5063291 Detection 0 1.000
#> 3 0.4936709 Count 1 9.000
#> 4 0.5063291 Count 2 9.025Even a precisely estimated detection probability yields individual
responses of zero or one. Individual counts also vary around their
fitted mean. The family_index values must match the
positions of the response families in the fitted model.
Check the fit separately for each response family
Raw residual magnitudes are not comparable between binary and count
responses. Probability integral transform (PIT) residuals locate each
observation in its own fitted distribution. At a discrete observation,
gratia randomises within its probability mass; quantile residuals
transform those probabilities to standard-normal scores. See Model diagnostics for the reference
calculations and the distinction from posterior predictive checks.
Setting by_family = TRUE gives separate panels for the
binary and count responses:
appraise(joint, type = "quantile", by_family = TRUE, seed = 244)
Separate panels help you see whether a pattern is confined to one survey. Look for departures in the tails of the QQ plots, changes in residual spread across the fitted values, or disagreement between the observed and fitted responses. Here the quantile residuals for both families broadly agree with their references.
Pooling standard-normal residuals is also possible. The colours retain each component’s identity; histogram densities are calculated separately with common bin edges. Traditional deviance or response residuals instead default to separate component facets because their scales differ. We draw the pooled histogram, then use a worm plot with separate family panels. A worm plot subtracts the reference quantile, so a well-fitting model should give points scattered around zero:
residuals_hist_plot(joint, type = "quantile", by_family = FALSE, seed = 244)
worm_plot(joint, type = "quantile", by_family = TRUE, seed = 244)
The worm plot’s separate panels show which response family contributes each pattern.
Next, compare the observed binary and count distributions with
replicated datasets. posterior_predictive_plot() includes
uncertainty in the fitted coefficients when generating these
replicates:
posterior_predictive_plot(joint, n = 50, seed = 245)
The count panel has some departures at individual counts, despite reasonable overall shape agreement. Its intervals are pointwise and have appreciable simulation error with 50 replicates; increase that number before judging individual probability masses closely.
The bars show how the proportion at each response value varies between replicated surveys. This checks the detection frequency in the binary survey and the distribution of counts in the other survey.
Using other families, weights and prediction data
gfam() accepts ordinary and extended mgcv families with
a scalar response, including negative binomial, Tweedie, beta, scaled-t
and ordered categories. gratia can simulate ordered-category responses.
For an ordinal component, request
fitted_samples(..., quantity = "expectation") to obtain
category probabilities, with categories identified by
.category. Link-scale fitted draws are also available.
General families with several linear predictors are not
gfam() components.
Missing required predictors or membership give missing predictions.
Missing responses alone do not prevent prediction. With
na.exclude(), excluded fitting rows are restored as
NA in fitted draws and simulations, while checks use the
observations actually fitted.
For scalar censored components, simulate() generates
uncensored responses. For a custom comparison with censored
observations, apply the same censoring rule to each simulated dataset
before comparing the distributions.
posterior_predictive_plot() is unavailable for censored
components. Matrix responses that encode censoring or binomial success
and failure counts are outside the scope of gfam().
For grouped binomial proportions, supply the number of trials in
weights; for Gaussian and Gamma components these weights
represent response precision. Prediction data default to weights of one
unless you supply them. These interpretations differ and should follow
how the observations were collected.
Use the component diagnostics to assess the observation distributions and the separate-curve comparison to decide whether to share the cover response.