-
Notifications
You must be signed in to change notification settings - Fork 1
/
1.RF_Bruvs_pres-abs.R
428 lines (318 loc) · 12.1 KB
/
1.RF_Bruvs_pres-abs.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
########################################################
###### Script -- Random Forest - BRUVs data - v1.0 ##############
### Load libraries ----
library(ggplot2)
library(ggthemes)
library(cowplot)
library(randomForest)
library(sp)
library(rgdal)
library(raster)
library(caTools)
library(reshape2)
library(tidyr)
library(car)
library(lattice)
library(dplyr)
library(raster)
library(rasterVis)
library(zoo)
library(sf)
library(fields)
library(ROCR)
library(caret)
# Clear memory ----
rm(list=ls())
### Set directories ----
w.dir <- "Y:/GB_Habitat_Classification"
d.dir <- "Y:/GB_Habitat_Classification/data"
s.dir <- "Y:/GB_Habitat_Classification/spatial_data"
p.dir <- "Y:/GB_Habitat_Classification/plots"
o.dir <- "Y:/GB_Habitat_Classification/outputs"
### Load data ----
df <- read.csv(paste(d.dir, "tidy", "GB_Bruvs_fine_bathy_habitat_dominant_broad.csv", sep='/'))
head(df)
str(df) # check the factors and the predictors
any(is.na(df)) # check for NA's in the data
p <- stack(paste(s.dir, "predictors.tif", sep='/'))
namesp <- read.csv(paste(s.dir, "namespredictors.csv", sep='/'))
namesp
names(p) <- namesp[,2]
names(p)
## Prepare data ----
# remove unneeded columns ---
names(df)
df2 <- df[,c(5:14)]
head(df2)
# change name of class
names(df2)
colnames(df2)[colnames(df2)=="Max_if_2_habitats_have_same"] <- "Class"
names(df2)
str(df2)
levels(df2$Class)
summary(df2)
head(df2)
## Plot predictors correlations by class -----
# matrix scatterplot of just these 13 variables --
scatterplotMatrix(df2[2:10], col = df2$Class)
plot(df2[2:10], col = df2$Class)
legend("center",
legend = levels(df2$Class))
### Check Predicitor correlations ---
# define function mosthighlycorrelated --
# https://little-book-of-r-for-multivariate-analysis.readthedocs.io/en/latest/src/multivariateanalysis.html
# linear correlation coefficients for each pair of variables in your data set,
# in order of the correlation coefficient. This lets you see very easily which pair of variables are most highly correlated.
mosthighlycorrelated <- function(mydataframe,numtoreport)
{
# find the correlations
cormatrix <- cor(mydataframe)
# set the correlations on the diagonal or lower triangle to zero,
# so they will not be reported as the highest ones:
diag(cormatrix) <- 0
cormatrix[lower.tri(cormatrix)] <- 0
# flatten the matrix into a dataframe for easy sorting
fm <- as.data.frame(as.table(cormatrix))
# assign human-friendly names
names(fm) <- c("First.Variable", "Second.Variable","Correlation")
# sort and print the top n correlations
head(fm[order(abs(fm$Correlation),decreasing=T),],n=numtoreport)
}
mosthighlycorrelated(df2[2:10], 9) # This results in only depth, rough and slope 4 not being correlated above 0.95
## MAKE BETTER PLOT -- TO do still -----
b <- bplot(train$aspect8, train$Class)
plot(b)
### Get train and test data ----
sample <- sample.split(df2$flowdir, SplitRatio = 0.75)
train <- subset(df2, sample == TRUE)
test <-subset(df2, sample == FALSE)
dim(train) # [1] 109 10
dim(test) # [1] 35 10
### MODEL 1 ----
### RF - 5 habitat classes ---
# this is using all the habitat classes = 5 in total
# Used only the preds that were not correlated: depth, slope4, roughness
model <- randomForest(Class ~ ., data=train %>% select(c(Class, depth, slope4, roughness)) , ntree=501, proximity=TRUE)
model # OOB = 55.05%
model$importance
model$classes
ptest <- p
names(ptest)
ptest <- dropLayer(p, c(3:7,9))
## Predict ----
test <- raster::predict(ptest, model)
## Plot ----
plot(test)
e <- drawExtent()
testx <- crop(test, e)
plot(testx)
# basic plot using lattice --
# https://pjbartlein.github.io/REarthSysSci/rasterVis01.html
lp <- levelplot(testx)
lp
class(lp) # trellis
#### MODEL 2 ----
### RF - 5 habitat classes ---
# try using all predictors ---
# remove all the Classes that are not SG or MA
levels(df2$Class)
model2 <- randomForest(Class ~ ., data=df2, ntree=501, proximity=T, mtry=3)
model2 # this is OOB = 56.94% for 2001 trees / OOB = 56.94% for 501 trees
model2$importance
# Predict ----
test <- raster::predict(p, model2)
# plot ----
plot(test)
e <- drawExtent()
testx <- crop(test, e)
plot(testx)
# Basic plot using lattice --
lp <- levelplot(testx)
lp
### MODEL 3 ----
### RF - 5 habitat classes ---
# this is using all the habitat classes = 5 in total
# Used all preds except flowdir
model3 <- randomForest(Class ~ ., data=train %>% select(-flowdir) , ntree=501, proximity=TRUE, mtry = 3)
model3 # OOB = 53.21%
model3$importance
ptest <- p
names(ptest)
ptest <- dropLayer(p, c(9))
## Predict ----
test <- raster::predict(ptest, model3)
## Plot ----
plot(test)
e <- drawExtent()
testx <- crop(test, e)
plot(testx)
# basic plot using lattice --
# https://pjbartlein.github.io/REarthSysSci/rasterVis01.html
lp <- levelplot(testx)
lp
class(lp) # trellis
### MODEL 4 ----
### RF - 3 habitat classes : unvegetated, seagrass, macroalgae ---
# Using all preds
# to manipulate factors: https://stackoverflow.com/questions/35088812/combine-sets-of-factors-in-a-dataframe-with-dplyr
model4 <- randomForest(Class ~ ., data=train %>% mutate(Class = car::recode(Class, "c('Unconsolidated', 'Consolidated')='Unvegetated';'Seagrasses' = 'Seagrass'; c('Turf.algae','Macroalgae')='Algae'")),
ntree=1001, proximity=TRUE, mtry = 3)
model4 # OOB = 53.21%
model4$importance
# Remove predictors if needed --
#ptest <- p
#names(ptest)
#ptest <- dropLayer(p, c(9))
## Predict ----
test <- raster::predict(p, model4)
## Plot ----
plot(test)
e <- drawExtent()
testx <- crop(test, e)
plot(testx)
# basic plot using lattice --
# https://pjbartlein.github.io/REarthSysSci/rasterVis01.html
lp <- levelplot(testx)
lp
class(lp) # trellis
### MODEL 5 ----
### RF - 3 habitat classes : unvegetated, seagrass, macroalgae ---
# Using all preds
# to manipulate factors: https://stackoverflow.com/questions/35088812/combine-sets-of-factors-in-a-dataframe-with-dplyr
model5 <- randomForest(Class ~ ., data=train %>% mutate(Class = car::recode(Class, "c('Unconsolidated', 'Consolidated')='Unvegetated';'Seagrasses' = 'Seagrass'; c('Turf.algae','Macroalgae')='Algae'")) %>%
select(-flowdir),
ntree=501, proximity=TRUE, mtry = 3)
model5 # OOB = 53.21%
model5$importance
# Remove predictors if needed --
ptest <- p
names(ptest)
ptest <- dropLayer(p, c(9))
## Predict ----
test <- raster::predict(ptest, model5)
## Plot ----
plot(test)
e <- drawExtent()
testx <- crop(test, e)
plot(testx)
# basic plot using lattice --
# https://pjbartlein.github.io/REarthSysSci/rasterVis01.html
lp <- levelplot(testx)
lp
class(lp) # trellis
### MODEL 6 ----
### RF - 3 habitat classes : unvegetated, seagrass, macroalgae ---
# Using all preds
# to manipulate factors: https://stackoverflow.com/questions/35088812/combine-sets-of-factors-in-a-dataframe-with-dplyr
model6 <- randomForest(Class ~ ., data=train %>% mutate(Class = car::recode(Class, "c('Unconsolidated', 'Consolidated')='Unvegetated';'Seagrasses' = 'Seagrass'; c('Turf.algae','Macroalgae')='Algae'")) %>%
select(c(Class, depth, slope4, roughness)),
ntree=2001, proximity=TRUE, mtry = 3, importance=TRUE)
model6 # OOB = 53.21%
model6$importance
varImpPlot(model6)
# using different code --
# https://www.edureka.co/blog/random-forest-classifier/
# Training using ‘random forest’ algorithm
# Converting ‘Survived’ to a factor
train$Class <- factor(train$Class)
# Set a random seed
set.seed(51)
# had to use less classes, otherwise it wouldn't run, I think because not enough replicates per class
t=train %>% mutate(Class = car::recode(Class, "c('Unconsolidated', 'Consolidated')='Unvegetated';'Seagrasses' = 'Seagrass'; c('Turf.algae','Macroalgae')='Algae'"))
head(t)
TrainData <- t[,c(2,3,9)]
TrainClasses <- t[,1]
model7 <- caret::train(TrainData, TrainClasses, # Class is a function of the variables we decided to include
#data = train, # Use the train data frame as the training data
#preProcess = c("center", "scale"),
method = 'rf',# Use the 'random forest' algorithm
trControl = trainControl(method = 'cv', # Use cross-validation
search = 'random')) # Use 5 folds for cross-validation
model7
model7$finalModel
#model7$importance
v<- varImp(model7, scale =F)
v
varImp(model7)
plot(v, top = 9)
# AREA UNDER THE CURVE --
roc_imp <- filterVarImp(x = train[, 2:10], y = train$Class)
roc_imp
# Remove predictors if needed --
ptest <- p
names(p)
ptest <- dropLayer(p, c(3:7,9))
ptest2 <- dropLayer(p, c(3:5,9))
names(ptest2)
## Predict ----
test <- raster::predict(ptest, model6)
test2 <- raster::predict(ptest, model7)
## Plot ----
plot(test)
e <- drawExtent()
testx <- crop(test, e)
plot(testx)
plot(test2)
e <- drawExtent()
testx <- crop(test2, e)
plot(testx)
# basic plot using lattice --
# https://pjbartlein.github.io/REarthSysSci/rasterVis01.html
lp <- levelplot(testx)
lp
class(lp) # trellis
#### Validation set assessment model 6: looking at confusion matrix ----
#prediction_for_table <- raster::predict(model6, test[,-c(1,4:8,10)])
prediction_for_table6 <- raster::predict(model6, test %>% mutate(Class = car::recode(Class, "c('Unconsolidated', 'Consolidated')='Unvegetated';'Seagrasses' = 'Seagrass'; c('Turf.algae','Macroalgae')='Algae'")) %>%
select(c(Class, depth, slope4, roughness)))
#table(observed=test[,-c(2:10)], predicted=prediction_for_table)
table(observed=test$Class %>%
car::recode("c('Unconsolidated', 'Consolidated')='Unvegetated';'Seagrasses' = 'Seagrass'; c('Turf.algae','Macroalgae')='Algae'"),
predicted=prediction_for_table6)
# confusion matrix
caret::confusionMatrix(test$Class %>%
car::recode("c('Unconsolidated', 'Consolidated')='Unvegetated';'Seagrasses' = 'Seagrass'; c('Turf.algae','Macroalgae')='Algae'"),
prediction_for_table6)
# Validation set assessment #2: ROC curves and AUC
# Needs to import ROCR package for ROC curve plotting:
install.packages("ROCR")
library(ROCR)
# Calculate the probability of new observations belonging to each class
# prediction_for_roc_curve will be a matrix with dimensions data_set_size x number_of_classes
prediction_for_roc_curve <- predict(model6,
test %>% mutate(Class = car::recode(Class, "c('Unconsolidated', 'Consolidated')='Unvegetated';'Seagrasses' = 'Seagrass'; c('Turf.algae','Macroalgae')='Algae'")) %>%
select(c(Class, depth, slope4, roughness)),
type="prob")
# Plot ROC curve ----
# Use pretty colours:
pretty_colours <- c("#F8766D","#00BA38","#619CFF")
# Specify the different classes
classes <- levels(test$Class %>%
car::recode("c('Unconsolidated', 'Consolidated')='Unvegetated';'Seagrasses' = 'Seagrass'; c('Turf.algae','Macroalgae')='Algae'"))
# For each class
for (i in 1:3)
{
# Define which observations belong to class[i]
true_values <- ifelse(test$Class %>%
car::recode("c('Unconsolidated', 'Consolidated')='Unvegetated';'Seagrasses' = 'Seagrass'; c('Turf.algae','Macroalgae')='Algae'")==classes[i],1,0)
# Assess the performance of classifier for class[i]
pred <- prediction(prediction_for_roc_curve[,i],true_values)
perf <- performance(pred, "tpr", "fpr")
if (i==1)
{
plot(perf,main="ROC Curve",col=pretty_colours[i])
}
else
{
plot(perf,main="ROC Curve",col=pretty_colours[i],add=TRUE)
}
# Calculate the AUC and print it to screen
auc.perf <- performance(pred, measure = "auc")
print([email protected])
}
# Confusion matrix Model 7 ----
prediction_for_table7 <- raster::predict(model7, test %>% mutate(Class = car::recode(Class, "c('Unconsolidated', 'Consolidated')='Unvegetated';'Seagrasses' = 'Seagrass'; c('Turf.algae','Macroalgae')='Algae'")) %>%
select(c(Class, depth, slope4, roughness)))
caret::confusionMatrix(test$Class %>%
car::recode("c('Unconsolidated', 'Consolidated')='Unvegetated';'Seagrasses' = 'Seagrass'; c('Turf.algae','Macroalgae')='Algae'"),
prediction_for_table7)