-
Notifications
You must be signed in to change notification settings - Fork 89
/
glmnet-engines.R
425 lines (353 loc) · 12.1 KB
/
glmnet-engines.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# glmnet call stack using `predict()` when object has
# classes "_<glmnet-class>" and "model_fit":
#
# predict()
# predict._<glmnet-class>(penalty = NULL)
# predict_glmnet(penalty = NULL) <-- checks and sets penalty
# predict.model_fit() <-- checks for extra vars in ...
# predict_numeric()
# predict_numeric._<glmnet-class>()
# predict_numeric_glmnet()
# predict_numeric.model_fit()
# predict.<glmnet-class>()
# glmnet call stack using `multi_predict` when object has
# classes "_<glmnet-class>" and "model_fit":
#
# multi_predict()
# multi_predict._<glmnet-class>(penalty = NULL)
# predict._<glmnet-class>(multi = TRUE)
# predict_glmnet(multi = TRUE) <-- checks and sets penalty
# predict.model_fit() <-- checks for extra vars in ...
# predict_raw()
# predict_raw._<glmnet-class>()
# predict_raw_glmnet()
# predict_raw.model_fit(opts = list(s = penalty))
# predict.<glmnet-class>()
predict_glmnet <- function(object,
new_data,
type = NULL,
opts = list(),
penalty = NULL,
multi = FALSE,
...) {
# See discussion in https://github.com/tidymodels/parsnip/issues/195
if (is.null(penalty) & !is.null(object$spec$args$penalty)) {
penalty <- object$spec$args$penalty
}
object$spec$args$penalty <- .check_glmnet_penalty_predict(penalty, object, multi)
object$spec <- eval_args(object$spec)
predict.model_fit(object, new_data = new_data, type = type, opts = opts, ...)
}
predict_numeric_glmnet <- function(object, new_data, ...) {
object$spec <- eval_args(object$spec)
predict_numeric.model_fit(object, new_data = new_data, ...)
}
predict_class_glmnet <- function(object, new_data, ...) {
object$spec <- eval_args(object$spec)
predict_class.model_fit(object, new_data = new_data, ...)
}
predict_classprob_glmnet <- function(object, new_data, ...) {
object$spec <- eval_args(object$spec)
predict_classprob.model_fit(object, new_data = new_data, ...)
}
predict_raw_glmnet <- function(object, new_data, opts = list(), ...) {
object$spec <- eval_args(object$spec)
opts$s <- object$spec$args$penalty
predict_raw.model_fit(object, new_data = new_data, opts = opts, ...)
}
# translation of glmnet classes to parsnip models
# elnet ~ linear_reg
# lognet ~ logistic_reg
# multnet ~ multinom_reg
# glmnetfit: that's a catch-all class for glmnet models fitted with a base-R
# family, thus can be any of linear_reg, logistic_reg, multinom_reg, poisson_reg
#' @export
predict._elnet <- predict_glmnet
#' @export
predict_numeric._elnet <- predict_numeric_glmnet
#' @export
predict_raw._elnet <- predict_raw_glmnet
#' @export
predict._lognet <- predict_glmnet
#' @export
predict_class._lognet <- predict_class_glmnet
#' @export
predict_classprob._lognet <- predict_classprob_glmnet
#' @export
predict_raw._lognet <- predict_raw_glmnet
#' @export
predict._multnet <- predict_glmnet
#' @export
predict_class._multnet <- predict_class_glmnet
#' @export
predict_classprob._multnet <- predict_classprob_glmnet
#' @export
predict_raw._multnet <- predict_raw_glmnet
#' @export
predict._glmnetfit <- predict_glmnet
#' @export
predict_numeric._glmnetfit <- predict_numeric_glmnet
#' @export
predict_class._glmnetfit <- predict_class_glmnet
#' @export
predict_classprob._glmnetfit <- predict_classprob_glmnet
#' @export
predict_raw._glmnetfit <- predict_raw_glmnet
#' Organize glmnet predictions
#'
#' This function is for developer use and organizes predictions from glmnet
#' models.
#'
#' @param x Predictions as returned by the `predict()` method for glmnet models.
#' @param object An object of class `model_fit`.
#'
#' @rdname glmnet_helpers_prediction
#' @keywords internal
#' @export
.organize_glmnet_pred <- function(x, object) {
unname(x[, 1])
}
organize_glmnet_class <- function(x, object) {
prob_to_class_2(x[, 1], object)
}
organize_glmnet_prob <- function(x, object) {
res <- tibble(v1 = 1 - x[, 1], v2 = x[, 1])
colnames(res) <- object$lvl
res
}
organize_multnet_class <- function(x, object) {
if (vec_size(x) > 1) {
x <- x[,1]
} else {
x <- as.character(x)
}
x
}
organize_multnet_prob <- function(x, object) {
if (vec_size(x) > 1) {
x <- as_tibble(x[,,1])
} else {
x <- tibble::as_tibble_row(x[,,1])
}
x
}
# -------------------------------------------------------------------------
multi_predict_glmnet <- function(object,
new_data,
type = NULL,
penalty = NULL,
...) {
if (any(names(enquos(...)) == "newdata")) {
rlang::abort("Did you mean to use `new_data` instead of `newdata`?")
}
if (object$spec$mode == "classification") {
if (is_quosure(penalty)) {
penalty <- eval_tidy(penalty)
}
}
dots <- list(...)
object$spec <- eval_args(object$spec)
if (is.null(penalty)) {
# See discussion in https://github.com/tidymodels/parsnip/issues/195
if (!is.null(object$spec$args$penalty)) {
penalty <- object$spec$args$penalty
} else {
penalty <- object$fit$lambda
}
}
model_type <- class(object$spec)[1]
if (object$spec$mode == "classification") {
if (is.null(type)) {
type <- "class"
}
if (!(type %in% c("class", "prob", "link", "raw"))) {
rlang::abort("`type` should be either 'class', 'link', 'raw', or 'prob'.")
}
if (type == "prob" |
model_type == "logistic_reg") {
dots$type <- "response"
} else {
dots$type <- type
}
}
pred <- predict(object, new_data = new_data, type = "raw",
opts = dots, penalty = penalty, multi = TRUE)
res <- switch(
model_type,
"linear_reg" = format_glmnet_multi_linear_reg(pred, penalty = penalty),
"logistic_reg" = format_glmnet_multi_logistic_reg(pred,
penalty = penalty,
type = type,
lvl = object$lvl),
"multinom_reg" = format_glmnet_multi_multinom_reg(pred,
penalty = penalty,
type = type,
n_rows = nrow(new_data),
lvl = object$lvl)
)
res
}
#' @export
#' @rdname multi_predict
#' @param penalty A numeric vector of penalty values.
multi_predict._elnet <- multi_predict_glmnet
#' @export
#' @rdname multi_predict
multi_predict._lognet <- multi_predict_glmnet
#' @export
#' @rdname multi_predict
multi_predict._multnet <- multi_predict_glmnet
#' @export
multi_predict._glmnetfit <- multi_predict_glmnet
format_glmnet_multi_linear_reg <- function(pred, penalty) {
param_key <- tibble(group = colnames(pred), penalty = penalty)
pred <- as_tibble(pred)
pred$.row <- 1:nrow(pred)
pred <- gather(pred, group, .pred, -.row)
if (utils::packageVersion("dplyr") >= "1.0.99.9000") {
pred <- full_join(param_key, pred, by = "group", multiple = "all")
} else {
pred <- full_join(param_key, pred, by = "group")
}
pred$group <- NULL
pred <- arrange(pred, .row, penalty)
.row <- pred$.row
pred$.row <- NULL
pred <- split(pred, .row)
names(pred) <- NULL
tibble(.pred = pred)
}
format_glmnet_multi_logistic_reg <- function(pred, penalty, type, lvl) {
type <- rlang::arg_match(type, c("class", "prob"))
penalty_key <- tibble(s = colnames(pred), penalty = penalty)
pred <- as_tibble(pred)
pred$.row <- seq_len(nrow(pred))
pred <- tidyr::pivot_longer(pred, -.row, names_to = "s", values_to = ".pred")
if (type == "class") {
pred <- pred %>%
dplyr::mutate(.pred_class = dplyr::if_else(.pred >= 0.5, lvl[2], lvl[1]),
.pred_class = factor(.pred_class, levels = lvl),
.keep = "unused")
} else {
pred <- pred %>%
dplyr::mutate(.pred_class_2 = 1 - .pred) %>%
rlang::set_names(c(".row", "s", paste0(".pred_", rev(lvl)))) %>%
dplyr::select(c(".row", "s", paste0(".pred_", lvl)))
}
if (utils::packageVersion("dplyr") >= "1.0.99.9000") {
pred <- dplyr::full_join(penalty_key, pred, by = "s", multiple = "all")
} else {
pred <- dplyr::full_join(penalty_key, pred, by = "s")
}
pred <- pred %>%
dplyr::select(-s) %>%
dplyr::arrange(penalty) %>%
tidyr::nest(.by = .row, .key = ".pred") %>%
dplyr::select(-.row)
pred
}
format_glmnet_multi_multinom_reg <- function(pred, penalty, type, n_rows, lvl) {
format_probs <- function(x) {
x <- as_tibble(x)
names(x) <- paste0(".pred_", names(x))
nms <- names(x)
x$.row <- 1:nrow(x)
x[, c(".row", nms)]
}
if (type == "prob") {
pred <- apply(pred, 3, format_probs)
names(pred) <- NULL
pred <- map_dfr(pred, function(x) x)
pred$penalty <- rep(penalty, each = n_rows)
pred <- dplyr::relocate(pred, penalty)
} else {
pred <-
tibble(
.row = rep(1:n_rows, length(penalty)),
penalty = rep(penalty, each = n_rows),
.pred_class = factor(as.vector(pred), levels = lvl)
)
}
pred <- arrange(pred, .row, penalty)
.row <- pred$.row
pred$.row <- NULL
pred <- split(pred, .row)
names(pred) <- NULL
tibble(.pred = pred)
}
# -------------------------------------------------------------------------
#' Helper functions for checking the penalty of glmnet models
#'
#' @description
#' These functions are for developer use.
#'
#' `.check_glmnet_penalty_fit()` checks that the model specification for fitting a
#' glmnet model contains a single value.
#'
#' `.check_glmnet_penalty_predict()` checks that the penalty value used for prediction is valid.
#' If called by `predict()`, it needs to be a single value. Multiple values are
#' allowed for `multi_predict()`.
#'
#' @param x An object of class `model_spec`.
#' @rdname glmnet_helpers
#' @keywords internal
#' @export
.check_glmnet_penalty_fit <- function(x) {
pen <- rlang::eval_tidy(x$args$penalty)
if (length(pen) != 1) {
rlang::abort(c(
"For the glmnet engine, `penalty` must be a single number (or a value of `tune()`).",
glue::glue("There are {length(pen)} values for `penalty`."),
"To try multiple values for total regularization, use the tune package.",
"To predict multiple penalties, use `multi_predict()`"
))
}
}
#' @param penalty A penalty value to check.
#' @param object An object of class `model_fit`.
#' @param multi A logical indicating if multiple values are allowed.
#'
#' @rdname glmnet_helpers
#' @keywords internal
#' @export
.check_glmnet_penalty_predict <- function(penalty = NULL, object, multi = FALSE) {
if (is.null(penalty)) {
penalty <- object$fit$lambda
}
# when using `predict()`, allow for a single lambda
if (!multi) {
if (length(penalty) != 1) {
rlang::abort(
glue::glue(
"`penalty` should be a single numeric value. `multi_predict()` ",
"can be used to get multiple predictions per row of data.",
)
)
}
}
if (length(object$fit$lambda) == 1 && penalty != object$fit$lambda) {
rlang::abort(
glue::glue(
"The glmnet model was fit with a single penalty value of ",
"{object$fit$lambda}. Predicting with a value of {penalty} ",
"will give incorrect results from `glmnet()`."
)
)
}
penalty
}
set_glmnet_penalty_path <- function(x) {
if (any(names(x$eng_args) == "path_values")) {
# Since we decouple the parsnip `penalty` argument from being the same
# as the glmnet `lambda` value, `path_values` allows users to set the
# path differently from the default that glmnet uses. See
# https://github.com/tidymodels/parsnip/issues/431
x$method$fit$args$lambda <- x$eng_args$path_values
x$eng_args$path_values <- NULL
x$method$fit$args$path_values <- NULL
} else {
# See discussion in https://github.com/tidymodels/parsnip/issues/195
x$method$fit$args$lambda <- NULL
}
x
}