Using fastglm with emmeans, broom, and tidymodels

fastglm supplies methods for generics of three other packages: tidy(), glance(), and augment() of broom; recover_data() and emm_basis() of emmeans; and an engine "fastglm" for model types of parsnip. Each set of methods is registered when the other package is loaded, and none of these packages is required by fastglm. This vignette carries three datasets from MASS through them: days absent from school (quine, counts), housing satisfaction (housing, ordered and unordered categories), and low birth weight (birthwt, a binary outcome). Each code chunk runs only when the packages it uses are installed.

Days absent: Poisson and negative binomial fits

quine records the days absent from school of 146 children, with ethnicity (Eth), sex (Sex), age group (Age, four levels), and learner status (Lrn). Both models below have the log-linear mean \[ \log \mu_i = x_i^\top\beta . \] The Poisson model sets \(\operatorname{Var}(Y_i)=\mu_i\); the negative binomial model sets \(\operatorname{Var}(Y_i)=\mu_i+\mu_i^2/\theta\) and estimates \(\theta\) with \(\beta\).

library(fastglm)
quine <- MASS::quine
pois <- fastglm(Days ~ Eth + Sex + Age + Lrn, data=quine, family=poisson())
nb <- fastglm_nb(Days ~ Eth + Sex + Age + Lrn, data=quine)
nb$theta
#> [1] 1.274893

glance() gives one row per fit. The Poisson residual deviance is more than ten times its residual degrees of freedom, so the Poisson variance is far too small for these data; the negative binomial log likelihood is higher by about 600.

library(broom)
rbind(poisson=glance(pois)[c("logLik","AIC","deviance","df.residual")],
      negbin=glance(nb)[c("logLik","AIC","deviance","df.residual")])
#>             logLik      AIC  deviance df.residual
#> poisson -1142.5918 2299.184 1696.7066         139
#> negbin   -546.5755 1109.151  167.9518         139

tidy() gives the coefficient table, here with Wald limits and exponentiated to the scale of mean ratios:

tidy(nb, conf.int=TRUE, exponentiate=TRUE)
#>          term   estimate std.error  statistic      p.value   conf.low
#> 1 (Intercept) 18.0759081 0.2284246 12.6719268 8.461020e-37 11.5522011
#> 2        EthN  0.5658809 0.1533334 -3.7132931 2.045797e-04  0.4189936
#> 3        SexM  1.0858035 0.1599150  0.5147751 6.067102e-01  0.7936542
#> 4       AgeF1  0.6386312 0.2397466 -1.8704255 6.142475e-02  0.3991880
#> 5       AgeF2  1.0920756 0.2361930  0.3729159 7.092110e-01  0.6873926
#> 6       AgeF3  1.4288943 0.2483244  1.4372370 1.506507e-01  0.8782659
#> 7       LrnSL  1.3392492 0.1864747  1.5664813 1.172360e-01  0.9292527
#>    conf.high
#> 1 28.2836536
#> 2  0.7642626
#> 3  1.4854948
#> 4  1.0216986
#> 5  1.7350044
#> 6  2.3247390
#> 7  1.9301406

augment() adds fitted values, residuals, and the influence measures of broom::augment.glm() (.hat, .sigma, .cooksd, .std.resid) to the model frame. With type.predict="response", .fitted is \(\hat\mu_i\):

aug <- augment(nb, type.predict="response")
head(aug)
#> # A tibble: 6 × 11
#>    Days Eth   Sex   Age   Lrn   .fitted .resid   .hat .sigma .cooksd .std.resid
#>   <int> <fct> <fct> <fct> <fct>   <dbl>  <dbl>  <dbl>  <dbl>   <dbl>      <dbl>
#> 1     2 A     M     F0    SL       26.3 -1.91  0.0738  0.995 0.0128      -1.98 
#> 2    11 A     M     F0    SL       26.3 -0.832 0.0738  0.998 0.00506     -0.864
#> 3    14 A     M     F0    SL       26.3 -0.625 0.0738  0.998 0.00327     -0.649
#> 4     5 A     M     F0    AL       19.6 -1.19  0.0519  0.997 0.00548     -1.23 
#> 5     5 A     M     F0    AL       19.6 -1.19  0.0519  0.997 0.00548     -1.23 
#> 6    13 A     M     F0    AL       19.6 -0.420 0.0519  0.999 0.00112     -0.431

Estimated marginal means and contrasts for counts

