-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathLOGOCV.R
311 lines (250 loc) · 11.2 KB
/
LOGOCV.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
################################################################################
# Author :
# Florian Rohart,
#
# created: 04-07-2015
# last modified: 22-04-2016
#
# Copyright (C) 2015
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
################################################################################
# ==============================================================================
# perform a Leave-one-out cross validation on the study to tune the number of
# variables (keepX) to keep in a mint.splsda analysis
# ==============================================================================
LOGOCV <- function(X,
Y,
ncomp,
study,
choice.keepX = NULL,
test.keepX = c(5, 10, 15),
dist = "max.dist",
measure = c("BER"), # one of c("overall","BER")
auc = auc,
max.iter = 100,
progressBar = FALSE,
near.zero.var = FALSE,
scale)
{
# X input
# Y factor input
# ncomp: which component we are tuning
# study: study effect
# choice.keepX: how many variables are kept on the first ncomp-1 components
# test.keepX: grid of keepX that is to be tested in the CV
# dist= which distance should be used to classify the samples?
# showProgress=TRUE, show the progress of the iteration
if(missing(X))
stop("missing X")
if(missing(Y))
stop("missing Y")
if(missing(study))
stop("missing study")
if(missing(ncomp))
ncomp = 1
if(missing(scale))
scale = FALSE
if(missing(dist))
dist = "max.dist"
if(length(Y) != nrow(X))
stop("X and Y have to be of same length")
#-- set up a progress bar --#
if (progressBar == TRUE)
{
pb = txtProgressBar(style = 3)
nBar = 1
} else {
pb = FALSE
}
M = nlevels(study)
names.study = levels(study)
features = NULL
prediction.comp = array(0, c(nrow(X), nlevels(Y), length(test.keepX)),
dimnames = list(rownames(X), levels(Y), test.keepX))
class.comp = list()
for(ijk in dist)
class.comp[[ijk]] = matrix(0, nrow = nrow(X), ncol = length(test.keepX))
# prediction of all samples for each test.keepX and nrep at comp fixed
PRED=INDICE = matrix(0, nrow = length(test.keepX), ncol = M)
rownames(PRED) = rownames(INDICE) = test.keepX
nbr.temp = matrix(0, nrow = length(test.keepX), ncol = nlevels(Y))
for (study_i in 1:M) #LOO on the study factor
{
if (progressBar == TRUE)
setTxtProgressBar(pb, (study_i-1)/M)
omit = which(study %in% names.study[study_i])
X.train = X[-omit,]
Y.train = factor(Y[-omit])
study.learn.CV = factor(as.character(study[-omit]))
X.test = X[omit, , drop = FALSE]
#note: drop is useless as there should always be more than a single
# sample in a study
Y.test = Y[omit]
study.test.CV = factor(as.character(study[omit]))
#---------------------------------------#
#-- near.zero.var ----------------------#
if(near.zero.var == TRUE)
{
remove.zero = nearZeroVar(X.train)$Position
if (length(remove.zero) > 0)
{
X.train = X.train[, -c(remove.zero),drop = FALSE]
X.test = X.test[, -c(remove.zero),drop = FALSE]
}
}
#-- near.zero.var ----------------------#
#---------------------------------------#
for (i in 1:length(test.keepX))
{
if (progressBar == TRUE)
setTxtProgressBar(pb, (study_i-1)/M + (i-1)/length(test.keepX)/M)
object.res = mint.splsda(X.train, Y.train,
study = study.learn.CV, ncomp = ncomp, keepX =
c(choice.keepX, test.keepX[i]),
scale = scale, max.iter = max.iter)
# record selected features
if (length(test.keepX) == 1)
# only done if only one test.keepX as not used if more so far
features = c(features, selectVar(object.res, comp = ncomp)$name)
test.predict.sw <- predict.mixo_spls(object.res, newdata = X.test,
method = dist, study.test = study.test.CV)
# Y.train can be missing factors, so the prediction
# 'test.predict.sw' might be missing factors compared to the
# full prediction.comp
prediction.comp[omit, match(levels(Y.train),levels(Y)) , i] =
test.predict.sw$predict[, , ncomp]
for(ijk in dist)
class.comp[[ijk]][omit,i] = test.predict.sw$class[[ijk]][, ncomp]
#levels(Y)[test.predict.sw$class[[ijk]][, ncomp]]
}#end test.keepX
if (progressBar == TRUE)
setTxtProgressBar(pb, (study_i)/M)
} # end study_i 1:M (M folds)
result = list()
auc.mean = error.mean = error.sd = error.per.class.keepX.opt.comp =
keepX.opt = test.keepX.out = choice.keepX.out =
error.per.study.keepX.opt = list()
if(auc)
{
data=list()
for (i in 1:length(test.keepX))
{
data$outcome=Y
data$data=prediction.comp[, , i]
auc.mean[[i]]=statauc(data)
}
names(auc.mean)=test.keepX
}
if (any(measure == "overall"))
{
for(ijk in dist)
{
rownames(class.comp[[ijk]]) = rownames(X)
colnames(class.comp[[ijk]]) = paste0("test.keepX.",test.keepX)
#finding the best keepX depending on the error measure:
# overall or BER
# classification error for each nrep and each test.keepX:
# summing over all samples
error = apply(class.comp[[ijk]], 2, function(x)
{
sum(as.character(Y) != x)
})
# we divide the error by the number of samples and choose the
# minimum error
error.mean[[ijk]] = error/length(Y)
keepX.opt[[ijk]] = which(error.mean[[ijk]] ==
min(error.mean[[ijk]]))[1]
# chose the lowest keepX if several minimum
# overall error per study
temp = matrix(0, ncol = length(test.keepX), nrow = nlevels(study))
for (study_i in 1:M) #LOO on the study factor
{
omit = which(study %in% names.study[study_i])
temp[study_i,] = apply(class.comp[[ijk]][omit,], 2, function(x)
{
sum(as.character(Y)[omit] != x)/length(omit)
})
}
error.per.study.keepX.opt[[ijk]] = temp[,keepX.opt[[ijk]]]
# confusion matrix for keepX.opt
error.per.class.keepX.opt.comp[[ijk]] =
apply(class.comp[[ijk]][, keepX.opt[[ijk]], drop = FALSE], 2,
function(x)
{
conf = get.confusion_matrix(truth = factor(Y), predicted = x)
out = (apply(conf, 1, sum) - diag(conf)) / summary(Y)
})
rownames(error.per.class.keepX.opt.comp[[ijk]]) = levels(Y)
test.keepX.out[[ijk]] = test.keepX[keepX.opt[[ijk]]]
choice.keepX.out[[ijk]] = c(choice.keepX, test.keepX.out)
result$"overall"$error.rate.mean = error.mean
result$"overall"$error.per.study.keepX.opt =
error.per.study.keepX.opt
result$"overall"$confusion = error.per.class.keepX.opt.comp
result$"overall"$keepX.opt = test.keepX.out
}
}
if (any(measure == "BER"))
{
for(ijk in dist)
{
rownames(class.comp[[ijk]]) = rownames(X)
colnames(class.comp[[ijk]]) = paste0("test.keepX.",test.keepX)
# we calculate a BER for each study and each test.keepX,
# then average over the study factor
error = matrix(0, ncol = length(test.keepX), nrow = nlevels(study))
for (study_i in 1:M) #LOO on the study factor
{
omit = which(study %in% names.study[study_i])
error[study_i,] = apply(class.comp[[ijk]][omit,], 2, function(x)
{
conf = get.confusion_matrix(truth = factor(Y[omit]),
all.levels = levels(factor(Y)), predicted = x)
get.BER(conf)
})
}
# weighted average BER over the studies
error.mean[[ijk]] = apply(error, 2, function(x) {
sum(x * table(study)/length(study))
})
keepX.opt[[ijk]] =
which(error.mean[[ijk]] == min(error.mean[[ijk]]))[1]
# error per study
error.per.study.keepX.opt[[ijk]] = error[,keepX.opt[[ijk]]]
# confusion matrix for keepX.opt
error.per.class.keepX.opt.comp[[ijk]] =
apply(class.comp[[ijk]][, keepX.opt[[ijk]], drop = FALSE], 2,
function(x)
{
conf = get.confusion_matrix(truth = factor(Y), predicted = x)
out = (apply(conf, 1, sum) - diag(conf)) / summary(Y)
})
rownames(error.per.class.keepX.opt.comp[[ijk]]) = levels(Y)
test.keepX.out[[ijk]] = test.keepX[keepX.opt[[ijk]]]
choice.keepX.out[[ijk]] = c(choice.keepX, test.keepX.out)
result$"BER"$error.rate.mean = error.mean
result$"BER"$error.per.study.keepX.opt = error.per.study.keepX.opt
result$"BER"$confusion = error.per.class.keepX.opt.comp
result$"BER"$keepX.opt = test.keepX.out
}
}
result$prediction.comp = prediction.comp
result$class.comp = class.comp
result$auc = auc.mean
result$features$stable =
sort(table(as.factor(features))/M, decreasing = TRUE)
return(result)
}#end function