Debian Codegraph @

R/glmnet-cv-glmnet.R

raw
1 #' @templateVar class cv.glmnet
2 #' @template title_desc_tidy
3 #'
4 #' @param x A `cv.glmnet` object returned from [glmnet::cv.glmnet()].
5 #' @template param_unused_dots
6 #'
7 #' @evalRd return_tidy(
8 #' "lambda",
9 #' "std.error",
10 #' "nzero",
11 #' conf.low = "lower bound on confidence interval for cross-validation
12 #' estimated loss.",
13 #' conf.high = "upper bound on confidence interval for cross-validation
14 #' estimated loss.",
15 #' estimate = "Median loss across all cross-validation folds for a given
16 #' lamdba"
17 #' )
18 #'
19 #' @examplesIf rlang::is_installed(c("glmnet", "ggplot2"))
20 #'
21 #' # load libraries for models and data
22 #' library(glmnet)
23 #'
24 #' set.seed(27)
25 #'
26 #' nobs <- 100
27 #' nvar <- 50
28 #' real <- 5
29 #'
30 #' x <- matrix(rnorm(nobs * nvar), nobs, nvar)
31 #' beta <- c(rnorm(real, 0, 1), rep(0, nvar - real))
32 #' y <- c(t(beta) %*% t(x)) + rnorm(nvar, sd = 3)
33 #'
34 #' cvfit1 <- cv.glmnet(x, y)
35 #'
36 #' tidy(cvfit1)
37 #' glance(cvfit1)
38 #'
39 #' library(ggplot2)
40 #'
41 #' tidied_cv <- tidy(cvfit1)
42 #' glance_cv <- glance(cvfit1)
43 #'
44 #' # plot of MSE as a function of lambda
45 #' g <- ggplot(tidied_cv, aes(lambda, estimate)) +
46 #' geom_line() +
47 #' scale_x_log10()
48 #' g
49 #'
50 #' # plot of MSE as a function of lambda with confidence ribbon
51 #' g <- g + geom_ribbon(aes(ymin = conf.low, ymax = conf.high), alpha = .25)
52 #' g
53 #'
54 #' # plot of MSE as a function of lambda with confidence ribbon and choices
55 #' # of minimum lambda marked
56 #' g <- g +
57 #' geom_vline(xintercept = glance_cv$lambda.min) +
58 #' geom_vline(xintercept = glance_cv$lambda.1se, lty = 2)
59 #' g
60 #'
61 #' # plot of number of zeros for each choice of lambda
62 #' ggplot(tidied_cv, aes(lambda, nzero)) +
63 #' geom_line() +
64 #' scale_x_log10()
65 #'
66 #' # coefficient plot with min lambda shown
67 #' tidied <- tidy(cvfit1$glmnet.fit)
68 #'
69 #' ggplot(tidied, aes(lambda, estimate, group = term)) +
70 #' scale_x_log10() +
71 #' geom_line() +
72 #' geom_vline(xintercept = glance_cv$lambda.min) +
73 #' geom_vline(xintercept = glance_cv$lambda.1se, lty = 2)
74 #'
75 #' @export
76 #' @family glmnet tidiers
77 #' @seealso [tidy()], [glmnet::cv.glmnet()]
78 tidy.cv.glmnet <- function(x, ...) {
79 with(
80 x,
81 tibble(
82 lambda = lambda,
83 estimate = cvm,
84 std.error = cvsd,
85 conf.low = cvlo,
86 conf.high = cvup,
87 nzero = nzero
88 )
89 )
90 }
91
92 #' @templateVar class cv.glmnet
93 #' @template title_desc_glance
94 #'
95 #' @inherit tidy.cv.glmnet params examples
96 #'
97 #' @evalRd return_glance("lambda.min", "lambda.1se", "nobs")
98 #'
99 #' @export
100 #' @seealso [glance()], [glmnet::cv.glmnet()]
101 #' @family glmnet tidiers
102 glance.cv.glmnet <- function(x, ...) {
103 as_glance_tibble(
104 lambda.min = x$lambda.min,
105 lambda.1se = x$lambda.1se,
106 nobs = stats::nobs(x),
107 na_types = "rri"
108 )
109 }