Debian Codegraph @

R/glmnet-glmnet.R

raw
1 #' @templateVar class glmnet
2 #' @template title_desc_tidy
3 #'
4 #' @param x A `glmnet` object returned from [glmnet::glmnet()].
5 #' @param return_zeros Logical indicating whether coefficients with value zero
6 #' zero should be included in the results. Defaults to `FALSE`.
7 #' @template param_unused_dots
8 #'
9 #' @evalRd return_tidy(
10 #' "term",
11 #' "step",
12 #' "estimate",
13 #' "lambda",
14 #' "dev.ratio"
15 #' )
16 #'
17 #' @details Note that while this representation of GLMs is much easier
18 #' to plot and combine than the default structure, it is also much
19 #' more memory-intensive. Do not use for large, sparse matrices.
20 #'
21 #' No `augment` method is yet provided even though the model produces
22 #' predictions, because the input data is not tidy (it is a matrix that
23 #' may be very wide) and therefore combining predictions with it is not
24 #' logical. Furthermore, predictions make sense only with a specific
25 #' choice of lambda.
26 #'
27 # sometimes triggers CRAN NOTE `elapsed time > 10s`
28 #' @examplesIf FALSE
29 #'
30 #' # load libraries for models and data
31 #' library(glmnet)
32 #'
33 #' set.seed(2014)
34 #' x <- matrix(rnorm(100 * 20), 100, 20)
35 #' y <- rnorm(100)
36 #' fit1 <- glmnet(x, y)
37 #'
38 #' # summarize model fit with tidiers + visualization
39 #' tidy(fit1)
40 #' glance(fit1)
41 #'
42 #' library(dplyr)
43 #' library(ggplot2)
44 #'
45 #' tidied <- tidy(fit1) |> filter(term != "(Intercept)")
46 #'
47 #' ggplot(tidied, aes(step, estimate, group = term)) +
48 #' geom_line()
49 #'
50 #' ggplot(tidied, aes(lambda, estimate, group = term)) +
51 #' geom_line() +
52 #' scale_x_log10()
53 #'
54 #' ggplot(tidied, aes(lambda, dev.ratio)) +
55 #' geom_line()
56 #'
57 #' # works for other types of regressions as well, such as logistic
58 #' g2 <- sample(1:2, 100, replace = TRUE)
59 #' fit2 <- glmnet(x, g2, family = "binomial")
60 #' tidy(fit2)
61 #'
62 #' @export
63 #' @aliases glmnet_tidiers
64 #' @family glmnet tidiers
65 #' @seealso [tidy()], [glmnet::glmnet()]
66 tidy.glmnet <- function(x, return_zeros = FALSE, ...) {
67 beta <- coef(x)
68
69 if (inherits(x, "multnet")) {
70 beta_d <- purrr::map_df(
71 beta,
72 function(b) {
73 as_tidy_tibble(as.matrix(b), new_names = 1:ncol(b))
74 },
75 .id = "class"
76 )
77 ret <- beta_d |>
78 pivot_longer(
79 cols = c(everything(), -term, -class),
80 names_to = "step",
81 values_to = "estimate"
82 )
83 } else {
84 beta_d <- as_tidy_tibble(
85 as.matrix(beta),
86 new_names = 1:ncol(beta)
87 )
88
89 ret <- pivot_longer(
90 beta_d,
91 cols = c(dplyr::everything(), -term),
92 names_to = "step",
93 values_to = "estimate"
94 )
95 }
96 # add values specific to each step
97 ret <- ret |>
98 mutate(
99 step = as.numeric(step),
100 lambda = x$lambda[step],
101 dev.ratio = x$dev.ratio[step]
102 )
103
104 if (!return_zeros) {
105 ret <- filter(ret, estimate != 0)
106 }
107
108 as_tibble(ret)
109 }
110
111
112 #' @templateVar class glmnet
113 #' @template title_desc_glance
114 #'
115 #' @inherit tidy.glmnet params examples
116 #'
117 #' @evalRd return_glance("nulldev", "npasses", "nobs")
118 #'
119 #' @export
120 #' @family glmnet tidiers
121 #' @seealso [glance()], [glmnet::glmnet()]
122 glance.glmnet <- function(x, ...) {
123 as_glance_tibble(
124 nulldev = x$nulldev,
125 npasses = x$npasses,
126 nobs = stats::nobs(x),
127 na_types = "rii"
128 )
129 }