forked from tidymodels/recipes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnnmf_sparse.R
266 lines (247 loc) · 7.67 KB
/
nnmf_sparse.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
#' Non-Negative Matrix Factorization Signal Extraction with lasso Penalization
#'
#' `step_nnmf_sparse()` creates a *specification* of a recipe step
#' that will convert numeric data into one or more non-negative
#' components.
#'
#' @inheritParams step_pca
#' @inheritParams step_center
#' @param penalty A non-negative number used as a penalization factor for the
#' loadings. Values are usually between zero and one.
#' @param options A list of options to `nmf()` in the RcppML package. That
#' package has a separate function `setRcppMLthreads()` that controls the
#' amount of internal parallelization. **Note** that the argument `A`, `k`,
#' `L1`, and `seed` should not be passed here.
#' @param res A matrix of loadings is stored here, along with the names of the
#' original predictors, once this preprocessing step has been trained by
#' [prep()].
#' @param seed An integer that will be used to set the seed in isolation when
#' computing the factorization.
#' @template step-return
#' @family multivariate transformation steps
#' @export
#' @details Non-negative matrix factorization computes latent components that
#' have non-negative values and take into account that the original data have
#' non-negative values.
#'
#' The argument `num_comp` controls the number of components that will be
#' retained (the original variables that are used to derive the components are
#' removed from the data). The new components will have names that begin with
#' `prefix` and a sequence of numbers. The variable names are padded with
#' zeros. For example, if `num < 10`, their names will be `NNMF1` - `NNMF9`. If
#' `num = 101`, the names would be `NNMF001` - `NNMF101`.
#'
#' # Tidying
#'
#' When you [`tidy()`][tidy.recipe()] this step, a tibble with column
#' `terms` (the selectors or variables selected) and the number of
#' components is returned.
#'
#' @template case-weights-not-supported
#'
#' @examplesIf rlang::is_installed(c("modeldata", "RcppML", "ggplot2"))
#' library(Matrix)
#' data(biomass, package = "modeldata")
#'
#' rec <- recipe(HHV ~ ., data = biomass) %>%
#' update_role(sample, new_role = "id var") %>%
#' update_role(dataset, new_role = "split variable") %>%
#' step_nnmf_sparse(
#' all_numeric_predictors(),
#' num_comp = 2,
#' seed = 473,
#' penalty = 0.01
#' ) %>%
#' prep(training = biomass)
#'
#' bake(rec, new_data = NULL)
#' #'
#' library(ggplot2)
#' bake(rec, new_data = NULL) %>%
#' ggplot(aes(x = NNMF2, y = NNMF1, col = HHV)) +
#' geom_point()
step_nnmf_sparse <-
function(recipe,
...,
role = "predictor",
trained = FALSE,
num_comp = 2,
penalty = 0.001,
options = list(),
res = NULL,
prefix = "NNMF",
seed = sample.int(10^5, 1),
keep_original_cols = FALSE,
skip = FALSE,
id = rand_id("nnmf_sparse")) {
recipes_pkg_check(required_pkgs.step_nnmf_sparse())
add_step(
recipe,
step_nnmf_sparse_new(
terms = ellipse_check(...),
role = role,
trained = trained,
num_comp = num_comp,
penalty = penalty,
options = options,
res = res,
prefix = prefix,
seed = seed,
keep_original_cols = keep_original_cols,
skip = skip,
id = id
)
)
}
step_nnmf_sparse_new <-
function(terms, role, trained, num_comp, penalty, options, res,
prefix, seed, keep_original_cols, skip, id) {
step(
subclass = "nnmf_sparse",
terms = terms,
role = role,
trained = trained,
num_comp = num_comp,
penalty = penalty,
options = options,
res = res,
prefix = prefix,
seed = seed,
keep_original_cols = keep_original_cols,
skip = skip,
id = id
)
}
tibble_to_sparse <- function(x, transp = FALSE) {
x <- as.matrix(x)
if (transp) {
x <- t(x)
}
Matrix::Matrix(x, sparse = TRUE)
}
nnmf_pen_call <- function(x) {
opts <-
list(
A = expr(dat),
k = x$num_comp,
L1 = c(x$penalty, x$penalty),
verbose = FALSE,
seed = x$seed,
nonneg = TRUE
)
cl <- rlang::call2("nmf", .ns = "RcppML", !!!opts)
user_opts <- x$opt
cl <- rlang::call_modify(cl, !!!user_opts)
cl
}
#' @export
prep.step_nnmf_sparse <- function(x, training, info = NULL, ...) {
col_names <- recipes_eval_select(x$terms, training, info)
check_type(training[, col_names])
if (x$num_comp > 0) {
x$num_comp <- min(x$num_comp, length(col_names))
dat <- tibble_to_sparse(training[, col_names], transp = TRUE)
cl <- nnmf_pen_call(x)
nnm <- try(rlang::eval_tidy(cl), silent = TRUE)
if (inherits(nnm, "try-error")) {
rlang::abort(paste0("`step_nnmf_sparse` failed with error:\n", as.character(nnm)))
} else {
na_w <- sum(is.na(nnm$w))
if (na_w > 0) {
rlang::abort("The NNMF loadings are missing. The penalty may have been to high.")
} else {
nnm <- list(x_vars = col_names, w = nnm$w)
rownames(nnm$w) <- col_names
colnames(nnm$w) <- names0(ncol(nnm$w), x$prefix)
}
}
} else {
nnm <- list(x_vars = col_names, w = NULL)
}
step_nnmf_sparse_new(
terms = x$terms,
role = x$role,
trained = TRUE,
num_comp = x$num_comp,
penalty = x$penalty,
options = x$options,
res = nnm,
prefix = x$prefix,
seed = x$seed,
keep_original_cols = get_keep_original_cols(x),
skip = x$skip,
id = x$id
)
}
#' @export
bake.step_nnmf_sparse <- function(object, new_data, ...) {
if (object$num_comp > 0) {
proj_data <- as.matrix(new_data[, object$res$x_vars, drop = FALSE])
proj_data <- proj_data %*% object$res$w
colnames(proj_data) <- names0(ncol(proj_data), object$prefix)
new_data <- bind_cols(new_data, as_tibble(proj_data))
keep_original_cols <- get_keep_original_cols(object)
if (!keep_original_cols) {
new_data <- new_data[, !(colnames(new_data) %in% object$res$x_vars), drop = FALSE]
}
}
new_data
}
print.step_nnmf_sparse <- function(x, width = max(20, options()$width - 29), ...) {
if (x$trained) {
if (x$num_comp == 0) {
title <- "No non-negative matrix factorization was extracted from "
} else {
title <- "Non-negative matrix factorization for "
}
columns <- names(x$res$x_vars)
} else {
title <- "Non-negative matrix factorization for "
}
print_step(columns, x$terms, x$trained, title, width)
invisible(x)
}
#' @rdname tidy.recipe
#' @param x A `step_nnmf_sparse` object.
tidy.step_nnmf_sparse <- function(x, ...) {
if (is_trained(x)) {
if (x$num_comp > 0) {
res <- x$res$w
var_nms <- rownames(res)
res <- tibble::as_tibble(res)
res$terms <- var_nms
res <- tidyr::pivot_longer(res,
cols = c(-terms),
names_to = "component", values_to = "value"
)
res <- res[, c("terms", "value", "component")]
res <- res[order(res$component, res$terms), ]
} else {
res <- tibble(terms = x$res$x_vars, value = na_dbl, component = na_chr)
}
} else {
term_names <- sel2char(x$terms)
res <- tibble(terms = term_names, value = na_dbl, component = x$num_comp)
}
res$id <- x$id
res
}
# ------------------------------------------------------------------------------
#' @export
tunable.step_nnmf_sparse <- function(x, ...) {
tibble::tibble(
name = c("num_comp", "penalty"),
call_info = list(
list(pkg = "dials", fun = "num_comp", range = c(1L, 4L)),
list(pkg = "dials", fun = "penalty")
),
source = "recipe",
component = "step_nnmf_sparse",
component_id = x$id
)
}
#' @rdname required_pkgs.recipe
#' @export
required_pkgs.step_nnmf_sparse <- function(x, ...) {
c("Matrix", "RcppML")
}