|
| 1 | +#' tidy methods for glmnet models |
| 2 | +#' |
| 3 | +#' `tidy()` methods for the various `glmnet` models that return the coefficients |
| 4 | +#' for the specific penalty value used by the `parsnip` model fit. |
| 5 | +#' @param x A fitted `parsnip` model that used the `glmnet` engine. |
| 6 | +#' @param penalty A _single_ numeric value. If none is given, the value specified |
| 7 | +#' in the model specification is used. |
| 8 | +#' @param ... Not used |
| 9 | +#' @return A tibble with columns `term`, `estimate`, and `penalty`. When a |
| 10 | +#' multinomial mode is used, an additional `class` column is included. |
| 11 | +#' @importFrom stats coef |
| 12 | +#' @export |
| 13 | +tidy._elnet <- function(x, penalty = NULL, ...) { |
| 14 | + tidy_glmnet(x, penalty) |
| 15 | +} |
| 16 | + |
| 17 | +#' @export |
| 18 | +#' @rdname tidy._elnet |
| 19 | +tidy._lognet <- function(x, penalty = NULL, ...) { |
| 20 | + tidy_glmnet(x, penalty) |
| 21 | +} |
| 22 | + |
| 23 | +#' @export |
| 24 | +#' @rdname tidy._elnet |
| 25 | +tidy._multnet <- function(x, penalty = NULL, ...) { |
| 26 | + tidy_glmnet(x, penalty) |
| 27 | +} |
| 28 | + |
| 29 | +#' @export |
| 30 | +#' @rdname tidy._elnet |
| 31 | +tidy._fishnet <- function(x, penalty = NULL, ...) { |
| 32 | + tidy_glmnet(x, penalty) |
| 33 | +} |
| 34 | + |
| 35 | +## ----------------------------------------------------------------------------- |
| 36 | + |
| 37 | +get_glmn_coefs <- function(x, penalty = 0.01) { |
| 38 | + res <- coef(x, s = penalty) |
| 39 | + res <- as.matrix(res) |
| 40 | + colnames(res) <- "estimate" |
| 41 | + rn <- rownames(res) |
| 42 | + res <- tibble::as_tibble(res) %>% mutate(term = rn, penalty = penalty) |
| 43 | + res <- dplyr::select(res, term, estimate, penalty) |
| 44 | + if (is.list(res$estimate)) { |
| 45 | + res$estimate <- purrr::map(res$estimate, ~ as_tibble(as.matrix(.x), rownames = "term")) |
| 46 | + res <- tidyr::unnest(res, cols = c(estimate), names_repair = "minimal") |
| 47 | + names(res) <- c("class", "term", "estimate", "penalty") |
| 48 | + } |
| 49 | + res |
| 50 | +} |
| 51 | + |
| 52 | +tidy_glmnet <- function(x, penalty = NULL, ...) { |
| 53 | + check_installs(x$spec) |
| 54 | + load_libs(x$spec, quiet = TRUE, attach = TRUE) |
| 55 | + if (is.null(penalty)) { |
| 56 | + if (isTRUE(is.numeric(x$spec$args$penalty))){ |
| 57 | + penalty <- x$spec$args$penalty |
| 58 | + } else { |
| 59 | + rlang::abort("Please pick a single value of `penalty`.") |
| 60 | + } |
| 61 | + } |
| 62 | + get_glmn_coefs(x$fit, penalty = penalty) |
| 63 | +} |
0 commit comments