/
LearnerClassifDebug.R
241 lines (222 loc) · 8.92 KB
/
LearnerClassifDebug.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
#' @title Classification Learner for Debugging
#'
#' @name mlr_learners_classif.debug
#' @include LearnerClassif.R
#'
#' @description
#' A simple [LearnerClassif] used primarily in the unit tests and for debugging purposes.
#' If no hyperparameter is set, it simply constantly predicts a randomly selected label.
#' The following hyperparameters trigger the following actions:
#' \describe{
#' \item{error_predict:}{Probability to raise an exception during predict.}
#' \item{error_train:}{Probability to raises an exception during train.}
#' \item{message_predict:}{Probability to output a message during predict.}
#' \item{message_train:}{Probability to output a message during train.}
#' \item{predict_missing:}{Ratio of predictions which will be NA.}
#' \item{predict_missing_type:}{To to encode missingness. \dQuote{na} will insert NA values, \dQuote{omit} will just return fewer predictions than requested.}
#' \item{save_tasks:}{Saves input task in `model` slot during training and prediction.}
#' \item{segfault_predict:}{Probability to provokes a segfault during predict.}
#' \item{segfault_train:}{Probability to provokes a segfault during train.}
#' \item{sleep_train:}{Function returning a single number determining how many seconds to sleep during `$train()`.}
#' \item{sleep_predict:}{Function returning a single number determining how many seconds to sleep during `$predict()`.}
#' \item{threads:}{Number of threads to use. Has no effect.}
#' \item{warning_predict:}{Probability to signal a warning during predict.}
#' \item{warning_train:}{Probability to signal a warning during train.}
#' \item{x:}{Numeric tuning parameter. Has no effect.}
#' \item{iter:}{Integer parameter for testing hotstarting.}
#' \item{count_marshaling:}{If `TRUE`, `marshal_model` will increase the `marshal_count` by 1 each time it is called. The default is `FALSE`.}
#' }
#' Note that segfaults may not be triggered reliably on your operating system.
#' Also note that if they work as intended, they will tear down your R session immediately!
#'
#' @templateVar id classif.debug
#' @template learner
#'
#' @template seealso_learner
#' @export
#' @examples
#' learner = lrn("classif.debug")
#' learner$param_set$values = list(message_train = 1, save_tasks = TRUE)
#'
#' # this should signal a message
#' task = tsk("penguins")
#' learner$train(task)
#' learner$predict(task)
#'
#' # task_train and task_predict are the input tasks for train() and predict()
#' names(learner$model)
LearnerClassifDebug = R6Class("LearnerClassifDebug", inherit = LearnerClassif,
public = list(
#' @description
#' Creates a new instance of this [R6][R6::R6Class] class.
initialize = function() {
param_set = ps(
error_predict = p_dbl(0, 1, default = 0, tags = "predict"),
error_train = p_dbl(0, 1, default = 0, tags = "train"),
message_predict = p_dbl(0, 1, default = 0, tags = "predict"),
message_train = p_dbl(0, 1, default = 0, tags = "train"),
predict_missing = p_dbl(0, 1, default = 0, tags = "predict"),
predict_missing_type = p_fct(c("na", "omit"), default = "na", tags = "predict"),
save_tasks = p_lgl(default = FALSE, tags = c("train", "predict")),
segfault_predict = p_dbl(0, 1, default = 0, tags = "predict"),
segfault_train = p_dbl(0, 1, default = 0, tags = "train"),
sleep_train = p_uty(tags = "train"),
sleep_predict = p_uty(tags = "predict"),
threads = p_int(1L, tags = c("train", "threads")),
warning_predict = p_dbl(0, 1, default = 0, tags = "predict"),
warning_train = p_dbl(0, 1, default = 0, tags = "train"),
x = p_dbl(0, 1, tags = "train"),
iter = p_int(1, default = 1, tags = c("train", "hotstart")),
count_marshaling = p_lgl(default = FALSE, tags = "train")
)
super$initialize(
id = "classif.debug",
param_set = param_set,
feature_types = c("logical", "integer", "numeric", "character", "factor", "ordered"),
predict_types = c("response", "prob"),
properties = c("twoclass", "multiclass", "missings", "hotstart_forward", "marshal"),
man = "mlr3::mlr_learners_classif.debug",
data_formats = c("data.table", "Matrix"),
label = "Debug Learner for Classification"
)
},
#' @description
#' Marshal the learner's model.
#' @param ... (any)\cr
#' Additional arguments passed to [`marshal_model()`].
marshal = function(...) {
learner_marshal(.learner = self, ...)
},
#' @description
#' Unmarshal the learner's model.
#' @param ... (any)\cr
#' Additional arguments passed to [`unmarshal_model()`].
unmarshal = function(...) {
learner_unmarshal(.learner = self, ...)
}
),
active = list(
#' @field marshaled (logical(1))\cr
#' Whether the learner has been marshaled.
marshaled = function() {
learner_marshaled(self)
}
),
private = list(
.train = function(task) {
pv = self$param_set$get_values(tags = "train")
pv$count_marshaling = pv$count_marshaling %??% FALSE
roll = function(name) {
name %in% names(pv) && pv[[name]] > runif(1L)
}
if (!is.null(pv$sleep_train)) {
secs = assert_number(pv$sleep_train())
Sys.sleep(max(0, secs))
}
if (roll("message_train")) {
message("Message from classif.debug->train()")
}
if (roll("warning_train")) {
warning("Warning from classif.debug->train()")
}
if (roll("error_train")) {
stop("Error from classif.debug->train()")
}
if (roll("segfault_train")) {
get("attach")(structure(list(), class = "UserDefinedDatabase"))
}
model = list(response = as.character(sample(task$truth(), 1L)), pid = Sys.getpid(), iter = pv$iter,
id = UUIDgenerate(), random_number = sample(100000, 1))
if (isTRUE(pv$save_tasks)) {
model$task_train = task$clone(deep = TRUE)
}
if (isTRUE(pv$count_marshaling)) {
model$marshal_count = 0L
}
set_class(model, "classif.debug_model")
},
.predict = function(task) {
n = task$nrow
pv = self$param_set$get_values(tags = "predict")
roll = function(name) {
name %in% names(pv) && pv[[name]] > runif(1L)
}
if (!is.null(pv$sleep_predict)) {
secs = assert_number(pv$sleep_predict())
Sys.sleep(max(0, secs))
}
if (roll("message_predict")) {
message("Message from classif.debug->predict()")
}
if (roll("warning_predict")) {
warning("Warning from classif.debug->predict()")
}
if (roll("error_predict")) {
stop("Error from classif.debug->predict()")
}
if (roll("segfault_predict")) {
get("attach")(structure(list(), class = "UserDefinedDatabase"))
}
if (isTRUE(pv$save_tasks)) {
self$state$model$task_predict = task$clone(deep = TRUE)
}
response = prob = NULL
missing_type = pv$predict_missing_type %??% "na"
if ("response" %in% self$predict_type) {
response = rep.int(unclass(self$model$response), n)
if (!is.null(pv$predict_missing)) {
ii = sample.int(n, n * pv$predict_missing)
response = switch(missing_type,
"na" = replace(response, ii, NA),
"omit" = response[ii]
)
}
}
if ("prob" %in% self$predict_type) {
cl = task$class_names
prob = matrix(runif(n * length(cl)), nrow = n)
prob = prob / rowSums(prob)
colnames(prob) = cl
if (!is.null(pv$predict_missing)) {
ii = sample.int(n, n * pv$predict_missing)
prob = switch(missing_type,
"na" = {
prob[ii, ] = NA_real_
prob
},
"omit" = {
prob[ii, , drop = FALSE]
}
)
}
}
list(response = response, prob = prob)
},
.hotstart = function(task) {
model = self$model
pars = self$param_set$get_values(tags = "train")
id = self$model$id
model = list(response = as.character(sample(task$truth(), 1L)), pid = Sys.getpid(), iter = pars$iter,
id = id)
set_class(model, "classif.debug_model")
}
)
)
#' @include mlr_learners.R
mlr_learners$add("classif.debug", function() LearnerClassifDebug$new())
#' @export
#' @method marshal_model classif.debug_model
marshal_model.classif.debug_model = function(model, inplace = FALSE, ...) {
if (!is.null(model$marshal_count)) {
model$marshal_count = model$marshal_count + 1
}
structure(list(
marshaled = model, packages = "mlr3"),
class = c("classif.debug_model_marshaled", "marshaled")
)
}
#' @export
#' @method unmarshal_model classif.debug_model_marshaled
unmarshal_model.classif.debug_model_marshaled = function(model, inplace = FALSE, ...) {
model$marshaled
}