The reference grid has one cell for each combination of the factor levels, \(2\times2\times4\times2=32\) cells here. For the age group \(a\), the estimated marginal mean averages the linear predictor over the cells with that age and returns to the mean scale: \[ \hat m_a=\exp\Big(\frac{1}{|G_a|}\sum_{g\in G_a} x_g^\top\hat\beta\Big), \] where \(G_a\) is the set of grid cells with age \(a\). Contrasts are formed on the log scale, so with type="response" a pairwise contrast is a ratio of means \(\hat m_a/\hat m_b\). Standard errors use the delta method with the covariance of \(\hat\beta\), with \(\theta\) treated as known (as for MASS::glm.nb() fits).

library(emmeans)
age_nb <- emmeans(nb, "Age", type="response")
age_nb
#>  Age response   SE  df asymp.LCL asymp.UCL
#>  F0      16.4 2.99 Inf     11.48      23.4
#>  F1      10.5 1.52 Inf      7.88      13.9
#>  F2      17.9 2.62 Inf     13.44      23.9
#>  F3      23.4 4.35 Inf     16.28      33.7
#> 
#> Results are averaged over the levels of: Eth, Sex, Lrn 
#> Confidence level used: 0.95 
#> Intervals are back-transformed from the log scale
pairs(age_nb)
#>  contrast ratio    SE  df null z.ratio p.value
#>  F0 / F1  1.566 0.375 Inf    1   1.870  0.2408
#>  F0 / F2  0.916 0.216 Inf    1  -0.373  0.9823
#>  F0 / F3  0.700 0.174 Inf    1  -1.437  0.4760
#>  F1 / F2  0.585 0.119 Inf    1  -2.630  0.0424
#>  F1 / F3  0.447 0.110 Inf    1  -3.278  0.0058
#>  F2 / F3  0.764 0.187 Inf    1  -1.099  0.6901
#> 
#> Results are averaged over the levels of: Eth, Sex, Lrn 
#> P value adjustment: tukey method for comparing a family of 4 estimates 
#> Tests are performed on the log scale

The Poisson fit is a glm object, which emmeans handles through its own glm support. Its means differ somewhat from those of the negative binomial fit, and its standard errors are a quarter to a third as large, because they use \(\operatorname{Var}(Y_i)=\mu_i\):

age_pois <- emmeans(pois, "Age", type="response")
data.frame(Age=levels(quine$Age),
           mean_poisson=summary(age_pois)$rate, mean_negbin=summary(age_nb)$response,
           se_poisson=summary(age_pois)$SE, se_negbin=summary(age_nb)$SE)
#>   Age mean_poisson mean_negbin se_poisson se_negbin
#> 1  F0     14.93710    16.39717  0.7605777  2.985345
#> 2  F1     10.69682    10.47175  0.4940851  1.520235
#> 3  F2     19.33035    17.90695  0.6950677  2.621732
#> 4  F3     22.90927    23.42983  1.0891852  4.351854

Any covariance of the coefficients can replace the model-based one through the vcov. argument. The sandwich covariance of the negative binomial fit (HC0, the default of sandwich::vcovHC() for fastglm count models) gives standard errors that do not rely on the variance function:

emmeans(nb, "Age", type="response", vcov.=sandwich::vcovHC(nb))
#>  Age response   SE  df asymp.LCL asymp.UCL
#>  F0      16.4 3.40 Inf     10.92      24.6
#>  F1      10.5 1.42 Inf      8.02      13.7
#>  F2      17.9 2.45 Inf     13.69      23.4
#>  F3      23.4 4.24 Inf     16.43      33.4
#> 
#> Results are averaged over the levels of: Eth, Sex, Lrn 
#> Confidence level used: 0.95 
#> Intervals are back-transformed from the log scale

Comparisons with a control group use the same interface; here each age group is compared with the youngest (F0):

contrast(age_nb, "trt.vs.ctrl")
#>  contrast ratio    SE  df null z.ratio p.value
#>  F1 / F0  0.639 0.153 Inf    1  -1.870  0.1559
#>  F2 / F0  1.092 0.258 Inf    1   0.373  0.9426
#>  F3 / F0  1.429 0.355 Inf    1   1.437  0.3436
#> 
#> Results are averaged over the levels of: Eth, Sex, Lrn 
#> P value adjustment: dunnettx method for 3 tests 
#> Tests are performed on the log scale

Unordered satisfaction: multinomial probabilities

