Is it possible to calculate marginal effects on a ridge / lasso logistic regression model fit through glmnet?

It seems like there is no support on applying the margins package to extract average marginal effects from a glmnet model. I am not able to replicate the same behaviour from glm as I'm fitting a ridge regression and (I think) the latter doesn't support this calculation. Is there any option to calculate marginal effects from a logistic ridge regression model?

Upvotes: 0

Views: 175

Answers (1)

Vincent
Vincent

Reputation: 17823

The development version of marginaleffects (soon to be published on CRAN as version 0.16.0) supports tidymodels. First, install the package:

remotes::install_github("vincentarelbundock/marginaleffects")

Then, restart R completely.

Finally, note that glmnet is only supported when the fit is specified via tidymodels’s formula interface (not the matrix form):

library(tidymodels)
library(marginaleffects)

penguins <- modeldata::penguins |> na.omit()

mod <- linear_reg(mode = "regression", penalty = 1) |>
    set_engine("glmnet") |>
    fit(bill_length_mm ~ ., data = penguins)

avg_slopes(mod, newdata = penguins)
# 
#               Term           Contrast Estimate
#  bill_depth_mm     dY/dX               0.00000
#  bill_length_mm    dY/dX               0.00000
#  body_mass_g       dY/dX               0.00142
#  flipper_length_mm dY/dX               0.14098
#  island            Dream - Biscoe      0.00000
#  island            Torgersen - Biscoe  0.00000
#  sex               male - female       0.00000
#  species           Chinstrap - Adelie  5.35902
#  species           Gentoo - Adelie     0.00000
# 
# Columns: term, contrast, estimate 
# Type:  numeric

Upvotes: 0

Related Questions