-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathtune_race_win_loss.R
348 lines (315 loc) · 11.1 KB
/
tune_race_win_loss.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
#' Efficient grid search via racing with win/loss statistics
#'
#' [tune_race_win_loss()] computes a set of performance metrics (e.g. accuracy or RMSE)
#' for a pre-defined set of tuning parameters that correspond to a model or
#' recipe across one or more resamples of the data. After an initial number of
#' resamples have been evaluated, the process eliminates tuning parameter
#' combinations that are unlikely to be the best results using a statistical
#' model. For each pairwise combinations of tuning parameters, win/loss
#' statistics are calculated and a logistic regression model is used to measure
#' how likely each combination is to win overall.
#'
#' @inheritParams tune_race_anova
#' @references
#' Kuhn, M 2014. "Futility Analysis in the Cross-Validation of Machine Learning
#' Models." \url{https://arxiv.org/abs/1405.6974}.
#' @param ... Not currently used.
#' @details
#' The technical details of this method are described in Kuhn (2014).
#'
#' Racing methods are efficient approaches to grid search. Initially, the
#' function evaluates all tuning parameters on a small initial set of
#' resamples. The `burn_in` argument of [control_race()] sets the number of
#' initial resamples.
#'
#' The performance statistics from the current set of resamples are converted
#' to win/loss/tie results. For example, for two parameters (`j` and `k`) in a
#' classification model that have each been resampled three times:
#'
#' \preformatted{
#' | area under the ROC curve |
#' -----------------------------
#' resample | parameter j | parameter k | winner
#' ---------------------------------------------
#' 1 | 0.81 | 0.92 | k
#' 2 | 0.95 | 0.94 | j
#' 3 | 0.79 | 0.81 | k
#' ---------------------------------------------
#' }
#'
#' After the third resample, parameter `k` has a 2:1 win/loss ratio versus `j`.
#' Parameters with equal results are treated as a half-win for each setting.
#' These statistics are determined for all pairwise combinations of the
#' parameters and a Bradley-Terry model is used to model these win/loss/tie
#' statistics. This model can compute the ability of a parameter combination to
#' win overall. A confidence interval for the winning ability is computed and
#' any settings whose interval includes zero are retained for future resamples
#' (since it is not statistically different form the best results).
#'
#'
#' The next resample is used with the remaining parameter combinations and the
#' statistical analysis is updated. More candidate parameters may be excluded
#' with each new resample that is processed.
#'
#' The [control_race()] function contains are parameter for the significance cutoff
#' applied to the Bradley-Terry model results as well as other relevant arguments.
#'
#' ## Censored regression models
#'
#' With dynamic performance metrics (e.g. Brier or ROC curves), performance is
#' calculated for every value of `eval_time` but the _first_ evaluation time
#' given by the user (e.g., `eval_time[1]`) is analyzed during racing.
#'
#' Also, values of `eval_time` should be less than the largest observed event
#' time in the training data. For many non-parametric models, the results beyond
#' the largest time corresponding to an event are constant (or `NA`).
#'
#' @examples
#' \donttest{
#' library(parsnip)
#' library(rsample)
#' library(dials)
#'
#' ## -----------------------------------------------------------------------------
#'
#' if (rlang::is_installed(c("discrim", "modeldata"))) {
#' library(discrim)
#' data(two_class_dat, package = "modeldata")
#'
#' set.seed(6376)
#' rs <- bootstraps(two_class_dat, times = 10)
#'
#' ## -----------------------------------------------------------------------------
#'
#' # optimize an regularized discriminant analysis model
#' rda_spec <-
#' discrim_regularized(frac_common_cov = tune(), frac_identity = tune()) %>%
#' set_engine("klaR")
#'
#' ## -----------------------------------------------------------------------------
#'
#' ctrl <- control_race(verbose_elim = TRUE)
#'
#' set.seed(11)
#' grid_wl <-
#' rda_spec %>%
#' tune_race_win_loss(Class ~ ., resamples = rs, grid = 10, control = ctrl)
#'
#' # Shows only the fully resampled parameters
#' show_best(grid_wl, metric = "roc_auc")
#'
#' plot_race(grid_wl)
#' }
#' }
#' @return An object with primary class `tune_race` in the same standard format
#' as objects produced by [tune::tune_grid()].
#' @seealso [tune::tune_grid()], [control_race()], [tune_race_anova()]
#' @export
tune_race_win_loss <- function(object, ...) {
UseMethod("tune_race_win_loss")
}
#' @export
tune_race_win_loss.default <- function(object, ...) {
msg <- paste0(
"The first argument to {.fn tune_race_win_loss} should be either ",
"a model or workflow."
)
cli::cli_abort(msg)
}
#' @export
tune_race_win_loss.recipe <-
function(object,
model,
resamples,
...,
param_info = NULL,
grid = 10,
metrics = NULL,
eval_time = NULL,
control = control_race()) {
tune::empty_ellipses(...)
control <- parsnip::condense_control(control, control_race())
tune_race_win_loss(
model,
preprocessor = object, resamples = resamples,
param_info = param_info, grid = grid,
metrics = metrics, control = control,
eval_time = eval_time
)
}
#' @export
tune_race_win_loss.formula <-
function(formula,
model,
resamples,
...,
param_info = NULL,
grid = 10,
metrics = NULL,
eval_time = NULL,
control = control_race()) {
tune::empty_ellipses(...)
control <- parsnip::condense_control(control, control_race())
tune_race_win_loss(
model,
preprocessor = formula,
resamples = resamples,
param_info = param_info,
grid = grid,
metrics = metrics,
eval_time = eval_time,
control = control
)
}
#' @export
#' @rdname tune_race_win_loss
tune_race_win_loss.model_spec <-
function(object,
preprocessor,
resamples,
...,
param_info = NULL,
grid = 10,
metrics = NULL,
eval_time = NULL,
control = control_race()) {
if (rlang::is_missing(preprocessor) || !tune::is_preprocessor(preprocessor)) {
cli::cli_abort(
"To tune a model spec, you must preprocess with a formula, recipe, \\
or variable specification."
)
}
tune::empty_ellipses(...)
control <- parsnip::condense_control(control, control_race())
wflow <- workflows::add_model(workflows::workflow(), object)
if (tune::is_recipe(preprocessor)) {
wflow <- workflows::add_recipe(wflow, preprocessor)
} else if (rlang::is_formula(preprocessor)) {
wflow <- workflows::add_formula(wflow, preprocessor)
}
tune_race_win_loss_workflow(
wflow,
resamples = resamples,
grid = grid,
metrics = metrics,
eval_time = eval_time,
param_info = param_info,
control = control
)
}
#' @export
#' @rdname tune_race_win_loss
tune_race_win_loss.workflow <- function(object,
resamples,
...,
param_info = NULL,
grid = 10,
metrics = NULL,
eval_time = NULL,
control = control_race()) {
tune::empty_ellipses(...)
control <- parsnip::condense_control(control, control_race())
tune_race_win_loss_workflow(
object,
resamples = resamples,
grid = grid,
metrics = metrics,
eval_time = eval_time,
param_info = param_info,
control = control
)
}
## -----------------------------------------------------------------------------
tune_race_win_loss_workflow <-
function(object,
resamples,
param_info = NULL,
grid = 10,
metrics = NULL,
eval_time = NULL,
control = control_race(),
call = caller_env()) {
rlang::check_installed("BradleyTerry2")
B <- nrow(resamples)
if (control$randomize) {
resamples <- randomize_resamples(resamples)
}
resamples <- dplyr::mutate(resamples, .order = dplyr::row_number())
min_rs <- control$burn_in
check_num_resamples(B, min_rs)
tmp_resamples <- restore_rset(resamples, 1:min_rs)
metrics <- tune::check_metrics_arg(metrics, object, call = call)
eval_time <- tune::check_eval_time_arg(eval_time, metrics, call = call)
grid_control <- parsnip::condense_control(control, tune::control_grid())
res <-
object %>%
tune::tune_grid(
resamples = tmp_resamples,
param_info = param_info,
grid = grid,
metrics = metrics,
eval_time = eval_time,
control = grid_control
)
param_names <- tune::.get_tune_parameter_names(res)
opt_metric <- tune::first_metric(metrics)
opt_metric_name <- opt_metric$metric
maximize <- opt_metric$direction == "maximize"
opt_metric_time <- tune::first_eval_time(
metrics,
metric = opt_metric_name,
eval_time = eval_time,
call = call
)
racing_obj_log(opt_metric_name, opt_metric$direction, control, opt_metric_time)
filters_results <- test_parameters_bt(res, control$alpha, opt_metric_time)
n_grid <- nrow(filters_results)
log_final <- TRUE
num_ties <- 0
for (rs in (min_rs + 1):B) {
if (sum(filters_results$pass) == 2) {
num_ties <- num_ties + 1
}
new_grid <-
filters_results %>%
dplyr::filter(pass) %>%
dplyr::select(!!!param_names)
if (nrow(new_grid) > 1) {
tmp_resamples <- restore_rset(resamples, rs)
log_racing(control, filters_results, res$splits, n_grid, opt_metric_name)
} else {
tmp_resamples <- restore_rset(resamples, rs:B)
if (log_final) {
log_racing(control, filters_results, res$splits, n_grid, opt_metric_name)
}
log_final <- FALSE
}
grid_control <- parsnip::condense_control(control, tune::control_grid())
tmp_res <-
object %>%
tune::tune_grid(
resamples = tmp_resamples,
param_info = param_info,
grid = new_grid,
metrics = metrics,
eval_time = eval_time,
control = grid_control
)
res <- restore_tune(res, tmp_res, opt_metric_time)
if (nrow(new_grid) > 1) {
filters_results <- test_parameters_bt(res, control$alpha, opt_metric_time)
if (sum(filters_results$pass) == 2 & num_ties >= control$num_ties) {
filters_results <- tie_breaker(res, control, eval_time = opt_metric_time)
}
} else {
# Depending on the value of control$parallel_over we don't need to do
# the remaining loop to get the rs counter to B
max_B <- max(tune::collect_metrics(res)$n)
if (max_B == B) {
break()
}
}
}
.stash_last_result(res)
res
}