-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathAnalysis.R
242 lines (195 loc) · 7.16 KB
/
Analysis.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
# This script goes through the regression tree analysis as well as the dynamic
# geography analysis
# Load libraries ----------------------------------------------------------------------
library(tidyverse)
library(gbm)
library(dismo)
library(ROCR)
library(ModelMetrics)
library(parallel)
library(doSNOW)
library(foreach)
library(brms)
# Part 1: Regression tree analysis ----------------------------------------------------
# This section involves running 1000 bootstrapped BRTs in parallel to calculate the
# relative importance of each variable, calculate the partial dependence of each variable,
# and calculate the predicted probability of extinctions for the Presence Uncertain nations
# read-in data
OccData <-
read_csv('Data/OccurrenceData.csv')
BRTpred <-
read_csv('Data/PresenceUncertain.csv') %>%
# convert to a dataframe
as.data.frame()
# for reproducibility
set.seed(123)
# start by randomizing the data
randomIndex <- sample(1:nrow(OccData), nrow(OccData))
OccData <- OccData[randomIndex, ]
# separate the data into a training set (80%) and a test set (20%)
n <- nrow(OccData)
nTrain <- round(0.8 * n)
trainIndex <- sample(1:n, nTrain)
BRTtrain <- OccData[trainIndex, ]
BRTtest <- OccData[-trainIndex, ]
# remove ISO3 identifier and covert to data frame
BRTtrain <-
BRTtrain %>%
# remove ISO3 column
dplyr::select(-ISO3) %>%
as.data.frame()
BRTtest <-
BRTtest %>%
# remove ISO3 column
#dplyr::select(-ISO3) %>%
as.data.frame()
# make a cluster
cl <- makeCluster(4)
# register the clusters
registerDoSNOW(cl)
# let each cluster read from the environment
clusterExport(cl, c('BRTpred', 'BRTtrain', 'BRTtest'),
envir = environment())
clusterEvalQ(cl, c(library(tidyverse),
library(gbm),
library(dismo),
library(ROCR),
library(ModelMetrics)))
# make an empty list to infill with relative influence values
RIresults <- list()
totalRI <- data.frame()
# make an empty list to infill with predictions of the test set values
PredTest <- list()
totalTest <- data.frame()
# make empty list to infill with predictions of data-deficient values
Predresults <- list()
totalPred <- data.frame()
# make empty list to infill with PDP values
PDPResults <- list()
# run the BRTs
bootend <- 2
foreach (i = 1:bootend) %dopar% {
# randomize the data again
randomI <- sample(1:nrow(BRTtrain), nrow(BRTtrain))
randomTrain <- BRTtrain[randomI, ]
# run cross-validated gbm
cvgbm <-
dismo::gbm.step(data = randomTrain,
gbm.x = 2:19,
gbm.y = 1,
family = 'bernoulli',
tree.complexity = 10,
learning.rate = 0.005,
bag.fraction = 0.5,
n.folds = 10)
# write down the results
CVnonpred <-
data.frame(run = paste(i)) %>%
mutate(cvauc = cvgbm$cv.statistics$discrimination.mean,
cvcorr = cvgbm$cv.statistics$correlation.mean,
intnull = cvgbm$self.statistics$mean.null,
residual_deviance = cvgbm$self.statistics$mean.resid,
dev_exp = (intnull - residual_deviance)/intnull)
# model external metrics
pred <-
predict.gbm(object = cvgbm,
newdata = BRTtest,
n.trees = cvgbm$gbm.call$best.trees,
type = 'response')
# combine all results
CVresults <-
CVnonpred %>%
mutate(evauc = gbm.roc.area(BRTtest$occurrence, pred),
evresdev = calc.deviance(BRTtest$occurrence, pred, calc.mean = TRUE),
evnulldev = calc.deviance(BRTtest$occurrence,
rep(mean(BRTtest$occurrence),
nrow(BRTtest)),
calc.mean = TRUE),
evdev = (evnulldev - evresdev)/evnulldev)
# record predicted values for test set
TestPred <-
BRTtest %>%
dplyr::select(ISO3, occurrence) %>%
mutate(run = paste(i),
PredValue = gbm::predict.gbm(object = cvgbm,
newdata = BRTtest,
n.trees = cvgbm$gbm.call$best.trees,
type = 'response'))
PredTest[[i]] <- TestPred
# record relative influences
relinf <- cvgbm$contributions
relinf$run <- i
RIresults[[i]] <- relinf
# make predictions on data-deficient values
pred <-
BRTpred %>%
dplyr::select(ISO3) %>%
mutate(Prediction = predict(object = cvgbm,
newdata = BRTpred,
n.trees = cvgbm$n.trees,
type = 'response'),
run = paste(i))
Predresults[[i]] <- pred
# bind together all relative influences
RIdf <- RIresults[[i]]
totalRI <- rbind(totalRI, RIdf)
# bind together all test predictions
testdf <- PredTest[[i]]
totalTest <- rbind(totalTest, testdf)
# bind together all predictions
preddf <- Predresults[[i]]
totalPred <- rbind(totalPred, preddf)
# write a csv for each run - this results in duplicates but that will be
# dealt with later
FileNameRI <-
paste('ModelOutputs/BRT/CvGBMRelInf', i, '.csv', sep = '_')
FileNameTest <-
paste('ModelOutputs/BRT/CvGBMTestPred', i, '.csv', sep = '_')
FileNamePred <-
paste('ModelOutputs/BRT/CvGBMPred', i, '.csv', sep = '_')
FileNameCv <-
paste('ModelOutputs/BRT/CvResults', i, '.csv', sep = '_')
write.csv(totalRI, paste(FileNameRI))
write.csv(totalTest, paste(FileNameTest))
write.csv(totalPred, paste(FileNamePred))
write.csv(CVresults, paste(FileNameCv))
# now let's calculate the partial dependence for each variable
# train a gbm model
pdpgbm <- gbm(formula = occurrence ~ .,
distribution = 'bernoulli',
data = BRTtrain,
n.trees = 4000,
interaction.depth = 10,
shrinkage = 0.005,
bag.fraction = 0.5,
cv.folds = 10,
verbose = FALSE)
for(j in names(BRTtrain)[2:19]) {
# create dataframes of pdp values predicted by gbm
PDPdf <-
pdpgbm %>%
pdp::partial(pred.var = paste(j),
grid.resolution = 102,
n.trees = pdpgbm$n.trees,
prob = TRUE)
PDPdf$run <- paste(i)
PDPResults[[j]] <-
as_tibble(PDPdf) %>%
mutate(variable = paste0(j)) %>%
dplyr::rename(independent_value = 1,
pdp_value = 'yhat')
# save each dataframe separately
FileNamePDP <- paste('ModelOutputs/BRT/PDP/PDP', j, i, '.csv', sep = '_')
write.csv(PDPResults[[j]], paste(FileNamePDP))
}
}
stopCluster(cl)
# Part 2: Dynamic geography analysis ------------------------------------------------------
# This section is a logistic regression regressing occurrence as a function of continental
# shelf area, gear-specific landings, mangrove area, and country ID as a grouping factor
DGmod <-
brm(occurrence ~ logShelfAreaShallow + logtotalGearTonnes + logMang + (1|ISO3),
data = OccData,
family = 'bernoulli',
seed = 123)
savedRDS(DGmod, 'ModelOutputs/DGmod.rds')