Improve details in test/compareToCV.R
[agghoo.git] / test / compareToCV.R
1 library(agghoo)
2
3 standardCV <- function(data, target, task = NULL, gmodel = NULL, params = NULL,
4 loss = NULL, CV = list(type = "MC", V = 10, test_size = 0.2, shuffle = TRUE)
5 ) {
6 if (!is.null(task))
7 task = match.arg(task, c("classification", "regression"))
8 if (is.character(gmodel))
9 gmodel <- match.arg(gmodel, c("knn", "ppr", "rf", "tree"))
10 if (is.numeric(params) || is.character(params))
11 params <- as.list(params)
12 if (is.null(task)) {
13 if (is.numeric(target))
14 task = "regression"
15 else
16 task = "classification"
17 }
18
19 if (is.null(loss)) {
20 loss <- function(y1, y2) {
21 if (task == "classification") {
22 if (is.null(dim(y1)))
23 mean(y1 != y2)
24 else {
25 if (!is.null(dim(y2)))
26 mean(rowSums(abs(y1 - y2)))
27 else {
28 y2 <- as.character(y2)
29 names <- colnames(y1)
30 positions <- list()
31 for (idx in seq_along(names))
32 positions[[ names[idx] ]] <- idx
33 mean(vapply(
34 seq_along(y2),
35 function(idx) sum(abs(y1[idx,] - positions[[ y2[idx] ]])),
36 0))
37 }
38 }
39 }
40 }
41 }
42
43 n <- nrow(data)
44 shuffle_inds <- NULL
45 if (CV$type == "vfold" && CV$shuffle)
46 shuffle_inds <- sample(n, n)
47 get_testIndices <- function(v, shuffle_inds) {
48 if (CV$type == "vfold") {
49 first_index = round((v-1) * n / CV$V) + 1
50 last_index = round(v * n / CV$V)
51 test_indices = first_index:last_index
52 if (!is.null(shuffle_inds))
53 test_indices <- shuffle_inds[test_indices]
54 }
55 else
56 test_indices = sample(n, round(n * CV$test_size))
57 test_indices
58 }
59 list_testinds <- list()
60 for (v in seq_len(CV$V))
61 list_testinds[[v]] <- get_testIndices(v, shuffle_inds)
62
63 gmodel <- agghoo::Model$new(data, target, task, gmodel, params)
64 best_error <- Inf
65 best_model <- NULL
66 for (p in seq_len(gmodel$nmodels)) {
67 error <- 0
68 for (v in seq_len(CV$V)) {
69 testIdx <- list_testinds[[v]]
70 dataHO <- data[-testIdx,]
71 testX <- data[testIdx,]
72 targetHO <- target[-testIdx]
73 testY <- target[testIdx]
74 if (!is.matrix(dataHO) && !is.data.frame(dataHO))
75 dataHO <- as.matrix(dataHO)
76 if (!is.matrix(testX) && !is.data.frame(testX))
77 testX <- as.matrix(testX)
78 model_pred <- gmodel$get(dataHO, targetHO, p)
79 prediction <- model_pred(testX)
80 error <- error + loss(prediction, testY)
81 }
82 if (error <= best_error) {
83 newModel <- list(model=model_pred, param=gmodel$getParam(p))
84 if (error == best_error)
85 best_model[[length(best_model)+1]] <- newModel
86 else {
87 best_model <- list(newModel)
88 best_error <- error
89 }
90 }
91 }
92 best_model[[ sample(length(best_model), 1) ]]
93 }
94
95 compareToCV <- function(df, t_idx, task=NULL, rseed=-1, verbose=TRUE, ...) {
96 if (rseed >= 0)
97 set.seed(rseed)
98 if (is.null(task))
99 task <- ifelse(is.numeric(df[,t_idx]), "regression", "classification")
100 n <- nrow(df)
101 test_indices <- sample( n, round(n / ifelse(n >= 500, 10, 5)) )
102 a <- agghoo(df[-test_indices,-t_idx], df[-test_indices,t_idx], task, ...)
103 a$fit()
104 if (verbose) {
105 print("Parameters:")
106 print(unlist(a$getParams()))
107 }
108 pa <- a$predict(df[test_indices,-t_idx])
109 err_a <- ifelse(task == "classification",
110 mean(pa != df[test_indices,t_idx]),
111 mean(abs(pa - df[test_indices,t_idx])))
112 if (verbose)
113 print(paste("error agghoo:", err_a))
114 # Compare with standard cross-validation:
115 s <- standardCV(df[-test_indices,-t_idx], df[-test_indices,t_idx], task, ...)
116 if (verbose)
117 print(paste( "Parameter:", s$param ))
118 ps <- s$model(df[test_indices,-t_idx])
119 err_s <- ifelse(task == "classification",
120 mean(ps != df[test_indices,t_idx]),
121 mean(abs(ps - df[test_indices,t_idx])))
122 if (verbose)
123 print(paste("error CV:", err_s))
124 invisible(c(err_a, err_s))
125 }
126
127 library(parallel)
128 compareMulti <- function(df, t_idx, task = NULL, N = 100, nc = NA, ...) {
129 if (is.na(nc))
130 nc <- detectCores()
131 errors <- mclapply(1:N,
132 function(n) {
133 compareToCV(df, t_idx, task, n, verbose=FALSE, ...) },
134 mc.cores = nc)
135 print("error agghoo vs. cross-validation:")
136 Reduce('+', errors) / N
137 }