Debian Codegraph @

tests/testthat/test-glmnet.R

raw
1 skip_if_not_installed("modeltests")
2 library(modeltests)
3
4 skip_if_not_installed("glmnet")
5 suppressPackageStartupMessages(library(glmnet))
6
7 set.seed(27)
8
9 x <- matrix(rnorm(100 * 20), 100, 20)
10 y <- rnorm(100)
11 g <- sample(1:4, 100, replace = TRUE)
12
13 fit <- glmnet(x, y)
14 fit2 <- glmnet(x, g, family = "multinomial")
15
16 cv_fit <- cv.glmnet(x, y)
17 cv_fit2 <- cv.glmnet(x, g, family = "multinomial")
18
19 test_that("glmnet tidier arguments", {
20 check_arguments(tidy.glmnet)
21 check_arguments(glance.glmnet)
22
23 check_arguments(tidy.cv.glmnet)
24 check_arguments(glance.cv.glmnet)
25 })
26
27 test_that("tidy.glmnet", {
28 td <- tidy(fit)
29 tdz <- tidy(fit, return_zeros = TRUE)
30
31 check_tidy_output(td)
32 check_tidy_output(tdz)
33
34 check_dims(td, expected_cols = 5)
35 check_dims(tdz, expected_cols = 5)
36
37 expect_true(all(td$estimate != 0))
38 expect_true(any(tdz$estimate == 0))
39
40 # multinomial
41
42 td2 <- tidy(fit2)
43 td2z <- tidy(fit2, return_zeros = TRUE)
44
45 check_tidy_output(td2)
46 check_tidy_output(td2z)
47
48 expect_true(all(td2$estimate != 0))
49 expect_true(any(td2z$estimate == 0))
50
51 # regression tests
52 expect_true(is.numeric(td$step) && !any(is.na(td$step)))
53 expect_true(is.numeric(td2$step) && !any(is.na(td2$step)))
54 })
55
56 test_that("glance.glmnet", {
57 gl <- glance(fit)
58 gl2 <- glance(fit2)
59
60 check_glance_outputs(gl, gl2)
61 })
62
63 test_that("tidy.cv.glmnet", {
64 td <- tidy(cv_fit)
65
66 check_tidy_output(td)
67 check_dims(td, expected_cols = 6)
68
69 # multinomial
70
71 td2 <- tidy(cv_fit2)
72
73 check_tidy_output(td2)
74 check_dims(td2, expected_cols = 6)
75 })
76
77 test_that("glance.cv.glmnet", {
78 gl <- glance(cv_fit)
79 gl2 <- glance(cv_fit2)
80
81 check_glance_outputs(gl, gl2)
82 })