-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfit_predict_svmc.R
More file actions
261 lines (221 loc) · 5.43 KB
/
fit_predict_svmc.R
File metadata and controls
261 lines (221 loc) · 5.43 KB
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
#' Hidden genome SVM classifier (svmc)
#'
#' @details Light wrapper around e1071::svm or liquidSVM::mcSVM to use in hidden
#' genome classification
#' @param ... additional arguments passed to e1071:tune.svm, or
#' liquidSVM::svm.
#' @param backend the backend to use. Either "e1071" or "liquidSVM". Defaults to
#' "liquidSVM". NOTE: these packages are required to be installed separately.
#'
#' @inheritParams fit_smlc
#'
#' @examples
#' data("impact")
#' top_v <- variant_screen_mi(
#' maf = impact,
#' variant_col = "Variant",
#' cancer_col = "CANCER_SITE",
#' sample_id_col = "patient_id",
#' mi_rank_thresh = 50,
#' return_prob_mi = FALSE
#' )
#' var_design <- extract_design(
#' maf = impact,
#' variant_col = "Variant",
#' sample_id_col = "patient_id",
#' variant_subset = top_v
#' )
#'
#' canc_resp <- extract_cancer_response(
#' maf = impact,
#' cancer_col = "CANCER_SITE",
#' sample_id_col = "patient_id"
#' )
#' pid <- names(canc_resp)
#' # create five stratified random folds
#' # based on the response cancer categories
#' set.seed(42)
#' folds <- data.table::data.table(
#' resp = canc_resp
#' )[,
#' foldid := sample(rep(1:5, length.out = .N)),
#' by = resp
#' ]$foldid
#'
#' # 80%-20% stratified separation of training and
#' # test set tumors
#' idx_train <- pid[folds != 5]
#' idx_test <- pid[folds == 5]
#'
#' \dontrun{
#' # train a classifier on the training set
#' # using only variants (will have low accuracy
#' # -- no meta-feature information used)
#' fit0 <- fit_svmc(
#' X = var_design[idx_train, ],
#' Y = canc_resp[idx_train]
#' )
#'
#' pred0 <- predict_svmc(
#' fit = fit0,
#' Xnew = var_design[idx_test, ]
#' )
#' }
#'
#' @export
fit_svmc <- function(X,
Y,
backend = "liquidSVM",
scale = TRUE,
scale_fn = function(x) 2*sd(x),
...) {
dots <- list(...)
if (is.null(dots$gamma)) {
gamma <- 10^(-4:3)
}
if (is.null(dots$cost)) {
dots$cost <- 10^(-4:3)
}
if (!backend %in% c("e1071", "liquidSVM")) {
stop("backend must be either 'e1071' or 'liquidSVM'")
}
if (scale) {
X_scale <- apply(
X, 2,
match.fun(scale_fn)
) %>%
pmax(1) %>%
setNames(colnames(X))
X <- X %>%
divide_cols(X_scale)
attr(X, "scaled:scale") <- X_scale
}
if (backend == "e1071") {
if (!requireNamespace(backend)) {
fit <- list(
x = X,
y = as.factor(Y),
probability = TRUE,
kernel = "radial"
) %>%
c(dots) %>%
do.call(e1071::tune.svm, .)
} else {
msg <- glue::glue(
"Package {backend} is required for backend = '{backend}'. \\
Please install it and then rerun."
)
stop(msg)
}
} else if (backend == "liquidSVM") {
if (requireNamespace(backend)) {
if (is.null(dots$type)) {
dots$type <- "AvA_ls"
}
if (is.null(dots$max_gamma)) {
dots$max_gamma <- 1e6
}
if (is.null(dots$min_gamma)) {
dots$min_gamma <- 1e-8
}
if (is.null(dots$min_lambda)) {
dots$min_lambda <- 1e-8
}
fit <- list(x = as.matrix(X),
y = as.factor(Y),
predict.prob = TRUE) %>%
c(dots) %>%
do.call(liquidSVM::mcSVM, .)
} else {
msg <- glue::glue(
"Package {backend} is required for backend = '{backend}'. \\
Please install it and then rerun."
)
stop(msg)
}
}
out <- list(
X = X,
Y = Y,
fit = fit,
scale = scale,
backend = backend,
method = "svm"
)
out
}
#' @rdname fit_svmc
#' @export
fit_svm <- fit_svmc
#' prediction based on hidden genome random forest classifier
#' @seealso fit_svmc
#' @inheritParams predict_mlogit
#' @param fit fitted hidden genome SVM classifier (output of
#' \code{fit_svmc()})
#' @export
predict_svmc <- function(fit,
Xnew,
Ynew = NULL, ...) {
Xold_names <- colnames(fit$X)
Xnew_adj <- Xnew %>%
fill_sparsemat_zero(
rownames = rownames(.),
colnames = Xold_names
)
if (fit$scale) {
Xscale <- rep(1, ncol(Xnew_adj)) %>%
setNames(colnames(Xnew_adj))
Xscale[Xold_names] <- attr(
fit$X,
"scaled:scale"
)[Xold_names]
Xnew_adj <- Xnew_adj %>%
divide_cols(Xscale) %>%
Matrix::Matrix(sparse = TRUE)
}
if (fit$backend == "e1071") {
fit_svm <- fit$fit$best.model
predict_obj <- predict(
fit_svm,
newdata = Xnew_adj,
probability = TRUE
)
predict_prob <- attr(predict_obj, "probabilities") %>%
as.matrix() %>%
magrittr::set_rownames(
rownames(Xnew_adj)
) %>%
.[, sort(colnames(.))]
} else if (fit$backend == "liquidSVM") {
fit_svm <- fit$fit
predict_prob <- predict(
fit_svm,
newdata = as.matrix(Xnew_adj)
# probability = TRUE
) %>%
data.matrix() %>%
divide_rows(
rowSums(.)
) %>%
magrittr::set_colnames(
colnames(.) %>%
strsplit("vs") %>%
sapply(head, 1)
) %>%
magrittr::set_rownames(
rownames(Xnew_adj)
) %>%
.[, sort(colnames(.))]
}
pred_class <- apply(
predict_prob,
1,
function(x) names(x)[which.max(x)]
)
list("predicted" = pred_class,
"probs_predicted" = predict_prob,
"observed" = Ynew)
}
#' @rdname predict_svmc
#' @export
predict_svm <- predict_svmc