-
Notifications
You must be signed in to change notification settings - Fork 106
glmnet autoplot method for #642 #643
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
5ce561d
glmnet autoplot method
topepo 3e0b4aa
workflow methods
topepo 880ff96
add pkgdown entry
topepo 783d323
makes labels appear on best_penalty line if present
EmilHvitfeldt ab0b869
Merge branch 'main' into glmnet-autoplot
topepo 86b9448
Apply suggestions from code review
topepo c11c783
move ggrepl to suggests
topepo c1ec272
doc updates
topepo e10a6b9
anmespace functions and check for glmnet package
topepo 38db0d0
remove workflow method
topepo 45c796b
move ... up in order
topepo 56ea1c0
A note about ggrepl
topepo bfbc26a
more consistent test files
topepo 522e4ab
Merge branch 'main' into glmnet-autoplot
topepo 862b15b
fix nocov tags
topepo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,170 @@ | ||
| #' Create a ggplot for a model object | ||
| #' | ||
| #' This method provides a good visualization method for model results. | ||
| #' Currently, only methods for glmnet models are implemented. | ||
| #' | ||
| #' @param object A model fit object. | ||
| #' @param min_penalty A single, non-negative number for the smallest penalty | ||
| #' value that should be shown in the plot. If left `NULL`, the whole data | ||
| #' range is used. | ||
| #' @param best_penalty A single, non-negative number that will show a vertical | ||
| #' line marker. If left `NULL`, no line is shown. When this argument is used, | ||
| #' the \pkg{ggrepl} package is required. | ||
| #' @param top_n A non-negative integer for how many model predictors to label. | ||
| #' The top predictors are ranked by their absolute coefficient value. For | ||
| #' multinomial or multivariate models, the `top_n` terms are selected within | ||
| #' class or response, respectively. | ||
| #' @param ... For [autoplot.glmnet()], options to pass to | ||
| #' [ggrepel::geom_label_repel()]. Otherwise, this argument is ignored. | ||
| #' @return A ggplot object with penalty on the x-axis and coefficients on the | ||
| #' y-axis. For multinomial or multivariate models, the plot is faceted. | ||
| #' @details The \pkg{glmnet} package will need to be attached or loaded for | ||
| #' its `autoplot()` method to work correctly. | ||
| #' | ||
| # registered in zzz.R | ||
| autoplot.model_fit <- function(object, ...) { | ||
| autoplot(object$fit, ...) | ||
| } | ||
|
|
||
| # glmnet is not a formal dependency here. | ||
| # unit tests are located at https://github.com/tidymodels/extratests | ||
| # nocov start | ||
|
|
||
| # registered in zzz.R | ||
| #' @rdname autoplot.model_fit | ||
| autoplot.glmnet <- function(object, ..., min_penalty = 0, best_penalty = NULL, | ||
| top_n = 3L) { | ||
| autoplot_glmnet(object, min_penalty, best_penalty, top_n, ...) | ||
| } | ||
|
|
||
|
|
||
| map_glmnet_coefs <- function(x) { | ||
| coefs <- coef(x) | ||
| # If parsnip is used to fit the model, glmnet should be attached and this will | ||
| # work. If an object is loaded from a new session, they will need to load the | ||
| # package. | ||
| if (is.null(coefs)) { | ||
| rlang::abort("Please load the glmnet package before running `autoplot()`.") | ||
| } | ||
| p <- x$dim[1] | ||
| if (is.list(coefs)) { | ||
| classes <- names(coefs) | ||
| coefs <- purrr::map(coefs, reformat_coefs, p = p, penalty = x$lambda) | ||
| coefs <- purrr::map2_dfr(coefs, classes, ~ dplyr::mutate(.x, class = .y)) | ||
| } else { | ||
| coefs <- reformat_coefs(coefs, p = p, penalty = x$lambda) | ||
| } | ||
| coefs | ||
| } | ||
|
|
||
| reformat_coefs <- function(x, p, penalty) { | ||
| x <- as.matrix(x) | ||
| num_estimates <- nrow(x) | ||
| if (num_estimates > p) { | ||
| # The intercept is first | ||
| x <- x[-(num_estimates - p),, drop = FALSE] | ||
| } | ||
| term_lab <- rownames(x) | ||
| colnames(x) <- paste(seq_along(penalty)) | ||
| x <- tibble::as_tibble(x) | ||
| x$term <- term_lab | ||
| x <- tidyr::pivot_longer(x, cols = -term, names_to = "index", values_to = "estimate") | ||
| x$penalty <- rep(penalty, p) | ||
| x$index <- NULL | ||
| x | ||
| } | ||
|
|
||
| top_coefs <- function(x, top_n = 5) { | ||
| x %>% | ||
| dplyr::group_by(term) %>% | ||
| dplyr::arrange(term, dplyr::desc(abs(estimate))) %>% | ||
| dplyr::slice(1) %>% | ||
| dplyr::ungroup() %>% | ||
| dplyr::arrange(dplyr::desc(abs(estimate))) %>% | ||
| dplyr::slice(1:top_n) | ||
| } | ||
|
|
||
| autoplot_glmnet <- function(x, min_penalty = 0, best_penalty = NULL, top_n = 3L, ...) { | ||
| check_penalty_value(min_penalty) | ||
|
|
||
| tidy_coefs <- | ||
| map_glmnet_coefs(x) %>% | ||
| dplyr::filter(penalty >= min_penalty) | ||
|
|
||
| actual_min_penalty <- min(tidy_coefs$penalty) | ||
| num_terms <- length(unique(tidy_coefs$term)) | ||
| top_n <- min(top_n[1], num_terms) | ||
| if (top_n < 0) { | ||
| top_n <- 0 | ||
| } | ||
|
|
||
| has_groups <- any(names(tidy_coefs) == "class") | ||
|
|
||
| # Keep the large values | ||
| if (has_groups) { | ||
| label_coefs <- | ||
| tidy_coefs %>% | ||
| dplyr::group_nest(class) %>% | ||
| dplyr::mutate(data = purrr::map(data, top_coefs, top_n = top_n)) %>% | ||
| dplyr::select(class, data) %>% | ||
| tidyr::unnest(cols = data) | ||
| } else { | ||
| if (is.null(best_penalty)) { | ||
| label_coefs <- tidy_coefs %>% | ||
| top_coefs(top_n) | ||
| } else { | ||
| label_coefs <- tidy_coefs %>% | ||
| dplyr::filter(penalty > best_penalty) %>% | ||
| dplyr::filter(penalty == min(penalty)) %>% | ||
| dplyr::arrange(dplyr::desc(abs(estimate))) %>% | ||
| dplyr::slice(seq_len(top_n)) | ||
| } | ||
| } | ||
|
|
||
| label_coefs <- | ||
| label_coefs %>% | ||
| dplyr::mutate(penalty = best_penalty %||% actual_min_penalty) %>% | ||
| dplyr::mutate(label = gsub(".pred_no_", "", term)) | ||
|
|
||
| # plot the paths and highlight the large values | ||
| p <- | ||
| tidy_coefs %>% | ||
| ggplot2::ggplot(ggplot2::aes(x = penalty, y = estimate, group = term, col = term)) | ||
|
|
||
| if (has_groups) { | ||
| p <- p + ggplot2::facet_wrap(~ class) | ||
| } | ||
|
|
||
| if (!is.null(best_penalty)) { | ||
| check_penalty_value(best_penalty) | ||
| p <- p + ggplot2::geom_vline(xintercept = best_penalty, lty = 3) | ||
| } | ||
|
|
||
| p <- p + | ||
| ggplot2::geom_line(alpha = .4, show.legend = FALSE) + | ||
| ggplot2::scale_x_log10() | ||
|
|
||
| if(top_n > 0) { | ||
| rlang::check_installed("ggrepel") | ||
| p <- p + | ||
| ggrepel::geom_label_repel( | ||
| data = label_coefs, | ||
| ggplot2::aes(y = estimate, label = label), | ||
| show.legend = FALSE, | ||
| ... | ||
| ) | ||
| } | ||
| p | ||
| } | ||
|
|
||
| check_penalty_value <- function(x) { | ||
| cl <- match.call() | ||
| arg_val <- as.character(cl$x) | ||
| if (!is.vector(x) || length(x) != 1 || !is.numeric(x) || x < 0) { | ||
| msg <- paste0("Argument '", arg_val, "' should be a single, non-negative value.") | ||
| rlang::abort(msg) | ||
| } | ||
| invisible(x) | ||
| } | ||
|
|
||
| # nocov end | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,6 @@ | ||
| #' @importFrom ggplot2 autoplot | ||
| #' @export | ||
| ggplot2::autoplot | ||
|
|
||
| #' @importFrom magrittr %>% | ||
| #' @export | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am slightly uncomfortable with the idea that dots are passed all the way through to here. I would be more comfortable with an explicit argument for
repel_opts = named list()that gets passed through to here instead.Then the dots of this
autoplot()method would either be ignored or you would callrlang::check_dots_empty()to ensure the user didn't have any typosThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why is it uncomfortable? It seems like the most standard application of
...There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think just because it feels a bit arbitrary. Like, why not send the dots to
geom_line()instead, which also has plenty of options to tweak and is a larger part of the overall plot?I don't feel extremely strongly about this though