Treating Sat as unordered gives the baseline-category logit model, with low satisfaction as the reference category: \[ P(Y_i=k\mid x_i)=\frac{\exp(x_i^\top\beta_k)}{\sum_{l=1}^{3}\exp(x_i^\top\beta_l)},\qquad \beta_1=0 . \] This model has a separate coefficient vector for each non-reference category, 14 coefficients in all against 8 parameters for the proportional odds model.

housing_unordered <- transform(housing, Sat=factor(Sat, ordered=FALSE))
mn <- fastglm_multinom(Sat ~ Infl + Type + Cont, data=housing_unordered,
                       weights=Freq)
glance(mn)
#>   nobs df    logLik      AIC      BIC deviance null.deviance df.residual
#> 1 1681 14 -1735.042 3498.084 3574.064 3470.084      3648.878         130
#>   converged
#> 1      TRUE
head(augment(mn)[c("Sat","Infl",".prob_Low",".prob_Medium",".prob_High",".class")], 3)
#> # A tibble: 3 × 6
#>   Sat    Infl  .prob_Low .prob_Medium .prob_High .class
#>   <fct>  <fct>     <dbl>        <dbl>      <dbl> <fct> 
#> 1 Low    Low       0.396        0.260      0.344 Low   
#> 2 Medium Low       0.396        0.260      0.344 Low   
#> 3 High   Low       0.396        0.260      0.344 Low

The emmeans modes are those of nnet::multinom(): "prob" (the default) and "latent".

sat_mn <- emmeans(mn, ~ Sat | Infl, mode="prob")
sat_mn
#> Infl = Low:
#>  Sat     prob     SE df lower.CL upper.CL
#>  Low    0.453 0.0203 14    0.410    0.497
#>  Medium 0.275 0.0186 14    0.235    0.315
#>  High   0.271 0.0178 14    0.233    0.310
#> 
#> Infl = Medium:
#>  Sat     prob     SE df lower.CL upper.CL
#>  Low    0.320 0.0188 14    0.280    0.360
#>  Medium 0.296 0.0189 14    0.256    0.337
#>  High   0.384 0.0194 14    0.342    0.425
#> 
#> Infl = High:
#>  Sat     prob     SE df lower.CL upper.CL
#>  Low    0.205 0.0207 14    0.161    0.249
#>  Medium 0.230 0.0222 14    0.182    0.278
#>  High   0.565 0.0255 14    0.510    0.619
#> 
#> Results are averaged over the levels of: Type, Cont 
#> Confidence level used: 0.95

These probabilities are close to those of the proportional odds model (the largest difference is below), and the proportional odds model, with 6 fewer parameters, has the lower AIC:

sat_ord <- emmeans(ord, ~ Sat | Infl, mode="prob")
max(abs(summary(sat_mn)$prob - summary(sat_ord)$prob))
#> [1] 0.02076236
AIC(ord, mn)
#>     df      AIC
#> ord  8 3495.149
#> mn  14 3498.084

A contrast within each category compares the influence levels on the probability scale; here, each level is compared with low influence:

contrast(emmeans(mn, ~ Infl | Sat, mode="prob"), "trt.vs.ctrl")
#> Sat = Low:
#>  contrast     estimate     SE df t.ratio p.value
#>  Medium - Low  -0.1334 0.0263 14  -5.072  0.0003
#>  High - Low    -0.2483 0.0281 14  -8.840 <0.0001
#> 
#> Sat = Medium:
#>  contrast     estimate     SE df t.ratio p.value
#>  Medium - Low   0.0210 0.0253 14   0.828  0.6290
#>  High - Low    -0.0451 0.0282 14  -1.601  0.2302
#> 
#> Sat = High:
#>  contrast     estimate     SE df t.ratio p.value
#>  Medium - Low   0.1124 0.0253 14   4.446  0.0011
#>  High - Low     0.2934 0.0303 14   9.695 <0.0001
#> 
#> Results are averaged over the levels of: Type, Cont 
#> P value adjustment: dunnettx method for 2 tests

The degrees of freedom of 14 follow the convention of nnet::multinom() in emmeans (the number of coefficients).

Logistic regression in a tidymodels workflow

birthwt records whether each of 189 infants weighed less than 2.5 kg at birth (low), with the mother’s age, weight (lwt), race, smoking status, number of previous premature labors (ptl), hypertension (ht), and uterine irritability (ui). The logistic model is \[ \operatorname{logit} P(Y_i=\text{normal}\mid x_i)=x_i^\top\beta . \] As with the "glm" engine, the model is for the probability of the second level of the outcome factor. With the levels low and normal, yardstick treats the first level, low, as the event.

