Generalized Mixed Models
A binary outcome that is measured several times per patient breaks two assumptions of ordinary regression at once. The outcome needs a logit link, and the measurements from one patient are correlated. A generalized linear mixed model, GLMM, handles both: the link function takes care of the binary outcome, and a random effect takes care of the clustering.
This page fits a GLMM with glmer() in R and a generalized estimating equation, GEE, in R and Python. The two methods return different coefficients for the same data, and the page shows why both are correct.
When to use it, and when not to
Section titled “When to use it, and when not to”Use a GLMM when the outcome is not continuous and the observations come in groups: binary calls per patient, cell counts per animal, positive wells per plate. For a continuous grouped outcome, use the linear mixed model on the mixed-effects page. For a binary outcome with independent observations, logistic regression is correct and simpler.
The analysis that a GLMM replaces is the pooled one. A logistic regression on all rows treats six correlated sites from one patient as six independent pieces of evidence, and its standard error comes out too small.
Get the data
Section titled “Get the data”Download biopsy_marker.csv into your working directory. The invented table has 240 rows: 40 patients with 6 biopsy sites each. The columns are patient, site, dose and marker_positive, which is 1 when the site was scored positive for the marker. Dose is 0, 1 or 2 and is fixed for each patient, so the patient is the experimental unit for the dose question.
The values come from a simulation with known answers. For a given patient, each dose level adds 0.9 to the log-odds of a positive site. Patients differ from each other with a standard deviation of 1.5 on the log-odds scale, which is more than one dose level moves a patient.
The first block loads the table, computes the positive rate of each patient, and defines a helper that prints the dose effect of a model as a log-odds coefficient and as an odds ratio with a Wald 95% confidence interval.
library(lme4)library(geepack)library(ggplot2)
biopsy <- read.csv("biopsy_marker.csv")biopsy$patient <- factor(biopsy$patient)dir.create("outputs", showWarnings = FALSE)
#' Print the dose effect of one model as log-odds and as an odds ratio.#'#' @param label A short name of the model for the printed lines.#' @param estimate The log-odds coefficient of dose.#' @param std_error The standard error of the coefficient.#' @return Invisibly, the Wald 95% limits of the odds ratio.ReportDose <- function(label, estimate, std_error) { limits <- exp(estimate + c(-1, 1) * qnorm(0.975) * std_error) cat(sprintf("%s: log-odds per dose %.4f, SE %.4f, z = %.2f\n", label, estimate, std_error, estimate / std_error)) cat(sprintf(" odds ratio %.2f [95%% CI %.2f, %.2f]\n", exp(estimate), limits[1], limits[2])) invisible(limits)}
patient_rates <- aggregate(marker_positive ~ patient + dose, data = biopsy, FUN = mean)cat(sprintf("%d sites in %d patients, %.1f%% positive\n", nrow(biopsy), nlevels(biopsy$patient), 100 * mean(biopsy$marker_positive)))for (dose in sort(unique(patient_rates$dose))) { rates <- patient_rates$marker_positive[patient_rates$dose == dose] cat(sprintf("Dose %d: %2d patients, rate per patient %.2f to %.2f\n", dose, length(rates), min(rates), max(rates)))}240 sites in 40 patients, 55.4% positiveDose 0: 13 patients, rate per patient 0.00 to 1.00Dose 1: 8 patients, rate per patient 0.17 to 0.83Dose 2: 19 patients, rate per patient 0.17 to 1.00from pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport statsmodels.api as smimport statsmodels.formula.api as smffrom scipy import stats
biopsy = pd.read_csv("biopsy_marker.csv")output = Path("outputs")output.mkdir(exist_ok=True)
def report_dose(label, estimate, std_error): """Print the dose effect of one model as log-odds and as an odds ratio.
Args: label: A short name of the model for the printed lines. estimate: The log-odds coefficient of dose. std_error: The standard error of the coefficient.
Returns: The Wald 95% limits of the odds ratio. """ margin = stats.norm.ppf(0.975) * std_error limits = np.exp([estimate - margin, estimate + margin]) print(f"{label}: log-odds per dose {estimate:.4f}, SE {std_error:.4f}, " f"z = {estimate / std_error:.2f}") print(f" odds ratio {np.exp(estimate):.2f} " f"[95% CI {limits[0]:.2f}, {limits[1]:.2f}]") return limits
patient_rates = biopsy.groupby(["patient", "dose"], as_index=False)["marker_positive"].mean()doses = sorted(patient_rates["dose"].unique())print(f"{len(biopsy)} sites in {biopsy['patient'].nunique()} patients, " f"{100 * biopsy['marker_positive'].mean():.1f}% positive")for dose in doses: rates = patient_rates.loc[patient_rates["dose"] == dose, "marker_positive"] print(f"Dose {dose:.0f}: {len(rates):2d} patients, " f"rate per patient {rates.min():.2f} to {rates.max():.2f}")240 sites in 40 patients, 55.4% positiveDose 0: 13 patients, rate per patient 0.00 to 1.00Dose 1: 8 patients, rate per patient 0.17 to 0.83Dose 2: 19 patients, rate per patient 0.17 to 1.00Overall, 55.4% of the 240 sites are positive. At dose 0 the rate per patient runs from 0.00 to 1.00, and the other two dose levels cover most of that range as well. Patients at the same dose are far from interchangeable, and the figure shows it with one point per patient.
patient_rates$dose_level <- factor(patient_rates$dose)jitter <- position_jitter(width = 0.12, height = 0, seed = 7)clustering_plot <- ggplot(patient_rates, aes(dose_level, marker_positive)) + geom_boxplot(width = 0.5, outlier.shape = NA, fill = "#D9E2EC", alpha = 0.7) + geom_point(position = jitter, size = 2, alpha = 0.8, color = "#1f4e5f") + labs(x = "Dose level", y = "Proportion of positive sites per patient") + theme_minimal(base_size = 12)ggsave("outputs/glmm-clustering-r.png", clustering_plot, width = 5.4, height = 4.2, dpi = 150, bg = "white")
rng = np.random.default_rng(7)figure, axes = plt.subplots(figsize=(5.4, 4.2))for position, dose in enumerate(doses, start=1): rates = patient_rates.loc[patient_rates["dose"] == dose, "marker_positive"] axes.boxplot(rates, positions=[position], widths=0.5, showfliers=False, patch_artist=True, boxprops={"facecolor": "#D9E2EC"}, medianprops={"color": "black"}) axes.scatter(position + rng.uniform(-0.12, 0.12, len(rates)), rates, s=22, alpha=0.8, color="#1f4e5f", zorder=3)axes.set_xticks(range(1, len(doses) + 1), [f"{dose:.0f}" for dose in doses])axes.set_xlabel("Dose level")axes.set_ylabel("Proportion of positive sites per patient")axes.spines[["top", "right"]].set_visible(False)figure.savefig(output / "glmm-clustering-python.png", dpi=150, bbox_inches="tight")plt.close(figure)
Each point is a patient, so the figure shows the 40 units that the dose question has. The points are moved sideways by a small random amount with a fixed seed, because many patients share a rate.
Fit the pooled model first
Section titled “Fit the pooled model first”The pooled logistic regression ignores the patient. It is the reference that the later models are compared with.
naive <- glm(marker_positive ~ dose, family = binomial, data = biopsy)naive_table <- coef(summary(naive))ReportDose("Pooled logistic", naive_table["dose", "Estimate"], naive_table["dose", "Std. Error"])Pooled logistic: log-odds per dose 0.7195, SE 0.1559, z = 4.62 odds ratio 2.05 [95% CI 1.51, 2.79]naive = smf.glm("marker_positive ~ dose", data=biopsy, family=sm.families.Binomial()).fit()report_dose("Pooled logistic", naive.params["dose"], naive.bse["dose"])Pooled logistic: log-odds per dose 0.7195, SE 0.1559, z = 4.62 odds ratio 2.05 [95% CI 1.51, 2.79]The pooled model estimates that each dose level multiplies the odds of a positive site by 2.05, with a 95% interval from 1.51 to 2.79. The coefficient is a usable estimate of the population-averaged effect, as the GEE section shows. The interval is the problem, because its standard error of 0.1559 assumes 240 independent sites.
Fit the GLMM
Section titled “Fit the GLMM”(1 | patient) gives each patient a baseline log-odds, drawn from a normal distribution whose standard deviation the model estimates. glmer() approximates the likelihood, and nAGQ sets the number of quadrature points of that approximation. The default of 1 is the Laplace approximation. The lme4 documentation states that larger values evaluate the log-likelihood more accurately and take longer, and that adaptive quadrature works only for a model with a single scalar random effect, as here. The block fits the model with 10 points and prints the Laplace fit for comparison.
This step is in R only. statsmodels 0.15 has no maximum likelihood GLMM for a binary outcome. Its BinomialBayesMixedGLM is a Bayesian model with a Laplace or variational approximation of the posterior, so it returns posterior summaries under a prior in place of maximum likelihood estimates.
glmm <- glmer(marker_positive ~ dose + (1 | patient), family = binomial, data = biopsy, nAGQ = 10)glmm_table <- coef(summary(glmm))ReportDose("glmer", glmm_table["dose", "Estimate"], glmm_table["dose", "Std. Error"])patient_sd <- attr(VarCorr(glmm)$patient, "stddev")[[1]]# The residual variance of a logistic model is pi squared over three.icc <- patient_sd^2 / (patient_sd^2 + pi^2 / 3)cat(sprintf("Patient SD = %.3f, intraclass correlation = %.3f\n", patient_sd, icc))laplace <- glmer(marker_positive ~ dose + (1 | patient), family = binomial, data = biopsy)cat(sprintf("Laplace fit: log-odds per dose %.4f, SE %.4f, SD %.3f\n", coef(summary(laplace))["dose", "Estimate"], coef(summary(laplace))["dose", "Std. Error"], attr(VarCorr(laplace)$patient, "stddev")[[1]]))glmer: log-odds per dose 0.9009, SE 0.2746, z = 3.28 odds ratio 2.46 [95% CI 1.44, 4.22]Patient SD = 1.106, intraclass correlation = 0.271Laplace fit: log-odds per dose 0.8950, SE 0.2673, SD 1.055For a given patient, one dose level multiplies the odds of a positive site by 2.46, with a 95% interval from 1.44 to 4.22. The log-odds coefficient of 0.9009 is close to the simulated 0.9.
The patient standard deviation is 1.106, where the simulation used 1.5. On the latent log-odds scale that gives an intraclass correlation of 0.271, so about 27% of the variance lies between patients. Forty patients with six binary sites each do not estimate that standard deviation precisely.
The Laplace fit gives nearly the same dose coefficient, 0.8950, and a smaller patient standard deviation, 1.055 against 1.106. The lme4 documentation calls adaptive quadrature the most reliable approximation for a GLMM, so the fit with 10 points is the one to report.
Fit the GEE
Section titled “Fit the GEE”A GEE does not model the patients. It fits the same mean model as the pooled regression, estimates one working correlation between the sites of a patient, and computes sandwich standard errors that count the clusters. The exchangeable structure assumes that any two sites of one patient are equally correlated, which is the correlation pattern that a random intercept produces.
geeglm() from geepack takes the cluster in id and expects the rows of one cluster to be adjacent, as they are in this table. statsmodels takes the cluster in groups.
gee <- geeglm(marker_positive ~ dose, id = patient, family = binomial, corstr = "exchangeable", data = biopsy)gee_table <- coef(summary(gee))ReportDose("GEE, geepack", gee_table["dose", "Estimate"], gee_table["dose", "Std.err"])cat(sprintf("Working correlation = %.3f\n", summary(gee)$corr$Estimate))cat(sprintf("SE ratio, GEE to pooled = %.2f\n", gee_table["dose", "Std.err"] / naive_table["dose", "Std. Error"]))GEE, geepack: log-odds per dose 0.7195, SE 0.2204, z = 3.26 odds ratio 2.05 [95% CI 1.33, 3.16]Working correlation = 0.189SE ratio, GEE to pooled = 1.41gee = smf.gee("marker_positive ~ dose", groups="patient", data=biopsy, family=sm.families.Binomial(), cov_struct=sm.cov_struct.Exchangeable()).fit()report_dose("GEE, statsmodels", gee.params["dose"], gee.bse["dose"])print(f"Working correlation = {gee.cov_struct.dep_params:.3f}")print("SE ratio, GEE to pooled = " f"{gee.bse['dose'] / naive.bse['dose']:.2f}")GEE, statsmodels: log-odds per dose 0.7195, SE 0.2204, z = 3.26 odds ratio 2.05 [95% CI 1.33, 3.16]Working correlation = 0.188SE ratio, GEE to pooled = 1.41The two packages agree on the coefficient, 0.7195, and on the sandwich standard error, 0.2204. The working correlation differs in the third decimal, 0.189 in geepack and 0.188 in statsmodels, and that difference does not reach the coefficient or its standard error.
The GEE coefficient equals the pooled coefficient. Every patient has six sites and one dose, so the exchangeable correlation gives every row the same weight, and the estimate does not move. The standard error does move. It is 1.41 times the pooled value, and the interval of the odds ratio runs from 1.33 to 3.16, where the pooled model claimed 1.51 to 2.79. The z statistic falls from 4.62 to 3.26.
With unequal cluster sizes, or with a predictor that varies within a patient, the GEE coefficient would differ from the pooled one as well.
Why the two coefficients differ
Section titled “Why the two coefficients differ”glmer() and the GEE estimate different quantities.
- The GLMM coefficient is conditional, or subject-specific. It is the change in the log-odds of one patient when the dose of that patient goes up one level.
- The GEE coefficient is marginal, or population-averaged. It is the change in the log-odds of a positive site across the whole population when everyone moves up one level.
With a logit link the two are different numbers, and the marginal one is closer to zero. Averaging logistic curves that are shifted left and right across patients gives a flatter curve than any one of them. Zeger, Liang, and Albert, 1988, give an approximation for the size of the gap: the marginal coefficient is the conditional coefficient divided by the square root of 1 + c²σ², where σ is the patient standard deviation and c is 16√3 / (15π).
The block computes that prediction from the glmer() fit and sets it beside the GEE estimate. It is in R only, because it needs the GLMM.
logit_scale <- 16 * sqrt(3) / (15 * pi)attenuation <- sqrt(1 + logit_scale^2 * patient_sd^2)cat(sprintf("c squared = %.3f, attenuation factor = %.3f\n", logit_scale^2, attenuation))cat(sprintf("Conditional effect from glmer = %.4f\n", glmm_table["dose", "Estimate"]))cat(sprintf("Marginal effect predicted from glmer = %.4f\n", glmm_table["dose", "Estimate"] / attenuation))cat(sprintf("Marginal effect estimated by GEE = %.4f\n", gee_table["dose", "Estimate"]))c squared = 0.346, attenuation factor = 1.193Conditional effect from glmer = 0.9009Marginal effect predicted from glmer = 0.7552Marginal effect estimated by GEE = 0.7195With a patient standard deviation of 1.106 the attenuation factor is 1.193, so the conditional coefficient of 0.9009 predicts a marginal coefficient of 0.7552. The GEE estimates 0.7195. The gap between the prediction and the estimate, 0.036, is small next to the GEE standard error of 0.2204.
The two models give nearly the same z statistic, 3.28 from glmer() and 3.26 from the GEE. They describe one dose effect on two scales.
Which coefficient to report depends on the question. A clinician who asks what a higher dose does to one patient needs the conditional effect, an odds ratio of 2.46. A question about the rate of positive sites in a treated population needs the marginal effect, an odds ratio of 2.05. Say which of the two a reported number is.
Mistakes to avoid
Section titled “Mistakes to avoid”- Do not pool the sites. The pooled model reported a standard error of 0.1559 where the sandwich estimate is 0.2204, and a predictor that is fixed per patient is affected in this direction whenever the sites of a patient are positively correlated.
- Do not treat a
glmer()coefficient and a GEE coefficient as two estimates of one number. Compute the attenuation factor before you call the difference a discrepancy. The same care applies when one paper reports a conditional odds ratio and another reports a marginal one. - Do not read the intraclass correlation of 0.271 as the correlation between the 0 and 1 calls of two sites. It lives on the latent log-odds scale. The working correlation of the GEE, 0.189, is the correlation on the observed scale.
- Do not keep the Laplace default without a comparison when clusters are small. Here it lowered the patient standard deviation from 1.106 to 1.055.
- In single-cell data, the cells of one donor play the role of the sites and the donor plays the role of the patient. A test that treats cells as independent replicates repeats the error of the pooled model.
Scientific references
Section titled “Scientific references”Bates, Mächler, Bolker and Walker, 2015 describe linear mixed-model representation and estimation in lme4.
Halekoh, Højsgaard, and Yan, 2006 describe the geepack package for generalized estimating equations in R.
Liang and Zeger, 1986 introduce generalized estimating equations for longitudinal data with a working correlation.
Zeger, Liang, and Albert, 1988 compare subject-specific and population-averaged models and derive the approximation that links their logistic coefficients.
Further reading
Section titled “Further reading”The lme4 glmer reference explains the response family, the random effects formula and the nAGQ setting used on this page.
The geepack geeglm reference lists the working correlation structures and states the row order that id needs. The statsmodels GEE guide describes the same model in Python, with its covariance structures.
The statsmodels page on Bayesian mixed GLMs describes BinomialBayesMixedGLM, the closest model to a GLMM that statsmodels offers.
The mixed-effects page covers the random intercept for a continuous outcome, and the logistic regression page covers the model for independent binary observations.