-
Notifications
You must be signed in to change notification settings - Fork 30
/
tune.R
488 lines (446 loc) · 18.3 KB
/
tune.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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
tune.control <- function(random = FALSE,
nrepeat = 1,
repeat.aggregate = mean,
sampling = c("cross", "fix", "bootstrap"),
sampling.aggregate = mean,
sampling.dispersion = sd,
cross = 10,
fix = 2 / 3,
nboot = 10,
boot.size = 9 / 10,
best.model = TRUE,
performances = TRUE,
error.fun = NULL) {
structure(list(random = random,
nrepeat = nrepeat,
repeat.aggregate = repeat.aggregate,
sampling = match.arg(sampling),
sampling.aggregate = sampling.aggregate,
sampling.dispersion = sampling.dispersion,
cross = cross,
fix = fix,
nboot = nboot,
boot.size = boot.size,
best.model = best.model,
performances = performances,
error.fun = error.fun
),
class = "tune.control"
)
}
tune <- function(METHOD, train.x, train.y = NULL, data = list(),
validation.x = NULL, validation.y = NULL,
ranges = NULL, predict.func = predict,
tunecontrol = tune.control(),
...
) {
call <- match.call()
## internal helper functions
resp <- function(formula, data) {
model.response(model.frame(formula, data))
}
classAgreement <- function (tab) {
n <- sum(tab)
if (!is.null(dimnames(tab))) {
lev <- intersect(colnames(tab), rownames(tab))
p0 <- sum(diag(tab[lev, lev])) / n
} else {
m <- min(dim(tab))
p0 <- sum(diag(tab[1:m, 1:m])) / n
}
p0
}
## parameter handling
if (tunecontrol$sampling == "cross")
validation.x <- validation.y <- NULL
useFormula <- is.null(train.y)
if (useFormula && (is.null(data) || length(data) == 0))
data <- model.frame(train.x)
if (is.vector(train.x)) train.x <- t(t(train.x))
if (is.data.frame(train.y))
train.y <- as.matrix(train.y)
## prepare training indices
if (!is.null(validation.x)) tunecontrol$fix <- 1
n <- nrow(if (useFormula) data else train.x)
perm.ind <- sample(n)
if (tunecontrol$sampling == "cross") {
if (tunecontrol$cross > n)
stop(sQuote("cross"), " must not exceed sampling size!")
if (tunecontrol$cross == 1)
stop(sQuote("cross"), " must be greater than 1!")
}
train.ind <- if (tunecontrol$sampling == "cross")
tapply(1:n, cut(1:n, breaks = tunecontrol$cross), function(x) perm.ind[-x])
else if (tunecontrol$sampling == "fix")
list(perm.ind[1:trunc(n * tunecontrol$fix)])
else ## bootstrap
lapply(1:tunecontrol$nboot,
function(x) sample(n, n * tunecontrol$boot.size, replace = TRUE))
## find best model
parameters <- if (is.null(ranges))
data.frame(dummyparameter = 0)
else
expand.grid(ranges)
p <- nrow(parameters)
if (!is.logical(tunecontrol$random)) {
if (tunecontrol$random < 1)
stop("random must be a strictly positive integer")
if (tunecontrol$random > p) tunecontrol$random <- p
parameters <- parameters[sample(1:p, tunecontrol$random),]
p <- nrow(parameters)
}
model.variances <- model.errors <- c()
## - loop over all models
for (para.set in 1:p) {
sampling.errors <- c()
## - loop over all training samples
for (sample in 1:length(train.ind)) {
repeat.errors <- c()
## - repeat training `nrepeat' times
for (reps in 1:tunecontrol$nrepeat) {
## train one model
pars <- if (is.null(ranges))
NULL
else
lapply(parameters[para.set,,drop = FALSE], unlist)
model <- if (useFormula)
do.call(METHOD, c(list(train.x,
data = data,
subset = train.ind[[sample]]),
pars, list(...)
)
)
else
do.call(METHOD, c(list(train.x[train.ind[[sample]],],
y = train.y[train.ind[[sample]]]),
pars, list(...)
)
)
## predict validation set
pred <- predict.func(model,
if (!is.null(validation.x))
validation.x
else if (useFormula)
data[-train.ind[[sample]],,drop = FALSE]
else if (inherits(train.x, "matrix.csr"))
train.x[-train.ind[[sample]],]
else
train.x[-train.ind[[sample]],,drop = FALSE]
)
## compute performance measure
true.y <- if (!is.null(validation.y))
validation.y
else if (useFormula) {
if (!is.null(validation.x))
resp(train.x, validation.x)
else
resp(train.x, data[-train.ind[[sample]],])
} else
train.y[-train.ind[[sample]]]
if (is.null(true.y)) true.y <- rep(TRUE, length(pred))
repeat.errors[reps] <- if (!is.null(tunecontrol$error.fun))
tunecontrol$error.fun(true.y, pred)
else if ((is.logical(true.y) || is.factor(true.y)) && (is.logical(pred) || is.factor(pred) || is.character(pred))) ## classification error
1 - classAgreement(table(pred, true.y))
else if (is.numeric(true.y) && is.numeric(pred)) ## mean squared error
crossprod(pred - true.y) / length(pred)
else
stop("Dependent variable has wrong type!")
}
sampling.errors[sample] <- tunecontrol$repeat.aggregate(repeat.errors)
}
model.errors[para.set] <- tunecontrol$sampling.aggregate(sampling.errors)
model.variances[para.set] <- tunecontrol$sampling.dispersion(sampling.errors)
}
## return results
best <- which.min(model.errors)
pars <- if (is.null(ranges))
NULL
else
lapply(parameters[best,,drop = FALSE], unlist)
structure(list(best.parameters = parameters[best,,drop = FALSE],
best.performance = model.errors[best],
method = if (!is.character(METHOD))
deparse(substitute(METHOD)) else METHOD,
nparcomb = nrow(parameters),
train.ind = train.ind,
sampling = switch(tunecontrol$sampling,
fix = "fixed training/validation set",
bootstrap = "bootstrapping",
cross = if (tunecontrol$cross == n) "leave-one-out" else
paste(tunecontrol$cross,"-fold cross validation", sep="")
),
performances = if (tunecontrol$performances) cbind(parameters, error = model.errors, dispersion = model.variances),
best.model = if (tunecontrol$best.model) {
modeltmp <- if (useFormula)
do.call(METHOD, c(list(train.x, data = data),
pars, list(...)))
else
do.call(METHOD, c(list(x = train.x,
y = train.y),
pars, list(...)))
call[[1]] <- as.symbol("best.tune")
modeltmp$call <- call
modeltmp
}
),
class = "tune"
)
}
best.tune <- function(...) {
call <- match.call()
modeltmp <- tune(...)$best.model
modeltmp$call <- call
modeltmp
}
print.tune <- function(x, ...) {
if (x$nparcomb > 1) {
cat("\nParameter tuning of ", sQuote(x$method), ":\n\n", sep="")
cat("- sampling method:", x$sampling,"\n\n")
cat("- best parameters:\n")
tmp <- x$best.parameters
rownames(tmp) <- ""
print(tmp)
cat("\n- best performance:", x$best.performance, "\n")
cat("\n")
} else {
cat("\nError estimation of ", sQuote(x$method), " using ", x$sampling, ": ",
x$best.performance, "\n\n", sep="")
}
}
summary.tune <- function(object, ...)
structure(object, class = "summary.tune")
print.summary.tune <- function(x, ...) {
print.tune(x)
if (!is.null(x$performances) && (x$nparcomb > 1)) {
cat("- Detailed performance results:\n")
print(x$performances)
cat("\n")
}
}
hsv_palette <- function(h = 2/3, from = 0.7, to = 0.2, v = 1)
function(n) hsv(h = h, s = seq(from, to, length.out = n), v = v)
plot.tune <- function(x,
type=c("contour","perspective"),
theta=60,
col="lightblue",
main = NULL,
xlab = NULL,
ylab = NULL,
swapxy = FALSE,
transform.x = NULL,
transform.y = NULL,
transform.z = NULL,
color.palette = hsv_palette(),
nlevels = 20,
...)
{
if (is.null(x$performances))
stop("Object does not contain detailed performance measures!")
k <- ncol(x$performances)
if (k > 4) stop("Cannot visualize more than 2 parameters")
type = match.arg(type)
if (is.null(main))
main <- paste("Performance of `", x$method, "'", sep="")
if (k == 3)
plot(x$performances[,1:2], type = "b", main = main)
else {
if (!is.null(transform.x))
x$performances[,1] <- transform.x(x$performances[,1])
if (!is.null(transform.y))
x$performances[,2] <- transform.y(x$performances[,2])
if (!is.null(transform.z))
x$performances[,3] <- transform.z(x$performances[,3])
if (swapxy)
x$performances[,1:2] <- x$performances[,2:1]
x <- xtabs(error~., data = x$performances[,-k])
if (is.null(xlab)) xlab <- names(dimnames(x))[1 + swapxy]
if (is.null(ylab)) ylab <- names(dimnames(x))[2 - swapxy]
if (type == "perspective")
persp(x=as.double(rownames(x)),
y=as.double(colnames(x)),
z=x,
xlab=xlab,
ylab=ylab,
zlab="accuracy",
theta=theta,
col=col,
ticktype="detailed",
main = main,
...
)
else
filled.contour(x=as.double(rownames(x)),
y=as.double(colnames(x)),
xlab=xlab,
ylab=ylab,
nlevels=nlevels,
color.palette = color.palette,
main = main,
x, ...)
}
}
#############################################
## convenience functions for some methods
#############################################
tune.svm <- function(x, y = NULL, data = NULL, degree = NULL, gamma = NULL,
coef0 = NULL, cost = NULL, nu = NULL, class.weights = NULL,
epsilon = NULL, ...) {
call <- match.call()
call[[1]] <- as.symbol("best.svm")
ranges <- list(degree = degree, gamma = gamma,
coef0 = coef0, cost = cost, nu = nu,
class.weights = class.weights, epsilon = epsilon)
ranges[vapply(ranges, is.null, NA)] <- NULL
if (length(ranges) < 1)
ranges = NULL
modeltmp <- if (inherits(x, "formula"))
tune("svm", train.x = x, data = data, ranges = ranges, ...)
else
tune("svm", train.x = x, train.y = y, ranges = ranges, ...)
if (!is.null(modeltmp$best.model))
modeltmp$best.model$call <- call
modeltmp
}
best.svm <- function(x, tunecontrol = tune.control(), ...) {
call <- match.call()
tunecontrol$best.model = TRUE
modeltmp <- tune.svm(x, ..., tunecontrol = tunecontrol)$best.model
modeltmp$call <- call
modeltmp
}
tune.nnet <- function(x, y = NULL, data = NULL,
size = NULL, decay = NULL, trace = FALSE,
tunecontrol = tune.control(nrepeat = 5),
...) {
call <- match.call()
call[[1]] <- as.symbol("best.nnet")
loadNamespace("nnet")
predict.func <- predict
useFormula <- inherits(x, "formula")
if (is.factor(y) ||
(useFormula && is.factor(model.response(model.frame(formula = x, data = data))))
)
predict.func = function(...) predict(..., type = "class")
ranges <- list(size = size, decay = decay)
ranges[vapply(ranges, is.null, NA)] <- NULL
if (length(ranges) < 1)
ranges = NULL
modeltmp <- if (useFormula)
tune("nnet", train.x = x, data = data, ranges = ranges, predict.func = predict.func,
tunecontrol = tunecontrol, trace = trace, ...)
else
tune("nnet", train.x = x, train.y = y, ranges = ranges, predict.func = predict.func,
tunecontrol = tunecontrol, trace = trace, ...)
if (!is.null(modeltmp$best.model))
modeltmp$best.model$call <- call
modeltmp
}
best.nnet <- function(x, tunecontrol = tune.control(nrepeat = 5), ...) {
call <- match.call()
tunecontrol$best.model = TRUE
modeltmp <- tune.nnet(x, ..., tunecontrol = tunecontrol)$best.model
modeltmp$call <- call
modeltmp
}
tune.randomForest <- function(x, y = NULL, data = NULL, nodesize = NULL, mtry = NULL, ntree = NULL, ...) {
call <- match.call()
call[[1]] <- as.symbol("best.randomForest")
loadNamespace("randomForest")
ranges <- list(nodesize = nodesize, mtry = mtry, ntree = ntree)
ranges[vapply(ranges, is.null, NA)] <- NULL
if (length(ranges) < 1)
ranges = NULL
modeltmp <- if (inherits(x, "formula"))
tune("randomForest", train.x = x, data = data, ranges = ranges, ...)
else
tune("randomForest", train.x = x, train.y = y, ranges = ranges, ...)
if (!is.null(modeltmp$best.model))
modeltmp$best.model$call <- call
modeltmp
}
best.randomForest <- function(x, tunecontrol = tune.control(), ...) {
call <- match.call()
tunecontrol$best.model = TRUE
modeltmp <- tune.randomForest(x, ..., tunecontrol = tunecontrol)$best.model
modeltmp$call <- call
modeltmp
}
tune.gknn <- function(x, y = NULL, data = NULL, k = NULL, ...) {
call <- match.call()
call[[1]] <- as.symbol("best.gknn")
ranges <- list(k = k)
ranges[vapply(ranges, is.null, NA)] <- NULL
if (length(ranges) < 1)
ranges = NULL
modeltmp <- if (inherits(x, "formula"))
tune("gknn", train.x = x, data = data, ranges = ranges, ...)
else
tune("gknn", train.x = x, train.y = y, ranges = ranges, ...)
if (!is.null(modeltmp$best.model))
modeltmp$best.model$call <- call
modeltmp
}
best.gknn <- function(x, tunecontrol = tune.control(), ...) {
call <- match.call()
tunecontrol$best.model = TRUE
modeltmp <- tune.gknn(x, ..., tunecontrol = tunecontrol)$best.model
modeltmp$call <- call
modeltmp
}
knn.wrapper <- function(x, y, k = 1, l = 0, ...)
list(train = x, cl = y, k = k, l = l, ...)
tune.knn <- function(x, y, k = NULL, l = NULL, ...) {
loadNamespace("class")
ranges <- list(k = k, l = l)
ranges[vapply(ranges, is.null, NA)] <- NULL
if (length(ranges) < 1)
ranges = NULL
tune("knn.wrapper",
train.x = x, train.y = y, ranges = ranges,
predict.func = function(x, ...) knn(train = x$train, cl = x$cl, k = x$k, l = x$l, ...),
...)
}
rpart.wrapper <- function(formula, minsplit=20, minbucket=round(minsplit/3), cp=0.01,
maxcompete=4, maxsurrogate=5, usesurrogate=2, xval=10,
surrogatestyle=0, maxdepth=30, ...)
rpart::rpart(formula,
control = rpart::rpart.control(minsplit=minsplit, minbucket=minbucket,
cp=cp, maxcompete=maxcompete, maxsurrogate=maxsurrogate,
usesurrogate=usesurrogate, xval=xval,
surrogatestyle=surrogatestyle, maxdepth=maxdepth),
...
)
tune.rpart <- function(formula, data, na.action = na.omit,
minsplit=NULL, minbucket=NULL, cp=NULL,
maxcompete=NULL, maxsurrogate=NULL, usesurrogate=NULL, xval=NULL,
surrogatestyle=NULL, maxdepth=NULL,
predict.func = NULL,
...) {
call <- match.call()
call[[1]] <- as.symbol("best.rpart")
loadNamespace("rpart")
ranges <- list(minsplit=minsplit, minbucket=minbucket, cp=cp,
maxcompete=maxcompete, maxsurrogate=maxsurrogate,
usesurrogate=usesurrogate, xval=xval,
surrogatestyle=surrogatestyle, maxdepth=maxdepth)
ranges[vapply(ranges, is.null, NA)] <- NULL
if (length(ranges) < 1)
ranges <- NULL
predict.func <- if (is.factor(model.response(model.frame(formula, data))))
function(...) predict(..., type = "class")
else
predict
modeltmp <- tune("rpart.wrapper", train.x = formula, data = data, ranges = ranges,
predict.func = predict.func, na.action = na.action, ...)
if (!is.null(modeltmp$best.model))
modeltmp$best.model$call <- call
modeltmp
}
best.rpart <- function(formula, tunecontrol = tune.control(), ...) {
call <- match.call()
tunecontrol$best.model = TRUE
modeltmp <- tune.rpart(formula, ..., tunecontrol = tunecontrol)$best.model
modeltmp$call <- call
modeltmp
}