bw <- MASS::birthwt
bw <- data.frame(
    low=factor(bw$low, levels=c(1, 0), labels=c("low", "normal")),
    age=bw$age, lwt=bw$lwt, ptl=bw$ptl,
    race=factor(bw$race, labels=c("white", "black", "other")),
    smoke=factor(bw$smoke, labels=c("no", "yes")),
    ht=factor(bw$ht, labels=c("no", "yes")),
    ui=factor(bw$ui, labels=c("no", "yes")))

A recipe codes the factors as indicator columns, and set_engine("fastglm") selects fastglm for logistic_reg():

library(parsnip)
library(recipes)
library(workflows)
rec <- recipe(low ~ ., data=bw) |>
    step_dummy(all_nominal_predictors())
wf <- workflow() |>
    add_recipe(rec) |>
    add_model(logistic_reg() |> set_engine("fastglm"))
wf_fit <- fit(wf, data=bw)
tidy(extract_fit_engine(wf_fit))
#>          term    estimate   std.error  statistic     p.value
#> 1 (Intercept) -0.46440328 1.204702110 -0.3854922 0.699872776
#> 2         age  0.02706978 0.036452614  0.7426019 0.457722762
#> 3         lwt  0.01518256 0.006927902  2.1915093 0.028414954
#> 4         ptl -0.54175512 0.346266562 -1.5645609 0.117685907
#> 5  race_black -1.26321937 0.526467741 -2.3994241 0.016420885
#> 6  race_other -0.86163511 0.439197492 -1.9618398 0.049781142
#> 7   smoke_yes -0.92334916 0.400858315 -2.3034302 0.021254649
#> 8      ht_yes -1.83369561 0.691769988 -2.6507302 0.008031797
#> 9      ui_yes -0.75859650 0.459391821 -1.6513061 0.098676093
head(predict(wf_fit, bw, type="prob"), 3)
#> # A tibble: 3 × 2
#>   .pred_low .pred_normal
#>       <dbl>        <dbl>
#> 1     0.312        0.688
#> 2     0.128        0.872
#> 3     0.321        0.679

The coefficients are on the log odds of a normal birth weight, so a negative coefficient, as for smoking, lowers the probability of a normal weight. extract_fit_engine() returns the fastglm fit, with all of its methods. Engine arguments are given to set_engine(): method (the decomposition), firth=TRUE for mean bias reduction, link, and threads. An engine fit uses one thread unless threads is given, since resampling and tuning can run several fits at once in separate processes.

Five-fold cross-validation, stratified by the outcome, estimates out-of-sample accuracy, the Brier score, and the area under the ROC curve:

library(rsample)
library(tune)
set.seed(2)
folds <- vfold_cv(bw, v=5, strata=low)
res <- fit_resamples(wf, folds)
collect_metrics(res)
#> # A tibble: 3 × 6
#>   .metric     .estimator  mean     n std_err .config        
#>   <chr>       <chr>      <dbl> <int>   <dbl> <chr>          
#> 1 accuracy    binary     0.688     5 0.0170  pre0_mod0_post0
#> 2 brier_class binary     0.202     5 0.00388 pre0_mod0_post0
#> 3 roc_auc     binary     0.677     5 0.0371  pre0_mod0_post0

The same resamples with the "glm" engine give the same metrics, to rounding error:

wf_glm <- update_model(wf, logistic_reg() |> set_engine("glm"))
res_glm <- fit_resamples(wf_glm, folds)
max(abs(collect_metrics(res)$mean - collect_metrics(res_glm)$mean))
#> [1] 0

A bias-reduced fit changes only the engine argument:

wf_firth <- update_model(wf, logistic_reg() |> set_engine("fastglm", firth=TRUE))
coef(extract_fit_engine(fit(wf_firth, data=bw)))
#> (Intercept)         age         lwt         ptl  race_black  race_other 
#> -0.34885664  0.02531534  0.01383356 -0.50340912 -1.20740831 -0.81811246 
#>   smoke_yes      ht_yes      ui_yes 
#> -0.87822061 -1.71216978 -0.73623928

Marginal effects with marginaleffects

Support for fastglm fits in marginaleffects is being contributed to that package. Until it is available there, fastglm_marginal_effects() and fastglm_average() compute average marginal effects and averaged predictions, with delta-method standard errors, for GLMs, count, two-part, ordinal, and multinomial fits, including streamed fits.