-
Notifications
You must be signed in to change notification settings - Fork 0
/
Kspp_model_NN_density_GRIIDC.Rmd
1602 lines (1261 loc) · 69.8 KB
/
Kspp_model_NN_density_GRIIDC.Rmd
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: 'GoMx _Kogia_ spp. habitat models: Density with neural nets'
author:
- name: Kaitlin Frasier
affiliation: Scripps Institution of Oceanography, UC San Diego
date: "`r format(Sys.time(), '%d %B %Y')`"
output:
html_document:
toc: true
toc_depth: 4
toc_float: true
theme: spacelab
fig_caption: true
bibliography: exportlist.bibtex
csl: plos-computational-biology.csl
---
```{r setup, echo = FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r load packages, echo = FALSE, message = FALSE, warning = FALSE}
library(rgdal)
library(raster)
library(ggplot2)
library(rgeos)
library(mapview)
library(leaflet)
library(psych)
library(broom)
library(plotrix)
library(magrittr)
library(colorRamps)
library(lubridate)
#library(HabitatProject)
library(nnet)
library(caret)
library(parallel)
library(MLmetrics)
library(pracma)
library(grid)
library(knitr)
library(matrixStats)
library(zoo)
library(tmap)
library(scales)
source('F:/GRIIDC_inputs/HabitatProject/R/plot_covarDensity.R')
source('F:/GRIIDC_inputs/HabitatProject/R/weighted_logloss.R')
source('F:/GRIIDC_inputs/HabitatProject/R/multiplot.R')
source('F:/GRIIDC_inputs/HabitatProject/R/plot_missingdata.R')
source('F:/GRIIDC_inputs/HabitatProject/R/plot_cleveland.R')
source('F:/GRIIDC_inputs/HabitatProject/R/plot_timeseries.R')
source('F:/GRIIDC_inputs/HabitatProject/R/transform_covars.R')
source('F:/GRIIDC_inputs/nnet_plot_update.r')
options(stringsAsFactors = FALSE)
# load some preferences
load('F:/GRIIDC_inputs/ModelData/Kspp/setup_info_Kspp.Rdata')
load('F:/GRIIDC_inputs/ModelData/Kspp/KsppMergedData.Rdata')
outDir <- file.path('F:/GRIIDC_inputs/ModelData',SP,'10000//')
inDir <- file.path('F:/GRIIDC_inputs/ModelData',SP,'//')
```
<br>
# 1. Exploratory analysis
<br>
## 1.1 Data Inputs
NOAA SEFSC visual data goes back to 1992, but as shown in the figure below, many predictor variables are only available starting in 2003, therefore earlier visual data is currently excluded from further analyses.
Note: Future work could use monthly climatologies (averages) so that older sightings data could be used. Some dynamic drivers like eddy and front locations would not be able to be considered using that approach.
```{r Missing data, results = 'hide', echo = FALSE, message= FALSE, warning = FALSE}
plotCols1 <-c(7:10,14,16,19,22,23)
covarList<-names(mergedSegments[c(plotCols1)])
varUnits <- c("SST (C)","SSH (m)",expression("Chlorophyll A (mg/m"^3*")"),"MLD (m)", "Salinity (ppm)",
"Current Magnitude (m/sec)", "Upwelling (m/sec)",
"Dist. to Anti-Cyclonic Eddy (km)","Dist. to Cyclonic Eddy (km)")
names(varUnits)<-covarList
plot.missingdata(AcOnlySegments,covarList,
paste0(outDir,'AcousticOnly_',SP),varUnits)
plot.missingdata(VisOnlySegments,covarList,
paste0(outDir,'VisualOnly_',SP),varUnits)
visDataAvailPlot <- paste0(outDir,'/VisualOnly_',SP,'_missingData.png')
```
**Visual data predictor variable availability:**
![](`r visDataAvailPlot`)
<br>
### 1.1.1 Splitting into testing and training sets
The data are split into training and testing sets. In this case, visual data from 2009 and acoustic data from 2013 were used only for testing. Only observations from 2003 or later were used for modeling due to covariate limitations.
```{r test train split, echo = FALSE}
# If you decide from the missing data plots that you want to restrict years going forward:
yearListIdx_AcOnly = as.numeric(format(AcOnlySegments$date,"%Y"))
yearListIdx_VisOnly = as.numeric(format(VisOnlySegments$date,"%Y"))
isVisual <- mergedSegments$Category
keepDates_AcOnly.train <- which(yearListIdx_AcOnly != 2009 &
yearListIdx_AcOnly >= 2003 & yearListIdx_AcOnly <= 2012)
keepDates_AcOnly.test <- which(yearListIdx_AcOnly == 2009 |
yearListIdx_AcOnly == 2013)
keepDatesVisOnly.train <- which(yearListIdx_VisOnly != 2009 &
yearListIdx_VisOnly >= 2003)
keepDatesVisOnly.test <- which(yearListIdx_VisOnly == 2009 |
yearListIdx_VisOnly == 2013)
Train_AcOnly.set <- AcOnlySegments[keepDates_AcOnly.train,]
Train_VisOnly.set<- VisOnlySegments[keepDatesVisOnly.train,]
Test_AcOnly.set<- AcOnlySegments[keepDates_AcOnly.test,]
Test_VisOnly.set<- VisOnlySegments[keepDatesVisOnly.test,]
```
<br>
### 1.1.2 Map of visual sightings data
The visual data selected for modeling are displayed on the map below. Data from 2009 were held back for testing. Blue markers indicate HARP locations.
```{r map inputs, warning = FALSE, echo = FALSE}
# Get test visual sightings
sightingsTrain <- Train_VisOnly.set[Train_VisOnly.set$Density>0,c('lat','long','date')]
sightingsTest <- Test_VisOnly.set[Test_VisOnly.set$Density>0,c('lat','long','date')]
HARPsites <- unique(Train_AcOnly.set[c('lat','long')])
pal <-colorFactor(palette = "RdYlGn",
domain = c(2003,2004,2009,2012,2014))
map1 <- leaflet() %>% setView(lng = -89.4, lat = 27.0, zoom = 6)%>%
addProviderTiles(providers$Esri.OceanBasemap) %>%
addCircleMarkers(data = sightingsTrain, lng = ~ long, lat = ~ lat,color = ~pal(year(date)),
stroke = TRUE, fillOpacity = 0.8, group = 'Training Set',radius = 4)%>%
addCircleMarkers(data = sightingsTest, lng = ~ long, lat = ~ lat,color = ~pal(year(date)),
stroke = TRUE, fillOpacity = 0.8, group = 'Test Set',radius = 4)%>%
addMarkers(data = HARPsites, lng = ~ long, lat = ~ lat) %>%
addLegend(pal = pal,values = c(2003,2004,2009,2012,2014),title = 'Year')
map1
```
<br>
### 1.1.3 Time series of acoustic data
The time series below show timeseries of estimated densities from passive acoustic data used for modeling (Densities were calculated following methods detailed in @RN806). Data from 2011 and 2012 were used for training, and 2013 data was held back for testing.
<br>
**Acoustic Timeseries:**
```{r plot timeseries, message = FALSE, echo = FALSE}
plot.timeseries(siteList,outDir,AcOnlySegments)
MCTS <- paste0(outDir,SP,'_Timeseries_Site_MC.png')
GCTS <- paste0(outDir,SP,'_Timeseries_Site_GC.png')
DTTS <- paste0(outDir,SP,'_Timeseries_Site_DT.png')
```
![](`r MCTS`)
![](`r GCTS`)
![](`r DTTS`)
<br>
## 1.2 Examination of covariates
```{r remove outliers, message = FALSE, results = 'hide', echo = FALSE}
### Identify Outliers
# Replace extreme outliers (bad data) with NaNs.
outlierList <-which(Train_AcOnly.set$CHL< -10)
Train_AcOnly.set$CHL[outlierList] <- NaN
outlierList <-which(Train_AcOnly.set$Density > 100000)
Train_AcOnly.set$Density[outlierList] <- NaN
outlierList <-which(Test_AcOnly.set$CHL< -10)
Test_AcOnly.set$CHL[outlierList] <- NaN
outlierList <-which(Test_AcOnly.set$Density>100000)
Test_AcOnly.set$Density[outlierList] <- NaN
outlierList <-which(Train_VisOnly.set$CHL< -10)
Train_VisOnly.set$CHL[outlierList] <- NaN
outlierList <-which(Train_VisOnly.set$Density>100000)
Train_VisOnly.set$Density[outlierList] <- NaN
outlierList <-which(Test_VisOnly.set$CHL< -10)
Test_VisOnly.set$CHL[outlierList] <- NaN
outlierList <-which(Test_VisOnly.set$Density>100000)
Test_VisOnly.set$Density[outlierList] <- NaN
```
<br>
### 1.2.1 Covariate distribution check
<br>
**Distributions of covariates from acoustic observations (training data only):**
```{r dot plots, eval = TRUE, message = FALSE, results = 'hide', echo = FALSE}
plot.cleveland(Train_AcOnly.set,covarList,FALSE,paste0(outDir,'AcousticOnly_',SP),varUnits)
plot.cleveland(Train_VisOnly.set,covarList,FALSE,paste0(outDir,'VisualOnly_',SP),varUnits)
ACclevelandPlot<-paste0(outDir,'AcousticOnly_',
SP,'_clevelandDots_noTransform.png')
VisclevelandPlot<-paste0(outDir,'VisualOnly_',
SP,'_clevelandDots_noTransform.png')
```
![](`r ACclevelandPlot`)
<br>
**Distributions of covariates from the visual observations (training data only):**
![](`r VisclevelandPlot`)
<br>
Some of these covariates are more or less interrelated. Correlations are examined in the figure below. Numbers closer to 1 above the diagonal in the figure below represent correlation coefficients. If a pair of covariates is highly-correlated only one should typically be used in the model.
```{r correlation plots, eval = TRUE, message = FALSE, warning = FALSE, results = 'hide', echo = FALSE}
covarList2 <- c("Density","SST","SSH","CHL",
"HYCOM_MLD","HYCOM_SALIN_0","HYCOM_MAG_0",
"HYCOM_UPVEL_50",
"Neg_EddyDist","Pos_EddyDist",
"fac1","fac2","EffectiveArea")
# restrict covariates again to limited set
Train_AcOnly.set2<- Train_AcOnly.set[,covarList2]
Test_AcOnly.set2<- Test_AcOnly.set[,covarList2]
Train_VisOnly.set2<- Train_VisOnly.set[,covarList2]
Test_VisOnly.set2<- Test_VisOnly.set[,covarList2]
# without transform
png(paste(outDir,SP,'_correlations_noTransform_AcOnly.png',sep=''), width = 2000, height = 1600)
pairs.panels(Train_AcOnly.set2[,1:(length(covarList2)-3)], ellipses=FALSE, method = "spearman",cex.cor=.75)
dev.off()
png(paste(outDir,SP,'_correlations_noTransform_visOnly.png',sep=''), width = 2000, height = 1600)
pairs.panels(Train_VisOnly.set2[,1:(length(covarList2)-3)], ellipses=FALSE, method = "spearman",cex.cor=.75)
dev.off()
covarPlot <-paste0(outDir,SP,'_correlations_noTransform_AcOnly.png')
```
<br>
**Covariate Correlations:**
![](`r covarPlot`)
<br>
### 1.2.2 Transformation of predictor variables
Some variables, including chlorophyll, mixed layer depth and distance to fronts are highly skewed and were log-transformed for input to GAMs.
```{r transform covars, message = FALSE, results = 'hide', echo = FALSE, warning = FALSE}
# covarList2 <- c("Density","SST","SSH","CHL",
# "HYCOM_MLD","HYCOM_SALIN_0","HYCOM_MAG_0",
# "HYCOM_UPVEL_50",
# "Neg_EddyDist", "PosEddyDist",
# "fac1","fac2")
transformList <- c("none","none","none","log10",
"log10","none","log10",
"none",
"none","none",
"none","none","none")
transformedCovars_AcOnly.train <-
transform.covars(Train_AcOnly.set2,covarList2,transformList)
transformedCovars_AcOnly.test <-
transform.covars(Test_AcOnly.set2,covarList2,transformList)
transformedCovars_VisOnly.train <-
transform.covars(Train_VisOnly.set2,covarList2,transformList)
transformedCovars_VisOnly.test <-
transform.covars(Test_VisOnly.set2,covarList2,transformList)
# Generate correlation plots with transform
png(paste(outDir,SP,'_correlations_withTransform_AcOnly.png',sep=''),
width = 2000, height = 1600)
pairs.panels(transformedCovars_AcOnly.train[,1:(length(covarList2)-2)],
ellipses=FALSE, method = "spearman",cex.cor=.75)
dev.off()
png(paste(outDir,SP,'_correlations_withTransform_visOnly.png',sep=''),
width = 2000, height = 1600)
pairs.panels(transformedCovars_VisOnly.train[,1:(length(covarList2)-2)],
ellipses=FALSE, method = "spearman",cex.cor=.75)
dev.off()
```
```{r transformed dot plots, eval = TRUE, message = FALSE, results = 'hide', echo = FALSE}
# Plotting the transformed variables:
plotCols = colnames(transformedCovars_AcOnly.train)[c(2:10)]
names(varUnits)<-plotCols
varUnits["log10_HYCOM_MAG_0"]<-expression("log"[10]*"(Current Magnitude (m/sec))")
varUnits["log10_HYCOM_MLD"]<- expression("log"[10]*"(MLD (m))")
varUnits["log10_CHL"] <-expression("log"[10]*"(Chorophyll A (mg/m"^3*"))")
plot.cleveland(transformedCovars_AcOnly.train,
plotCols,TRUE,paste0(outDir,'AcousticOnly_',SP),varUnits)
plot.cleveland(transformedCovars_VisOnly.train,
plotCols,TRUE,paste0(outDir,'VisualOnly_',SP),varUnits)
```
<br>
### 1.2.3 Preliminary check of predictive power
To get an idea of the basic predictive power of these covariates, we can look at presence/absence relative to each variable. This also provides an opportunity to look at the range of values observed for each covariate in the visual and acoustic datasets. In the plots below dotted lines indicate the distribution of each covariate when `r SPLong` were present, and solid lines indicate the distribution when `r SPLong` were absent. Note that these plots do not account for effort.
```{r presence absence histograms, eval = TRUE, message = FALSE, results = 'hide', echo = FALSE}
plot.covarDensity(transformedCovars_AcOnly.train[,2:10],
colnames(transformedCovars_AcOnly.train[2:10]),
transformedCovars_AcOnly.train$Density,paste0(outDir,'AcousticOnly_',SP),varUnits)
plot.covarDensity(transformedCovars_VisOnly.train[,2:10],
colnames(transformedCovars_VisOnly.train[,2:10]),
transformedCovars_VisOnly.train$Density,paste0(outDir,'VisualOnly_',SP),varUnits)
acKernels <-paste0(outDir,'/AcousticOnly_',SP,'_density_pres_abs.png')
visKernels <- paste0(outDir,'/VisualOnly_',SP,'_density_pres_abs.png')
```
<br>
**Acoustic kernel densities:**
![](`r acKernels`)
<br>
**Visual kernel densities:**
![](`r visKernels`)
<br>
```{r load detection prob, echo = FALSE}
visDetProbData<-paste0(inDir,SP,'sightwTrunc_GU.Rdata')
load(visDetProbData)
visDetProb <- detFun[[bestModelIdx]]$fitted[1]
visDetProbFigure <- paste0(inDir,SP,'sightwTrunc_GU.png')
```
**Best visual detection probability model for `r SPLong`:**
![](`r visDetProbFigure`)
<br>
# 2. Model Fitting
Models were fit using avnnet from the caret package in R.
```{r model setup, echo = FALSE, message = FALSE, results = 'hide'}
yAcOnly <- transformedCovars_AcOnly.train$Density
yVisOnly <- transformedCovars_VisOnly.train$Density
visDetProb <- detFun[[bestModelIdx]]$fitted[1]
transformedCovars_AcOnly.train$yAcOnly<- transformedCovars_AcOnly.train$Density
transformedCovars_VisOnly.train$yVisOnly<-transformedCovars_VisOnly.train$Density
transformedCovars_AcOnly.train$yAcOnlySqrt <-sqrt(transformedCovars_AcOnly.train$Density)
transformedCovars_VisOnly.train$yVisOnlySqrt <-sqrt(transformedCovars_VisOnly.train$Density)
transformedCovars_AcOnly.test$yAcOnly <- transformedCovars_AcOnly.test$Density
transformedCovars_VisOnly.test$yVisOnly <- transformedCovars_VisOnly.test$Density
transformedCovars_AcOnly.test$yAcOnlySqrt <-sqrt(transformedCovars_AcOnly.test$Density)
transformedCovars_VisOnly.test$yVisOnlySqrt <-sqrt(transformedCovars_VisOnly.test$Density)
# Remove NaNs
goodData_Ac <- which(!is.na(rowSums(transformedCovars_AcOnly.train)))
AcOnly.train.NoNa <- transformedCovars_AcOnly.train[goodData_Ac,]
goodData_Vis <- which(!is.na(rowSums(transformedCovars_VisOnly.train)))
VisOnly.train.NoNa <- transformedCovars_VisOnly.train[goodData_Vis,]
goodData_Ac_test <- which(!is.na(rowSums(transformedCovars_AcOnly.test)))
AcOnly.test.NoNa <- transformedCovars_AcOnly.test[goodData_Ac_test,]
goodData_Vis_test <- which(!is.na(rowSums(transformedCovars_VisOnly.test)))
VisOnly.test.NoNa <- transformedCovars_VisOnly.test[goodData_Vis_test,]
```
<br>
```{r Scale all the data, echo = FALSE}
# NNs don't do well with unscaled data. Scale it and then unscale it at the end.
# Scale training data for the NN
covars_AcOnly_max.train <- apply(AcOnly.train.NoNa, 2, max, na.rm = TRUE)
covars_AcOnly_min.train <- apply(AcOnly.train.NoNa, 2, min, na.rm = TRUE)
covars_AcOnly_mean.train <- apply(AcOnly.train.NoNa, 2, mean, na.rm = TRUE)
covars_AcOnly_std.train <- apply(AcOnly.train.NoNa, 2, std)
covars_VisOnly_max.train <- apply(VisOnly.train.NoNa, 2, max, na.rm = TRUE)
covars_VisOnly_min.train <- apply(VisOnly.train.NoNa, 2, min, na.rm = TRUE)
covars_VisOnly_mean.train <- apply(VisOnly.train.NoNa, 2, mean, na.rm = TRUE)
covars_VisOnly_std.train <- apply(VisOnly.train.NoNa, 2, std)
# Scale Ac only training data for the NN
AcOnly_train_scaled <- as.data.frame(scale(AcOnly.train.NoNa,
center = covars_AcOnly_min.train,
scale = covars_AcOnly_max.train-covars_AcOnly_min.train))
AcOnly_train_scaled$yAcOnly <-log(AcOnly.train.NoNa$yAcOnly+1)/log(covars_AcOnly_max.train['yAcOnly'])
AcOnly_train_scaled$yAcOnly [is.infinite(AcOnly_train_scaled$yAcOnly )]<-0
AcOnly_train_scaled$yAcOnlySqrt <- AcOnly.train.NoNa$yAcOnlySqrt
# Scale Vis only training data for the NN
VisOnly_train_scaled <- as.data.frame(scale(VisOnly.train.NoNa,
center = covars_VisOnly_min.train,
scale = covars_VisOnly_max.train-covars_VisOnly_min.train))
VisOnly_train_scaled$yVisOnly <- log(VisOnly.train.NoNa$yVisOnly+1)/log(covars_VisOnly_max.train['yVisOnly'])
VisOnly_train_scaled$yVisOnly[is.infinite(VisOnly_train_scaled$yVisOnly)]<-0
VisOnly_train_scaled$yVisOnlySqrt <- VisOnly.train.NoNa$yVisOnlySqrt
# Scale Ac only test data for the NN
AcOnly_test_scaled <- as.data.frame(scale(AcOnly.test.NoNa,
center = covars_AcOnly_min.train,
scale = covars_AcOnly_max.train-covars_AcOnly_min.train))
AcOnly_test_scaled$yAcOnly <- log(AcOnly.test.NoNa$yAcOnly+1)/log(covars_AcOnly_max.train['yAcOnly'])
AcOnly_test_scaled$yAcOnly[is.infinite(AcOnly_test_scaled$yAcOnly)]<-0
AcOnly_test_scaled$yAcOnlySqrt <- AcOnly.test.NoNa$yAcOnlySqrt
# Scale Vis only test data for the NN
VisOnly_test_scaled <- as.data.frame(scale(VisOnly.test.NoNa,
center = covars_VisOnly_min.train,
scale = covars_VisOnly_max.train-covars_VisOnly_min.train))
VisOnly_test_scaled$yVisOnly <- log(VisOnly.test.NoNa$yVisOnly+1)/log(covars_VisOnly_max.train['yVisOnly'])
VisOnly_test_scaled$yVisOnly[is.infinite(VisOnly_test_scaled$yVisOnly )]<-0
VisOnly_test_scaled$yVisOnlySqrt <- VisOnly.test.NoNa$yVisOnlySqrt
n <- names(AcOnly_test_scaled)
# save ranges of each scaled covariate in training set (max and min)
AcOnlyRangesMax <- apply(AcOnly_train_scaled, MARGIN = 2,
function(x) max(x, na.rm =TRUE))
AcOnlyRangesMin <- apply(AcOnly_train_scaled, MARGIN = 2,
function(x) min(x, na.rm =TRUE))
VisOnlyRangesMax <- apply(VisOnly_train_scaled, MARGIN = 2,
function(x) max(x, na.rm =TRUE))
VisOnlyRangesMin <- apply(VisOnly_train_scaled, MARGIN = 2,
function(x) min(x, na.rm=TRUE))
```
<br>
## 2.1 Run Models
```{r, echo = FALSE}
# set up model params
model1.indices <- c(2:10)
nMax1 <- length(model1.indices)
layerSizeList <- c(4,6,8,10,12,14)
trainRepeats <- 25
```
Run NNs on Acoustic and Visual datasets.
Models have the following characteristics:
* `R trainRepeats` averaged repeats with random node initalization
* Include `r length(model1.indices)` covariates
* One hidden layer
* Weighted training data
* Hidden node layer sizes from `r min(layerSizeList)` to `r max(layerSizeList)` were tested in 2 node increments to search for optimal network size.
<br>
```{r, echo = FALSE}
# initialize empty structure for model storage
nn_AcOnly<-NULL
nn_VisOnly<-NULL
# initialize empty structure for error scores and predictions
MSE <- NULL
pr <- NULL
```
```{r Ac only Model, results = 'hide', message = FALSE, eval = FALSE, echo = FALSE}
## ACOUSTIC ONLY
AcCounter <- 0
f.AcOnly_NN1 <- as.formula(paste("yAcOnly ~", paste(n[model1.indices], collapse = " + ")))
# Iterate over a range of hidden layer sizes between 2 and 14 nodes.
for (layerSize in layerSizeList){
AcCounter <- AcCounter + 1
# put together the formula
# train network
nn_AcOnly[[AcCounter]] <- avNNet(f.AcOnly_NN1, data = AcOnly_train_scaled,
size = layerSize,
repeats = trainRepeats,
na.action = na.omit,
rang = 0.7,
decay = 0.0001,
maxit = 10000,
trace = FALSE)
# predict on train data and estimate Mean Squared Error (MSE)
pr$nn_AcOnly_train[[AcCounter]] <- predict(nn_AcOnly[[AcCounter]],
AcOnly_train_scaled[,model1.indices])
pr$nn_AcOnly_train[[AcCounter]][pr$nn_AcOnly_train[[AcCounter]] <0]<-0
MSE$nn_AcOnly_train[[AcCounter]] <- mean(abs(AcOnly_train_scaled$yAcOnly -
pr$nn_AcOnly_train[[AcCounter]]),na.rm = TRUE)
# predict on test data and estimate MSE
pr$nn_AcOnly_test[[AcCounter]] <- predict(nn_AcOnly[[AcCounter]],
AcOnly_test_scaled[,model1.indices])
pr$nn_AcOnly_test[[AcCounter]][pr$nn_AcOnly_test[[AcCounter]] <0]<-0
MSE$nn_AcOnly_test[[AcCounter]] <- mean(abs(exp(log(covars_AcOnly_max.train['yAcOnly'])*
(AcOnly_test_scaled$yAcOnly -
pr$nn_AcOnly_test[[AcCounter]]))),na.rm = TRUE)
}
```
```{r Vis only model, eval = FALSE, echo = FALSE}
## VISUAL ONLY
modelCounter <- 0
# put together the formula
f.VisOnly_NN1 <- as.formula(paste("yVisOnly ~", paste(n[model1.indices], collapse = " + ")))
for (layerSize in layerSizeList){
modelCounter <- modelCounter + 1
# train network
nn_VisOnly[[modelCounter]] <- avNNet(f.VisOnly_NN1, VisOnly_train_scaled,
size = layerSize,
repeats = trainRepeats,
na.action = na.omit,
rang = 0.7,
decay = 0.0001,
maxit = 10000,
trace = FALSE)
# predict on train data and estimate MSE
pr$nn_VisOnly_train[[modelCounter]] <- predict(nn_VisOnly[[modelCounter]],
VisOnly_train_scaled[,model1.indices])
pr$nn_VisOnly_train[[modelCounter]][ pr$nn_VisOnly_train[[modelCounter]]<0]<-0
MSE$nn_VisOnly_train[[modelCounter]] <- mean(
abs(exp(log(covars_VisOnly_max.train['yVisOnly'])*
(VisOnly_train_scaled$yVisOnly -
pr$nn_VisOnly_train[[modelCounter]]))),na.rm = TRUE)
# predict on test data and estimate MSE
pr$nn_VisOnly_test[[modelCounter]] <- predict(nn_VisOnly[[modelCounter]],
VisOnly_test_scaled[,model1.indices])
pr$nn_VisOnly_test[[modelCounter]][ pr$nn_VisOnly_test[[modelCounter]]<0]<-0
MSE$nn_VisOnly_test[[modelCounter]] <- mean(
abs(exp(log(covars_VisOnly_max.train['yVisOnly'])*
(VisOnly_test_scaled$yVisOnly -
pr$nn_VisOnly_test[[modelCounter]]))),na.rm = TRUE)
cat(paste("Done with VisOnly model iteration ",
modelCounter, " of ", length(layerSizeList),
": Layer Size = ", layerSize, "\n"))
}
```
<br>
```{r save models, eval = FALSE, echo = FALSE}
# Save models if re-calculating everything
save(nn_AcOnly,MSE,pr,
file = paste(outDir,SP,'_AcOnly_NN_density_noWeights.Rdata',sep=''))
save(nn_VisOnly,MSE,pr,
file = paste(outDir,SP,'_VisOnly_NN_density_noWeights.Rdata',sep=''))
```
```{r load models, eval = TRUE, echo = FALSE}
# alternative if models are already calculated
load(paste0(outDir,SP,'_AcOnly_NN_density_noWeights.Rdata'))
load(paste0(outDir,SP,'_VisOnly_NN_density_noWeights.Rdata'))
```
<br>
## 2.2 Model Comparisons
Models were compared using mean absolute error (MAE) to compare predicted and observed density in the test data.
```{r model plots,echo = FALSE}
windowsFonts(A = windowsFont("Times New Roman"))
RMSE <- NULL
MAE <- NULL
wRMSE <- NULL
wMAE <- NULL
modelCounter <-1
for (modelCounter in 1:length(nn_AcOnly)){
#Visual on Visual
pr$nn_VisOnly_test_VisData[[modelCounter]] <-(exp(log(covars_VisOnly_max.train['yVisOnly'])*
predict(nn_VisOnly[[modelCounter]],
VisOnly_test_scaled[,model1.indices],
na.action = na.omit)))-1
pr$nn_VisOnly_test_VisData[[modelCounter]][pr$nn_VisOnly_test_VisData[[modelCounter]]<0]<-0
RMSE$nn_VisOnly_test_VisData[[modelCounter]] <- sqrt(mean(
(VisOnly.test.NoNa$yVisOnly -
pr$nn_VisOnly_test_VisData[[modelCounter]])^2,na.rm = TRUE))
# Visual on Acoustic
pr$nn_VisOnly_test_AcData[[modelCounter]] <-(exp(log(covars_VisOnly_max.train['yVisOnly'])*
predict(nn_VisOnly[[modelCounter]],
AcOnly_test_scaled[,model1.indices],
na.action = na.omit)))-1
pr$nn_VisOnly_test_AcData[[modelCounter]][pr$nn_VisOnly_test_AcData[[modelCounter]]<0]<-0
RMSE$nn_VisOnly_test_AcData[[modelCounter]] <- sqrt(mean(
(AcOnly.test.NoNa$yAcOnly -
pr$nn_VisOnly_test_AcData[[modelCounter]])^2,na.rm = TRUE))
#Acoustic on Visual
pr$nn_AcOnly_test_VisData[[modelCounter]] <-(exp(log(covars_AcOnly_max.train['yAcOnly'])*
predict(nn_AcOnly[[modelCounter]],
VisOnly_test_scaled[,model1.indices],
na.action = na.omit)))-1
pr$nn_AcOnly_test_VisData[[modelCounter]][pr$nn_AcOnly_test_VisData[[modelCounter]]<0]<-0
RMSE$nn_AcOnly_test_VisData[[modelCounter]] <- sqrt(mean(
(VisOnly.test.NoNa$yVisOnly -
pr$nn_AcOnly_test_VisData[[modelCounter]])^2,na.rm = TRUE))
# Acoustic on Acoustic
pr$nn_AcOnly_test_AcData[[modelCounter]] <-(exp(log(covars_AcOnly_max.train['yAcOnly'])*
predict(nn_AcOnly[[modelCounter]],
AcOnly_test_scaled[,model1.indices],
na.action = na.omit)))-1
pr$nn_AcOnly_test_AcData[[modelCounter]][pr$nn_AcOnly_test_AcData[[modelCounter]]<0]<-0
RMSE$nn_AcOnly_test_AcData[[modelCounter]] <- sqrt(mean(
(AcOnly.test.NoNa$yAcOnly -
pr$nn_AcOnly_test_AcData[[modelCounter]])^2,na.rm = TRUE))
}
RMSEtable <- rbind(RMSE$nn_AcOnly_test_AcData,RMSE$nn_AcOnly_test_VisData,RMSE$nn_VisOnly_test_VisData,RMSE$nn_VisOnly_test_AcData)
colnames(RMSEtable)<- layerSizeList
rownames(RMSEtable)<- c("Acoustic - Acoustic test data","Acoustic - Visual test data","Visual - Visual test data","Visual - Acoustic test data")
print('RMSE (lower is better)')
print(RMSEtable, digits = 3)
```
```{r best model index, echo = FALSE}
best_AcOnly_ModelIndex <-which.min(RMSE$nn_AcOnly_test_AcData)
print(paste(c('Best acoustic model has', layerSizeList[best_AcOnly_ModelIndex],
'nodes.'),collapse = " "))
best_VisOnly_ModelIndex <-which.min(RMSE$nn_VisOnly_test_VisData)
print(paste(c('Best visual model has', layerSizeList[best_VisOnly_ModelIndex],
'nodes.'),collapse = " "))
```
<br>
## 2.3 Variable Importance
For the best model in each category, the importance of each input variable was calculated across the 50 model iterations.
```{r, Variable Importance, echo = FALSE, eval = TRUE}
Ac_importance_avg <-varImp(nn_AcOnly[[best_AcOnly_ModelIndex]])
Vis_importance_avg <-varImp(nn_VisOnly[[best_VisOnly_ModelIndex]])
AcOnly_node_mean<-NULL
AcOnly_node_cv<-NULL
VisOnly_node_mean<-NULL
VisOnly_node_cv<-NULL
for (iNode in 1:length(model1.indices)) {
thisSet <- (1:trainRepeats)+(trainRepeats*(iNode-1))
AcOnly_node_mean[iNode] <- mean(Ac_importance_avg$Overall[thisSet])
AcOnly_node_cv[iNode] <- std(Ac_importance_avg$Overall[thisSet])/mean(Ac_importance_avg$Overall[thisSet])
VisOnly_node_mean[iNode] <- mean(Vis_importance_avg$Overall[thisSet])
VisOnly_node_cv[iNode] <- std(Vis_importance_avg$Overall[thisSet])/mean(Vis_importance_avg$Overall[thisSet])
}
mean_var_importance<-NULL
mean_var_importance$AcOnly <- AcOnly_node_mean
mean_var_importance$VisOnly <- VisOnly_node_mean
mean_var_importance<-as.data.frame(mean_var_importance)
row.names(mean_var_importance)<-n[model1.indices]
cv_var_importance<-NULL
cv_var_importance$AcOnly <- AcOnly_node_cv
cv_var_importance$VisOnly <- VisOnly_node_cv
cv_var_importance<-as.data.frame(cv_var_importance)
row.names(cv_var_importance)<-n[model1.indices]
kable(mean_var_importance,'markdown',digits = 1)
```
<br>
```{r plot acoustic network, eval = TRUE, message = FALSE, warning = FALSE, results = 'hide', echo = FALSE, fig.width = 14, fig.height = 8}
n2 = varUnits[n[model1.indices]]
n3 = c("SST","SSH","CHL","MLD","SAL","CUR","Upwell","-Eddy","+Eddy")
png(paste(outDir,SP,'_AcNetwork.png',sep=''), res = 300,width = 5, height = 4, units = "in")
par(mar=c(1,1,1,1),family = 'serif')
NNFitVals <- NULL
for (iN in c(1:trainRepeats)){
NNFitVals[iN] <- nn_AcOnly[[best_AcOnly_ModelIndex]]$model[[iN]]$value
}
bestNetwork <- which.min(NNFitVals)
plot.nnet(nn_AcOnly[[best_AcOnly_ModelIndex]]$model[[bestNetwork]],x.lab = n3, y.lab = bquote(hat("D")),bias = F,cex=1.3,circle.col='gray',bord.col = 'darkgray',
neg.col = 'red',node.labs = FALSE,circle.cex = 3, alpha.val =.8, max.sp = TRUE)
dev.off()
acNetFig <-paste0(outDir,SP,'_AcNetwork.png')
```
***Best acoustic network:***
![](`r acNetFig`)
<br>
```{r plot visual network, eval = TRUE, message = FALSE, warning = FALSE, results = 'hide', echo = FALSE, fig.width = 14, fig.height = 8}
n2 = varUnits[n[model1.indices]]
n3 = c("SST","SSH","CHL","MLD","SAL","CUR","Upwell","-Eddy","+Eddy")
png(paste(outDir,SP,'_VisNetwork.png',sep=''), res = 300,width = 5, height = 4, units = "in")
par(mar=c(1,1,1,1),family = 'serif')
NNFitVals <- NULL
for (iN in c(1:trainRepeats)){
NNFitVals[iN] <- nn_VisOnly[[best_VisOnly_ModelIndex]]$model[[iN]]$value
}
bestNetwork <- which.min(NNFitVals)
plot.nnet(nn_AcOnly[[best_VisOnly_ModelIndex]]$model[[bestNetwork]],x.lab = n3, y.lab = bquote(hat("D")),bias = F,cex=1.3,circle.col='gray',bord.col = 'darkgray',
neg.col = 'red',node.labs = FALSE,circle.cex = 3, alpha.val =.8, max.sp = TRUE)
dev.off()
visNetFig <-paste0(outDir,SP,'_VisNetwork.png')
```
***Best visual network:***
![](`r visNetFig`)
<br>
# 3. Model Predictions
## 3.1 Temporal predictions
Predictions were made on the acoustic test dataset, and compared with actual observations for 2013. The predicted density of animals at each site was compared with the estimated daily density from the pasive acoustic record.
<br>
### 3.1.1 Acoustic-only prediction
```{r Ac Temporal Predict, echo = FALSE, warning = FALSE, message = FALSE}
# Predict on acoustic test data, using acoustic only model for comparison...
allCovars <- NA
allCovars <- rbind(AcOnly_train_scaled,
AcOnly_test_scaled)
allCovars$fac2 <- c(Train_AcOnly.set$fac2[goodData_Ac],Test_AcOnly.set$fac2[goodData_Ac_test])
allCovars$date <- c(Train_AcOnly.set$date[goodData_Ac],Test_AcOnly.set$date[goodData_Ac_test])
compAcSet_MC_all <- which((allCovars$fac2)<=5)
compAcSet_GC_all <- which((allCovars$fac2)>5 & (allCovars$fac2)<=10)
compAcSet_DT_all <- which((allCovars$fac2)>10 &
(allCovars$fac2)<=16)
allObservations<-c(Train_AcOnly.set$Density[goodData_Ac],
Test_AcOnly.set$Density[goodData_Ac_test])
allTheDays = seq(min(Train_AcOnly.set$date),max(Test_AcOnly.set$date), by="days")
# Predict in time
dateTicks = as.POSIXct(c('2013-01-01 GMT','2013-04-01 GMT',
'2013-07-01 GMT','2013-10-01 GMT',
'2014-01-01 GMT'))
dateLabels = c('Jan. 2013','Apr. 2013','Jul. 2013','Oct 2013','Jan. 2014')
predAcOnly_MC <-NULL
predAcOnly_GC <-NULL
predAcOnly_DT <-NULL
reducedData_MC <- allCovars[compAcSet_MC_all,model1.indices]
predAcOnly_MC <- exp(unname(predict(nn_AcOnly[[best_AcOnly_ModelIndex]],
reducedData_MC))*log(covars_AcOnly_max.train['yAcOnly']))-1
predAcOnly_MC[predAcOnly_MC<0]=0
reducedData_GC <- allCovars[compAcSet_GC_all,model1.indices]
predAcOnly_GC <- exp(unname(predict(nn_AcOnly[[best_AcOnly_ModelIndex]],
reducedData_GC))*log(covars_AcOnly_max.train['yAcOnly']))-1
predAcOnly_GC[predAcOnly_GC<0]=0
reducedData_DT <- allCovars[compAcSet_DT_all,model1.indices]
predAcOnly_DT <- exp(unname(predict(nn_AcOnly[[best_AcOnly_ModelIndex]],
reducedData_DT))*log(covars_AcOnly_max.train['yAcOnly']))-1
predAcOnly_DT[predAcOnly_DT<0]=0
predVar_MC <- NULL
predVar_GC <- NULL
predVar_DT <- NULL
myYmax <- 125#ceiling(max(c(predAcOnly_MC,predAcOnly_GC,predAcOnly_DT),na.rm = TRUE))
for (iMod in c(1:trainRepeats)){
predVar_MC[[iMod]] <- predict(nn_AcOnly[[best_AcOnly_ModelIndex]]$model[[iMod]],
reducedData_MC)*
covars_AcOnly_max.train['yAcOnly']
predVar_MC[[iMod]][predVar_MC[[iMod]]<0] = 0
predVar_GC[[iMod]] <- predict(nn_AcOnly[[best_AcOnly_ModelIndex]]$model[[iMod]],
reducedData_GC)*
covars_AcOnly_max.train['yAcOnly']
predVar_GC[[iMod]][predVar_GC[[iMod]]<0] = 0
predVar_DT[[iMod]] <- predict(nn_AcOnly[[best_AcOnly_ModelIndex]]$model[[iMod]],
reducedData_DT)*
covars_AcOnly_max.train['yAcOnly']
predVar_DT[[iMod]][predVar_DT[[iMod]]<0] = 0
}
# AcOnly_predictionSet <- data.frame(unique(Test_AcOnly.set$date[goodData_Ac_test]))
# AcOnlyGoodTimes <- Test_AcOnly.set$date[goodData_Ac_test]
# colnames(AcOnly_predictionSet) <-"date"
n1MC <- length(predVar_MC[[1]])
predVar_MC_DF <- structure(predVar_MC, row.names = c(NA, -n1MC), class = "data.frame")
n1GC <- length(predVar_GC[[1]])
predVar_GC_DF <- structure(predVar_GC, row.names = c(NA, -n1GC), class = "data.frame")
n1DT <- length(predVar_DT[[1]])
predVar_DT_DF <- structure(predVar_DT, row.names = c(NA, -n1DT), class = "data.frame")
allCovars$observations <- allObservations
allCovars$observations_smooth <- rollmean(allObservations,k = 7,fill=NA)
allCovars$Legend <- "Predictions"
allCovars$DataGroup <- "Observations"
allCovars$DE <- "Density"
AcOnly_predictionSet <- data.frame(allTheDays)
colnames(AcOnly_predictionSet) <-"date"
AcOnly_predictionSet$MC <- NA
AcOnly_predictionSet$predSd_MC <- NA
MC_times <- allCovars$date[compAcSet_MC_all]
m1 <- match(MC_times,allTheDays)
AcOnly_predictionSet$MC[m1] <-predAcOnly_MC
AcOnly_predictionSet$predSd_MC[m1] <- rowSds(data.matrix(predVar_MC_DF),na.rm=TRUE)#/sqrt(trainRepeats)
AcOnly_predictionSet$obs_MC_smooth <- NA
AcOnly_predictionSet$obs_MC_smooth[m1]<- allCovars$observations_smooth[compAcSet_MC_all]
AcOnly_predictionSet$obs_MC <- NA
AcOnly_predictionSet$obs_MC[m1]<- allCovars$observations[compAcSet_MC_all]
AcOnly_predictionSet$GC <- NA
AcOnly_predictionSet$predSd_GC <- NA
AcOnly_predictionSet$testObs_GC <-NA
GC_times <- allCovars$date[compAcSet_GC_all]
m2 <- match(GC_times,allTheDays)
AcOnly_predictionSet$GC[m2] <-predAcOnly_GC
AcOnly_predictionSet$predSd_GC[m2] <- rowSds(data.matrix(predVar_GC_DF),na.rm=TRUE)#/sqrt(trainRepeats)
AcOnly_predictionSet$obs_GC_smooth <- NA
AcOnly_predictionSet$obs_GC_smooth[m2]<- rollmean(allCovars$observations[compAcSet_GC_all],k = 7,fill=NA)
AcOnly_predictionSet$obs_GC <- NA
AcOnly_predictionSet$obs_GC[m2]<- allCovars$observations[compAcSet_GC_all]
AcOnly_predictionSet$DT <- NA
AcOnly_predictionSet$predSd_DT <- NA
AcOnly_predictionSet$testObs_DT <-NA
DT_times <- allCovars$date[compAcSet_DT_all]
m3 <- match(DT_times,allTheDays)
AcOnly_predictionSet$DT[m3] <-predAcOnly_DT
AcOnly_predictionSet$predSd_DT[m3] <- rowSds(data.matrix(predVar_DT_DF),na.rm=TRUE)#/sqrt(trainRepeats)
AcOnly_predictionSet$obs_DT_smooth <- NA
AcOnly_predictionSet$obs_DT_smooth[m3]<- rollmean(allCovars$observations[compAcSet_DT_all],k = 7,fill=NA)
AcOnly_predictionSet$obs_DT <- NA
AcOnly_predictionSet$obs_DT[m3]<- allCovars$observations[compAcSet_DT_all]
AcOnly_predictionSet$Legend1 <- "1 Observations"
AcOnly_predictionSet$StDev <- "Std. Error"
AcOnly_predictionSet$Legend <- "2 Observations (mean)"
AcOnly_predictionSet$LegendTest <- "3 Acoustic"
mcLabel <- grobTree(textGrob("MC", x=0.01, y=0.90, hjust=0,
gp=gpar(col="black", fontsize=13, fontface="bold")))
gcLabel <- grobTree(textGrob("GC", x=0.01, y=0.90, hjust=0,
gp=gpar(col="black", fontsize=13, fontface="bold")))
dtLabel <- grobTree(textGrob("DT", x=0.01, y=0.90, hjust=0,
gp=gpar(col="black", fontsize=13, fontface="bold")))
dcLabel <- grobTree(textGrob("DC", x=0.01, y=0.90, hjust=0,
gp=gpar(col="black", fontsize=13, fontface="bold")))
mpLabel <- grobTree(textGrob("MP", x=0.01, y=0.90, hjust=0,
gp=gpar(col="black", fontsize=13, fontface="bold")))
```
### 3.1.2 Visual-only prediction
```{r Vis Temporal Predict, warning = FALSE, echo = FALSE}
# Confusing, but acoustic only predictors are passed in to since
# we're predicting on the acoustic timeseries.
# Predict in time
predVisOnly_MC <- exp(predict(nn_VisOnly[[best_VisOnly_ModelIndex]],
reducedData_MC)*
log(covars_VisOnly_max.train['yVisOnly']))-1
predVisOnly_MC[predVisOnly_MC<0]=0
predVisOnly_GC <- exp(predict(nn_VisOnly[[best_VisOnly_ModelIndex]],
reducedData_GC)*
log(covars_VisOnly_max.train['yVisOnly']))-1
predVisOnly_GC[predVisOnly_GC<0]=0
predVisOnly_DT <- exp(predict(nn_VisOnly[[best_VisOnly_ModelIndex]],
reducedData_DT)*
log(covars_VisOnly_max.train['yVisOnly']))-1
predVisOnly_DT[predVisOnly_DT<0]=0
predVar_MC <- NULL
predVar_GC <- NULL
predVar_DT <- NULL
for (iMod in c(1:trainRepeats)){
predVar_MC[[iMod]] <- predict(nn_VisOnly[[best_VisOnly_ModelIndex]]$model[[iMod]],
reducedData_MC)*
covars_VisOnly_max.train['yVisOnly']
predVar_MC[[iMod]][predVar_MC[[iMod]]<0]=0
predVar_GC[[iMod]] <- predict(nn_VisOnly[[best_VisOnly_ModelIndex]]$model[[iMod]],
reducedData_GC)*
covars_VisOnly_max.train['yVisOnly']
predVar_GC[[iMod]][predVar_GC[[iMod]]<0]=0
predVar_DT[[iMod]] <- predict(nn_VisOnly[[best_VisOnly_ModelIndex]]$model[[iMod]],
reducedData_DT)*
covars_VisOnly_max.train['yVisOnly']
predVar_DT[[iMod]][predVar_DT[[iMod]]<0]=0
}
n1MC <- length(predVar_MC[[1]])
predVar_MC_DF <- structure(predVar_MC, row.names = c(NA, -n1MC), class = "data.frame")
n1GC <- length(predVar_GC[[1]])
predVar_GC_DF <- structure(predVar_GC, row.names = c(NA, -n1GC), class = "data.frame")
n1DT <- length(predVar_DT[[1]])
predVar_DT_DF <- structure(predVar_DT, row.names = c(NA, -n1DT), class = "data.frame")
VisOnly_predictionSet <- data.frame(allTheDays)
colnames(VisOnly_predictionSet) <-"date"
VisOnly_predictionSet$MC <- NA
VisOnly_predictionSet$predSd_MC <- NA
m1 <- match(MC_times,VisOnly_predictionSet$date)
VisOnly_predictionSet$MC[m1] <-predVisOnly_MC
VisOnly_predictionSet$predSd_MC[m1] <- rowSds(data.matrix(predVar_MC_DF),na.rm=TRUE)#/sqrt(trainRepeats)
VisOnly_predictionSet$GC <- NA
VisOnly_predictionSet$predSd_GC <- NA
m2 <- match(GC_times,VisOnly_predictionSet$date)
VisOnly_predictionSet$GC[m2] <-predVisOnly_GC
VisOnly_predictionSet$predSd_GC[m2] <- rowSds(data.matrix(predVar_GC_DF),na.rm=TRUE)#/sqrt(trainRepeats)
VisOnly_predictionSet$DT <- NA
VisOnly_predictionSet$predSd_DT <- NA
m3 <- match(DT_times,VisOnly_predictionSet$date)
VisOnly_predictionSet$DT[m3] <-predVisOnly_DT
VisOnly_predictionSet$predSd_DT[m3] <- rowSds(data.matrix(predVar_DT_DF),na.rm=TRUE)#/sqrt(trainRepeats)
VisOnly_predictionSet$Legend <- "Predictions - Train"
VisOnly_predictionSet$LegendTest <- "4 Predictions - Test"
```
<br>