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.
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.274893glance() 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 139tidy() 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.9301406augment() 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.431The 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 scaleThe 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.351854Any 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 scaleComparisons 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 scalehousing gives the satisfaction (Sat: low,
medium, high) of 1681 residents, recorded as frequencies
(Freq) in 72 cells defined by perceived influence
(Infl), housing type (Type), and contact with
other residents (Cont). The proportional odds model is
\[
P(Y_i\le j\mid x_i)=F(\alpha_j-x_i^\top\beta),\qquad j=1,2,
\] with \(F\) the logistic
distribution function and cutpoints \(\alpha_1<\alpha_2\), so that \[
P(Y_i=j\mid
x_i)=F(\alpha_j-x_i^\top\beta)-F(\alpha_{j-1}-x_i^\top\beta),
\] with \(\alpha_0=-\infty\) and
\(\alpha_3=\infty\). The frequencies
enter as weights.
housing <- MASS::housing
ord <- fastglm_ordinal(Sat ~ Infl + Type + Cont, data=housing, weights=Freq)tidy(ord)
#> term component estimate std.error statistic p.value
#> 1 threshold:Low|Medium threshold -0.4961351 0.12454078 NA NA
#> 2 threshold:Medium|High threshold 0.6907083 0.12521214 NA NA
#> 3 InflMedium location 0.5663937 0.10496301 5.396127 6.809467e-08
#> 4 InflHigh location 1.2888191 0.12670485 10.171821 2.649079e-24
#> 5 TypeApartment location -0.5723500 0.11874737 -4.819896 1.436329e-06
#> 6 TypeAtrium location -0.3661864 0.15676586 -2.335881 1.949745e-02
#> 7 TypeTerrace location -1.0910147 0.15151371 -7.200765 5.987547e-13
#> 8 ContHigh location 0.3602840 0.09535746 3.778247 1.579364e-04
glance(ord)
#> logLik AIC BIC deviance df df.residual nobs nobs.rows estimation
#> 1 -1739.575 3495.149 3538.566 3479.149 8 1673 1681 72 ML
#> converged boundary iterations
#> 1 TRUE FALSE 6The modes of emmeans for ordinal fits are those it provides
for MASS::polr(). With mode="prob", the grid
gains the outcome category as a factor, and each estimate is a category
probability averaged over the grid cells:
emmeans(ord, ~ Sat | Infl, mode="prob")
#> Infl = Low:
#> Sat prob SE df asymp.LCL asymp.UCL
#> Low 0.459 0.0192 Inf 0.422 0.497
#> Medium 0.267 0.0113 Inf 0.245 0.289
#> High 0.274 0.0161 Inf 0.242 0.305
#>
#> Infl = Medium:
#> Sat prob SE df asymp.LCL asymp.UCL
#> Low 0.331 0.0175 Inf 0.297 0.365
#> Medium 0.275 0.0113 Inf 0.253 0.297
#> High 0.394 0.0182 Inf 0.358 0.430
#>
#> Infl = High:
#> Sat prob SE df asymp.LCL asymp.UCL
#> Low 0.198 0.0169 Inf 0.164 0.231
#> Medium 0.238 0.0121 Inf 0.214 0.262
#> High 0.565 0.0243 Inf 0.517 0.612
#>
#> Results are averaged over the levels of: Type, Cont
#> Confidence level used: 0.95With mode="mean.class", the estimate is the mean
category number \(\sum_j j\,P(Y=j\mid
x)\), averaged over the grid, which places the three influence
levels on one scale:
pairs(emmeans(ord, "Infl", mode="mean.class"))
#> contrast estimate SE df z.ratio p.value
#> Low - Medium -0.249 0.0456 Inf -5.456 <0.0001
#> Low - High -0.553 0.0508 Inf -10.888 <0.0001
#> Medium - High -0.304 0.0503 Inf -6.042 <0.0001
#>
#> Results are averaged over the levels of: Type, Cont
#> P value adjustment: tukey method for comparing a family of 3 estimatesThe covariance of an ordinal fit is the inverse of the expected
information, while MASS::polr() and
ordinal::clm() use the observed information, so these
standard errors can differ from theirs by a few percent.
augment() keeps the matrix column .fitted
of category probabilities and adds one column
.prob_<level> per category:
head(augment(ord)[c("Sat","Infl","Type","Cont",".prob_Low",".prob_Medium",".prob_High",".class")], 3)
#> # A tibble: 3 × 8
#> Sat Infl Type Cont .prob_Low .prob_Medium .prob_High .class
#> <ord> <fct> <fct> <fct> <dbl> <dbl> <dbl> <ord>
#> 1 Low Low Tower Low 0.378 0.288 0.334 Low
#> 2 Medium Low Tower Low 0.378 0.288 0.334 Low
#> 3 High Low Tower Low 0.378 0.288 0.334 LowTreating 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 LowThe 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.95These 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.084A 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 testsThe degrees of freedom of 14 follow the convention of
nnet::multinom() in emmeans (the number of
coefficients).
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.679The 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_post0The 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] 0A 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.73623928Support 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.