-
Notifications
You must be signed in to change notification settings - Fork 0
/
bootNet.R
203 lines (183 loc) · 8.39 KB
/
bootNet.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
#!/usr/bin/Rscript
#
# Created: 2016/01/10
# Last modified: 2017/04/27
# Author: Miles Benton
# Version: 0.1.2.0
#
# bootNet is a wrapper for the fantastic glmnet R package - it brings bootstrapping and parallel processing to the elastic-net framework.
#
# For more information please see README at: https://github.com/sirselim/bootNet
#
# """
#
# This update adds a parallel version of the bootNet function to utalise multiple cores if available
# WARNING [here be dragons!]: be aware of the amount of available system RAM when using bootNet.parallel, if the data
# set is large even running across 4-8 cores will quickly utalise many GB of RAM - you have been warned!
#
# E.g. use:
# bootNet.parallel(data = x, outcome = y, Alpha = 0.1, iter = 1000, sub_sample = 0.666, cores = 4, sampleID = sampleID)
#
# """
########################
## bootstrap function ##
########################
# Bootnet function
bootNet <- function(data, outcome, Alpha, iter, Lambda, sub_sample, sampleID, method=F){
#
# ----- METHODS -----
# BOOTSTRAP (default) - iterate over all samples N times; requires iter and sub_sample arguements
# JACKKNIFE - remove one sample and run glmnet. Iterations match the length of outcome
# LOOCV (leave one out cross validataion) - drops unique permutations (one from sample from both sides) of a qualitative factor
#
# report on outcome type
if (is.numeric(outcome) == TRUE) {
cat('...outcome is quantitative, using gaussian approach in glmnet model...', '\n')
} else if (is.factor(outcome) == TRUE) {
cat('...outcome is qualitative, using binomial approach in glmnet model...', '\n')
} else {
outcome.error <- paste0('outcome is [', class(outcome), ']', ' it needs to be numeric or factor...')
cat('...ERROR:', outcome.error, '\n')
}
## implement a check for NA's in data and outcome, quit with error if found
outcome_nas <- any(is.na(outcome))
data_nas <- any(is.na(data))
if (outcome_nas | data_nas) stop("bootNet has discovered NA's in outcome or data, terminating function call")
# load packages
require(glmnet)
# create empty list
site_list <- list()
# create an object to extract sites from later
featured.sites <- rownames(data)
# transpose data for glmnet
data <- t(data)
# method setup
if (method == "JACKKNIFE"){
print('jackknifing data, sub_sample and iteration arguments over-ruled')
iter <- length(outcome)-1
}
else if (method == "LOOCV"){
print('Running leave one out cross validation, sub_sample and iteration arguments over-ruled')
if (is.factor(outcome) == FALSE) stop("LOOCV requires a two-factor outcome, terminating function call")
a <- grep(levels(outcome)[1], outcome)
b <- grep(levels(outcome)[2], outcome)
eg <- expand.grid(a,b) # permutation list of indices to drop
iter <- length(eg[,1]) # iterations is set to the number of permutations
}
else{
print('Running default boostrap method... ')
}
# bootstrap process
for (i in 1:iter){
set.seed(i)
# subset by method selection
# 1. JACKKNIFE
if (method == "JACKKNIFE"){
jk_data<- data[-i,]
newOut <- outcome[-i]
if (is.numeric(outcome) == TRUE) {
fit <- glmnet(x = jk_data, y = newOut, family = "gaussian", alpha = Alpha, lambda = Lambda)
}
else {
fit <- glmnet(x = jk_data, y = newOut, family = "binomial", alpha = Alpha, lambda = Lambda)
}
}
# 2. LOOCV
else if (method == "LOOCV"){
eg_handle <- c(as.numeric(eg[i,1:2][1]),as.numeric(eg[i,1:2][2])) #gets the indices that will be dropped
loocv_data <- data[-eg_handle,]
newOut <- outcome[-eg_handle]
fit <- glmnet(x = loocv_data, y = newOut, family = "binomial", alpha = Alpha, lambda = Lambda)
}
# 3. BOOTSTRAP (default)
else{
# Select a random sub-sample from all samples
# first determine whether outcome is qualitative or quantitative
if (is.numeric(outcome) == TRUE) {
# sample from quantitative outcome
# NOTE: sampleID must be the same order as samples in the beta matrix/data!
subID <- sample(sampleID, ceiling(sub_sample*(length(sampleID)))) # get ID's for sub-sample
newDataInd <- outcome[names(outcome) %in% subID] # subset outcome for correct samples
newData <- data[rownames(data) %in% names(newDataInd),] # subset the data
newOut <- as.numeric(newDataInd)
# Do glmnet - 'gaussian' family
fit <- glmnet(x = newData, y = newOut, family = "gaussian", alpha = Alpha, lambda = Lambda)
} else {
# sample from qualitative outcome
newDataInd <- c(sample(grep(levels(outcome)[1], outcome), ceiling(sub_sample*(length(grep(levels(outcome)[1], outcome))))),
sample(grep(levels(outcome)[2], outcome), ceiling(sub_sample*(length(grep(levels(outcome)[2], outcome))))))
newData <- data[newDataInd,] # subset the data
newOut <- outcome[newDataInd] # In the outcome variable get the same patients as were selected for this iteration
# Do glmnet - 'binomial' family
fit <- glmnet(x = newData, y = newOut, family = "binomial", alpha = Alpha, lambda = Lambda)
}
}
# Get model coefficients
Coefficients <- coef(fit, s = 0.001) # if cv is performed this can be coef(fit, s = cv.fit$lambda.min)
# Get CpG list for which coefficients are not 0
selected.sites <- featured.sites[Coefficients@i]
name <- paste('run:', i, sep = '')
site_list[[name]] <- selected.sites
}
return(site_list)
cat('\n', ' ...Processing Done...')
}
########################
#################################
## parallel bootstrap function ##
#################################
bootNet.parallel <- function(data, outcome, Alpha, iter, Lambda, sub_sample, cores, sampleID){
# report on outcome type
if (is.numeric(outcome) == TRUE) {
cat('...outcome is quantitative, using gaussian approach in glmnet model...', '\n')
} else if (is.factor(outcome) == TRUE) {
cat('...outcome is qualitative, using binomial approach in glmnet model...', '\n')
} else {
outcome.error <- paste0('outcome is [', class(outcome), ']', ' it needs to be numeric or factor...')
cat('...ERROR:', outcome.error, '\n')
}
## implement a check for NA's in data and outcome, quit with error if found
outcome_nas <- any(is.na(outcome))
data_nas <- any(is.na(data))
if (outcome_nas | data_nas) stop("bootNet has discovered NA's in outcome or data, terminating function call")
# load packages
require(glmnet)
require(foreach)
require(doParallel)
# register cores
registerDoParallel(cores = cores)
# create an object to extract sites from later
feature.sites <- rownames(data)
# transpose data for glmnet
data <- t(data)
# bootstrap process
foreach (i = 1:iter, .combine = c) %dopar% {
set.seed(i)
# Select a random sub-sample from all samples
# first determine whether outcome is qualitative or quantitative
if (is.numeric(outcome) == TRUE) {
# sample from quantitative outcome
# NOTE: sampleID must be the same order as samples in the beta matrix/data!
subID <- sample(sampleID, ceiling(sub_sample*(length(sampleID)))) # get ID's for sub-sample
newDataInd <- outcome[names(outcome) %in% subID] # subset outcome for correct samples
newData <- data[rownames(data) %in% names(newDataInd),] # subset the data
newOut <- as.numeric(newDataInd)
# Do glmnet - 'gaussian' family
fit <- glmnet(x = newData, y = newOut, family = "gaussian", alpha = Alpha, lambda = Lambda)
} else {
# sample from qualitative outcome
newDataInd <- c(sample(grep(levels(outcome)[1], outcome), ceiling(sub_sample*(length(grep(levels(outcome)[1], outcome))))),
sample(grep(levels(outcome)[2], outcome), ceiling(sub_sample*(length(grep(levels(outcome)[2], outcome))))))
newData <- data[newDataInd,] # subset the data
newOut <- outcome[newDataInd] # In the outcome variable get the same patients as were selected for this iteration
# Do glmnet - 'gaussian' family
fit <- glmnet(x = newData, y = newOut, family = "binomial", alpha = Alpha, lambda = Lambda)
}
# Get model coefficients
Coefficients <- coef(fit, s = 0.001) # if cv is performed this can be coef(fit, s = cv.fit$lambda.min)
# Get site list for which coefficients are not 0
selected.sites <- feature.sites[Coefficients@i]
list(selected.sites)
}
}
#################################