/
Results.R
1763 lines (1612 loc) · 74.1 KB
/
Results.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
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 Order fitted models
#' @description Find the models that outperform the others in terms of cross-validation index
#'
#' @param saveWD directory where outputs of the cross-validation procedure have
#' been saved or zip.file of this directory.
#' All necessary information have been saved in this directory to be
#' able to compile results. This is the only output of findBestModel in the
#' global R environment.
#' @param plot logical. Either to create the output plots or not. Saved
#' directly in saveWD.
#' @param zip.file TRUE (default) to save all outputs in a zipfile with saveWD,
#' FALSE for no zipfile output, or path to a new zip file
#' @param cl a cluster as made with \code{\link[snow]{makeCluster}}.
#' If empty, nbclust in \code{\link{modelselect_opt}} will be used.
#'
#' @importFrom grDevices heat.colors png dev.off
#' @import graphics
#'
#' @details
#' According to the family of model, the index of cross-validation procedure is
#' selected to rank all models fitted for all modeltypes conjointly. Model ranks
#' are then statistically compared. Model with lowest ranks not statistically
#' different than the first ranked model are kept.
#'
#' @return
#' VeryBestModels_crossV: Best models among all
#' BestForModeltypes: Best models among all in the modeltypes type
#' Figures are produced to visualize ranking and eventually help for a choice
#'
#' @export
ModelOrder <- function(saveWD, plot, zip.file = TRUE, cl = NULL)
{
saveWD <- normalizePath(saveWD)
if (utils::file_test("-f", saveWD) & file.exists(saveWD) & grepl("zip", saveWD)) {
if (zip.file == TRUE) {zip.file <- saveWD}
utils::unzip(saveWD, exdir = gsub(".zip", "", saveWD))
saveWD <- gsub(".zip", "", saveWD)
} else if (utils::file_test("-d", saveWD)) {
if (zip.file == TRUE) {zip.file <- paste0(saveWD, ".zip")}
} else {
stop("saveWD is neither an existing directory nor a zip file")
}
imgprefix <- paste0(basename(saveWD), "-")
saveWD <- normalizePath(saveWD)
lim_pvalue_final <- modelselect_opt$lim_pvalue_final
# Load variables of model configuration that need to be equivalent as fit
opt_saved <- readr::read_rds(paste0(saveWD, "/modelselect_opt.save.rds"))
seqthd <- opt_saved$seqthd
# Load information
# load(paste0(saveWD, "/Allinfo_all.RData"))
Allinfo_all <- readr::read_rds(paste0(saveWD, "/Allinfo_all.rds"))
datatype <- Allinfo_all$datatype
modeltypes <- Allinfo_all$modeltypes
# message("Image outputs will be saved in ", saveWD)
# Combine results of the different modeltypes ----
# Verif random sub-dataset for crossV used are the same
allM <- paste0("M", 1:length(modeltypes))
for (MX in 1:length(allM)) {
# load(file = paste0(saveWD, "/saveAlea", allM[MX], ".RData"))
saveAlea <- readr::read_rds(paste0(saveWD, "/saveAlea", allM[MX], ".rds"))
if (MX == 1) {
saveAleaM1 <- saveAlea
}
if (MX >= 2) {
if (!identical(saveAleaM1, saveAlea)) {
stop(c("Models of ", modeltypes[1], "and", modeltypes[MX],
"have not been fitted with the same cross-validation random subdatasets"))
}
}
}
saveAlea <- saveAleaM1
saveAlea.nb <- readr::read_rds(paste0(saveWD, "/saveAlea.nbM1.rds"))
# Combine all results
resAIC_unlist <- logical(0)
test_models_unlist <- logical(0)
ToutResDev_crossV <- logical(0)
ToutAUC_crossV <- logical(0)
ToutRMSE_crossV <- logical(0)
nb_models_per_nb <- logical(0)
nb_per_modeltypes <- logical(0)
BestTHD_crossV_unlist <- logical(0)
DiffSelSpeTHD_crossV_unlist <- logical(0)
MinUn_crossV <- logical(0)
MaxZero_crossV <- logical(0)
MeanPercentError_crossV <- logical(0)
l_Max_Nb_Var <- logical(0)
ToutLogl_crossV <- logical(0)
resParam_unlist <- logical(0)
allM <- paste0("M", 1:length(modeltypes))
for (MX in 1:length(allM)) {
# load(file = paste0(saveWD, "/resAIC_save", allM[MX], ".RData"))
resAIC_save <- readr::read_rds(paste0(saveWD, "/resAIC_save", allM[MX], ".rds"))
resAIC_unlist <- c(resAIC_unlist, unlist(resAIC_save))
nb_per_modeltypes <- c(nb_per_modeltypes, length(unlist(resAIC_save)))
if (grepl("TweedGLM|KrigeGLM", modeltypes[MX])) {
# load(file = paste0(saveWD, "/resParam_save", allM[MX], ".RData"))
resParam_save <- readr::read_rds(paste0(saveWD, "/resParam_save", allM[MX], ".rds"))
resParam_unlist <- c(resParam_unlist, unlist(resParam_save))
} else {
resParam_unlist <- c(resParam_unlist, rep(NA, length(unlist(resAIC_save))))
}
# load(file = paste0(saveWD, "/test_models", allM[MX], ".RData"))
test_models <- readr::read_rds(paste0(saveWD, "/test_models", allM[MX], ".rds"))
test_models_unlist_A <- unlist(test_models)
test_models_unlist <- c(test_models_unlist, test_models_unlist_A)
# load(file = paste0(saveWD, "/Output_models", allM[MX], ".RData"))
Output_models <- readr::read_rds(
paste0(saveWD, "/Output_models", allM[MX], ".rds"))
# ToutResDev_crossV_A <- apply(t(1:length(Output_models)), 2, function(x)
# Output_models[[x]][4,,])
# browser()
ToutResDev_crossV_A <- purrr::map(Output_models, ~.[4,,])
ToutResDev_crossV_A2 <- do.call(rbind, ToutResDev_crossV_A)
ToutResDev_crossV <- rbind(ToutResDev_crossV, ToutResDev_crossV_A2)
l_Max_Nb_Var <- c(l_Max_Nb_Var, length(ToutResDev_crossV_A))
if (grepl("PA|TweedGLM", modeltypes[MX])) {
#ToutAUC_crossV_A <- apply(t(1:length(Output_models)), 2, function(x)
# Output_models[[x]][7 + length(seqthd) + 1,,])
ToutAUC_crossV_A <- purrr::map(Output_models, ~.[7 + length(seqthd) + 1,,])
ToutAUC_crossV_A2 <- do.call(rbind, ToutAUC_crossV_A)
ToutAUC_crossV <- rbind(ToutAUC_crossV, ToutAUC_crossV_A2)
}
if (grepl("Cont|Count|Gamma", modeltypes[MX])) {
# MeanPercentError_crossV_A <- apply(t(1:length(Output_models)),
# 2, function(x) Output_models[[x]][5,,])
MeanPercentError_crossV_A <- purrr::map(Output_models, ~.[5,,])
MeanPercentError_crossV_A2 <- do.call(rbind, MeanPercentError_crossV_A)
MeanPercentError_crossV <- rbind(MeanPercentError_crossV,
MeanPercentError_crossV_A2)
}
if (grepl("PA|TweedGLM", modeltypes[MX])) {
N_RMSE <- 7 + length(seqthd) + 2
} else {
N_RMSE <- 6
}
#ToutRMSE_crossV_A <- apply(t(1:length(Output_models)), 2, function(x)
# Output_models[[x]][N_RMSE,,])
ToutRMSE_crossV_A <- purrr::map(Output_models, ~.[N_RMSE,,])
ToutRMSE_crossV_A2 <- do.call(rbind, ToutRMSE_crossV_A)
ToutRMSE_crossV <- rbind(ToutRMSE_crossV, ToutRMSE_crossV_A2)
nb_models_per_nb <- c(nb_models_per_nb, unlist(lapply(ToutRMSE_crossV_A, nrow)))
if (grepl("PA|TweedGLM", modeltypes[MX])) {
# load(file = paste0(saveWD, "/BestTHD_crossV", allM[MX], ".RData"))
BestTHD_crossV <- readr::read_rds(
paste0(saveWD, "/BestTHD_crossV", allM[MX], ".rds"))
# load(file = paste0(saveWD, "/DiffSelSpeTHD_crossV", allM[MX], ".RData"))
DiffSelSpeTHD_crossV <- readr::read_rds(
paste0(saveWD, "/DiffSelSpeTHD_crossV", allM[MX], ".rds"))
BestTHD_crossV_unlist <- c(BestTHD_crossV_unlist, unlist(BestTHD_crossV))
DiffSelSpeTHD_crossV_unlist_A <- do.call(rbind, DiffSelSpeTHD_crossV)
DiffSelSpeTHD_crossV_unlist <- rbind(DiffSelSpeTHD_crossV_unlist,
100 * DiffSelSpeTHD_crossV_unlist_A/dim(saveAlea)[1])
#MinUn_crossV_A <- apply(t(1:length(Output_models)), 2, function(x)
# Output_models[[x]][5,,])
MinUn_crossV_A <- purrr::map(Output_models, ~.[5,,])
MinUn_crossV_A2 <- do.call(rbind, MinUn_crossV_A)
MinUn_crossV <- rbind(MinUn_crossV, MinUn_crossV_A2)
#MaxZero_crossV_A <- apply(t(1:length(Output_models)), 2, function(x)
# Output_models[[x]][6,,])
MaxZero_crossV_A <- purrr::map(Output_models, ~.[6,,])
MaxZero_crossV_A2 <- do.call(rbind, MaxZero_crossV_A)
MaxZero_crossV <- rbind(MaxZero_crossV, MaxZero_crossV_A2)
}
save(BestTHD_crossV_unlist, file = paste0(saveWD, "/BestTHD_crossV_unlist.RData"))
save(MinUn_crossV, file = paste0(saveWD, "/MinUn_crossV.RData"))
save(MaxZero_crossV, file = paste0(saveWD, "/MaxZero_crossV.RData"))
if (grepl("TweedGLM", modeltypes[MX])) {
#ToutLogl_crossV_A <- apply(t(1:length(Output_models)), 2, function(x)
# Output_models[[x]][7 + length(seqthd) + 3,,])
ToutLogl_crossV_A <- purrr::map(Output_models, ~.[7 + length(seqthd) + 3,,])
ToutLogl_crossV_A2 <- do.call(rbind, ToutLogl_crossV_A)
ToutLogl_crossV <- rbind(ToutLogl_crossV, ToutLogl_crossV_A2)
}
} # END of allMX
if (grepl("Krige", datatype)) {
allmodeltypes <- rep(paste(modeltypes, Model, sep = "_"), nb_per_modeltypes)
} else {
allmodeltypes <- rep(modeltypes, nb_per_modeltypes)
}
# Fig for the choice of the best thd for 'PA' pred ----
if (plot & grepl("PA", datatype))
{
png(filename = paste0(saveWD, "/", imgprefix, "Thresholds_for_prediction.png"),
width = 18, height = 8, units = "cm", pointsize = 7, res = 300)
# x11()
par(mfrow = c(1, 3))
MinUn_crossV[MinUn_crossV == "Inf"] <- 1
for (i in c("BestTHD_crossV_unlist", "MinUn_crossV", "MaxZero_crossV")) {
if (i == "BestTHD_crossV_unlist") {
histSeuil <- hist(BestTHD_crossV_unlist, main = i)
} else {
histSeuil <- hist(apply(get(i), 1,
function(x) mean(x, na.rm = TRUE)),
main = i)
}
abline(v = 0.5, col = "blue", lwd = 2)
SeuilFromHist_crossV <- histSeuil$mids[which(histSeuil$density ==
max(histSeuil$density))]
abline(v = SeuilFromHist_crossV, col = "red", lwd = 2)
axis(1, line = 1, at = SeuilFromHist_crossV, col = "red",
col.axis = "red")
}
dev.off()
} # end of datatype == 'PA'
# Choose the very best models ----
# Define indice depending on datatype
minus_index <- 1
if (grepl("PA", datatype)) {
IndexForRank_crossV <- -ToutAUC_crossV
minus_index <- -1
nameIndex <- "Mean_AUC_crossV"
} else if (grepl("Cont", datatype)) {
# IndexForRank_crossV <- log(MeanPercentError_crossV)
IndexForRank_crossV <- ToutRMSE_crossV
nameIndex <- "Mean_RMSE_crossV"
} else if (grepl("Count|Krige", datatype)) {
# IndexForRank_crossV <- log(ToutRMSE_crossV)
IndexForRank_crossV <- ToutRMSE_crossV
nameIndex <- "Mean_RMSE_crossV"
} else if (grepl("Tweed", datatype)) {
# IndexForRank_crossV <- -ToutLogl_crossV
IndexForRank_crossV <- ToutRMSE_crossV
nameIndex <- "Mean_RMSE_crossV"
} # log likelihood
if (length(which(IndexForRank_crossV == "Inf")) > 0) {
IndexForRank_crossV[which(IndexForRank_crossV == "Inf")] <- 1e+15
}
if (length(which(IndexForRank_crossV == "-Inf")) > 0) {
IndexForRank_crossV[which(IndexForRank_crossV == "-Inf")] <- -1e+15
}
# Rank models ----
# according to their quality of prediction for each
# cross-validation sub-dataset
IndexForRank_crossVMean <- rowMeans(IndexForRank_crossV, na.rm = T)
ToutRMSE_crossVMean <- apply(ToutRMSE_crossV, 1, function(x) {
mean(x, na.rm = T)
})
# The best model is the one which is the best on average for all crossV samples
# meanLineMin <- order(OrderIndexForRank_crossVMean)[1]
# The model that is always smaller than the other is not necessarily the one
# with the smallest average rank because of the calculation of the rank and
# the possible same ranking
# It is also not necessary the one with the smallest average value
# as comparisons test will be paired and because there are NA values.
# Although models with too many NA are removed from the analysis
# To avoid comparison of all distributions against all distributions,
# we do an iterative procedure in maxit step maximum.
# This should be better for memory...
# 1/ The model with the smallest mean is set as the best model
# 2/ Mean comparison is done for all against this model
# 3/ If a model shows a mean difference lower than zero, then
# the lowest is retained and return to 2/
best.distri <- best_distri(x = IndexForRank_crossV, w = saveAlea.nb,
test = "wilcoxon", na.max = 0.5,
p.min = lim_pvalue_final, silent = TRUE,
cl = cl)
orderModels <- best.distri$orderModels
Line_keep <- best.distri$orderModels[which(best.distri$p.min.test)]
DiffTo1 <- meandiff_distri(x = IndexForRank_crossV[orderModels,],
n = 1, w = saveAlea.nb, comp.n = TRUE)
# Figures of ranks on Percent Errors ----
if (plot)
{
# Rank models, Select the best model and
# the best ones that are not significantly
# different from the 1st
if (grepl("PA", datatype)) {
titre <- "AUC on crossV"
} else {
titre <- "Root of Mean Squared Error on crossV"
}
png(filename = paste0(saveWD, "/", imgprefix, "Ordered_Models.png"),
width = 50, height = 8, units = "cm", pointsize = 5, res = 300)
par(mai = c(0.2, 0.4, 0.25, 0.3))
plot(-10,-10, main = "Mean difference of index with 1st model",
ylim = c(quantile(c(DiffTo1$comp.n), probs = 0.005, na.rm = TRUE),
quantile(c(DiffTo1$comp.n), probs = 0.995, na.rm = TRUE)),
pch = 20, xlab = "", ylab = "Mean difference with 1st model",
xlim = c(0,
nrow(IndexForRank_crossV) + 1),
xaxs = "i")
res <- apply(t(1:nrow(DiffTo1$comp.n)), 2, function(x) {
boxplot(DiffTo1$comp.n[x, ], at = x, pch = 20,
border = c("black", "forestgreen")[1 + best.distri$p.min.test[x]],
pch = 20, cex = 0.5, yaxt = "n", xaxt = "n",
outline = TRUE, add = TRUE)
})
points(DiffTo1$means, col = "green", pch = 20, cex = 0.5)
abline(h = 0, col = "grey", lty = "dashed")
par(new = TRUE)
plot(best.distri$p.values, pch = 20, col = "red",
xaxt = "n", yaxt = "n", cex = 0.5, xaxs = "i",
xlim = c(0, nrow(IndexForRank_crossV) + 1),
ylim = c(0,1), yaxs = "i", xlab = "", ylab = "")
axis(4, col.axis = "orangered")
mtext("p-value", side = 4, line = 2)
abline(h = c(lim_pvalue_final), col = "orangered", lwd = 2)
abline(v = max(which(best.distri$p.min.test)) + 0.5, col = "green")
par(new = FALSE)
dev.off()
IndexForRank_crossV.plot <- minus_index * IndexForRank_crossV
png(filename = paste0(saveWD, "/", imgprefix, "Index_Error_on_crossV.png"),
width = 50, height = 8, units = "cm", pointsize = 5, res = 300)
plot(-10,-10, main = titre,
ylim = c(stats::quantile(c(IndexForRank_crossV.plot), probs = 0.005, na.rm = TRUE),
stats::quantile(c(IndexForRank_crossV.plot), probs = 0.995, na.rm = TRUE)),
pch = 20, xlab = "", ylab = gsub("_", " ", nameIndex),
xlim = c(0, nrow(IndexForRank_crossV.plot) + 1),
xaxs = "i")
axis(1)
# Using apply accelerate calculation for table of models and
# reduce use of RAM
res <- apply(t(1:nrow(IndexForRank_crossV.plot)), 2, function(x) {
boxplot(IndexForRank_crossV.plot[x, ], at = x, pch = 20,
col = c("grey", "forestgreen")[1 + x %in% Line_keep],
border = c("black", heat.colors(length(Line_keep)))[
c(which(Line_keep %in% x) + 1, 1)[1]], yaxt = "n", xaxt = "n",
outline = FALSE, add = TRUE)
if (x %in% Line_keep) {
axis(1, at = x, labels = "", line = 1.5,
col = heat.colors(length(Line_keep))[which(Line_keep %in% x)],
col.axis = heat.colors(length(Line_keep))[which(Line_keep %in% x)])
}
})
rm(res)
gc()
axis(1, at = Line_keep[1], labels = Line_keep[1], line = 2, col = "red",
col.axis = "red")
# Add a line to separate models with 1, 2, 3 ... parameters
for (i in 1:length(nb_models_per_nb)) {
abline(v = c(0, sum(nb_models_per_nb[1:i])) + 0.5, col = "blue",
lwd = 2)
}
abline(v = 0.5, col = "red", lwd = 3)
mtext(modeltypes[1], side = 1, at = 0.5, cex = 1.5)
if (length(l_Max_Nb_Var) > 1) {
for (i in 1:(length(l_Max_Nb_Var) - 1)) {
pos <- cumsum(l_Max_Nb_Var)[i]
abline(v = sum(nb_models_per_nb[1:pos]) + 0.5, col = "red",
lwd = 3)
mtext(modeltypes[i+1], side = 1,
at = sum(nb_models_per_nb[1:pos]) + 0.5, cex = 1.5)
}
}
dev.off()
} # end of plot
# Create table with the models ranked ----
# and with the non-statistically differantiated best models
if (grepl("RMSE", nameIndex)) {
VeryBestModels_crossV_A <- data.frame(
Num = 1:length(test_models_unlist),
model = test_models_unlist,
nameIndex = round(IndexForRank_crossVMean, digits = 2),
AIC = round(resAIC_unlist)
)
} else {
VeryBestModels_crossV_A <- data.frame(
Num = 1:length(test_models_unlist),
model = test_models_unlist,
nameIndex = minus_index * round(IndexForRank_crossVMean, digits = 2),
Mean_RMSE_crossV = round(ToutRMSE_crossVMean, digits = 2),
AIC = round(resAIC_unlist)
)
}
# With tweedie, selection is made on SSQ but we need to get AUC of the
# binomial part
if (grepl("Tweed", datatype)) {
VeryBestModels_crossV_A$Mean_AUC_crossV <- -ToutAUC_crossVMean
}
# We keep XI fo tweedie or Lambda for KrigeGLM
if (length(grep("TweedGLM|KrigeGLM", modeltypes)) > 0) {
VeryBestModels_crossV_A$Param <- resParam_unlist
}
VeryBestModels_crossV_A$modeltype <- allmodeltypes
names(VeryBestModels_crossV_A)[
which(names(VeryBestModels_crossV_A) == "nameIndex")] <- nameIndex
for (i in 3:(ncol(VeryBestModels_crossV_A) - 1)) {
VeryBestModels_crossV_A[, i] <- as.numeric(as.character(
VeryBestModels_crossV_A[, i]))
}
VeryBestModels_crossV <- VeryBestModels_crossV_A[Line_keep, ]
# Save all models ordered
AllModels_crossV_ordered <- VeryBestModels_crossV_A[orderModels, ]
utils::write.table(AllModels_crossV_ordered,
file = paste0(saveWD, "/", imgprefix,
"AllModels_crossV_ordered.csv"),
sep = ";", col.names = TRUE, row.names = FALSE)
LimitNb <- nrow(VeryBestModels_crossV)
# List of covariates ranked ----
# with higher score when on the top of the list
nChar_crossV <- logical(0)
sumTot_crossV <- 0
for (i in 1:LimitNb) {
nChar_crossV[i] <- length(strsplit(gsub(", ", ",", as.character(
VeryBestModels_crossV[, "model"][i])), split = " ")[[1]])
sumTot_crossV <- sumTot_crossV + i
}
freq_fact_crossV2 <- tapply(rep(c(LimitNb:1), nChar_crossV),
unlist(strsplit(gsub(", ", ",", as.character(
VeryBestModels_crossV[, "model"])),
split = " ")), sum)
ScoreTab_A <- t(t(round(t(t(freq_fact_crossV2[
order(freq_fact_crossV2, decreasing = TRUE)]))/sumTot_crossV * 100)))
ScoreTab <- t(t(ScoreTab_A[-which(rownames(ScoreTab_A) %in%
c("+", "~", "dataY", "log(dataY)")), ]))
utils::write.table(ScoreTab, file = paste0(saveWD, "/", imgprefix, "ScoreTab_VeryBest.csv"),
sep = ";", col.names = TRUE, row.names = TRUE)
freq_fact_crossVlist2 <- strsplit(gsub(", ", ",", as.character(
VeryBestModels_crossV[, "model"])), split = " ")
# Compare models expression to the first 20 covariates chosen by the
# best models
NbParam <- min(20, nrow(ScoreTab))
ParamMat <- matrix(NA, nrow = NbParam, ncol = nrow(VeryBestModels_crossV))
for (i in 1:nrow(VeryBestModels_crossV)) {
VeryBestModels_crossV[i, "Num"]
for (j in 1:NbParam) {
if (sum(freq_fact_crossVlist2[[i]] %in% rownames(ScoreTab)[j]) >= 1) {
ParamMat[j, i] <- 1
}
}
}
if (plot) {
png(filename = paste0(saveWD, "/", imgprefix, "Help_for_model_Choice_NbParam-",
NbParam, ".png"),
width = 18, height = 9, units = "cm",
pointsize = 7, res = 300)
# x11(h=6,w=12) par(mai=c(0.5,4,0.8,0.1))
mai_left <- max(strwidth(c(paste0(nameIndex),
paste0(rownames(ScoreTab)[NbParam:1], " ")),
cex = 1, units = "inches"))
par(mai = c(0.3, mai_left + 0.1, 0.7, 0.4))
# par(mai = c(0.4, 3, 0.6, 0.4))
image(1:ncol(ParamMat), 1:nrow(ParamMat), t(ParamMat[nrow(ParamMat):1,]),
xaxt = "n", yaxt = "n", xlab = "", ylab = "", col = "forestgreen")
axis(2, at = 1:nrow(ParamMat), rownames(ScoreTab)[NbParam:1], las = 1)
axis(3, at = 1:ncol(ParamMat), labels = NA, las = 2)
axis(3, at = 1:ncol(ParamMat)-0.2, VeryBestModels_crossV[, "Num"],
las = 2, tick = FALSE, lwd = 0)
axis(3, at = 1:ncol(ParamMat)+0.2, VeryBestModels_crossV[, "modeltype"],
las = 2, cex.axis = 0.6, tick = FALSE, lwd = 0)
# SumScore <- apply(ParamMat, 2, function(x) sum(x, na.rm = TRUE))
# for (i in min(SumScore):max(SumScore)) {
# axis(1, at = c(1:ncol(ParamMat))[which(SumScore == i)],
# SumScore[which(SumScore == i)], tick = FALSE,
# col.axis = rev(heat.colors(max(SumScore) - min(SumScore) + 1))[
# i - min(SumScore) + 1])
# }
axis(1, at = 1:ncol(ParamMat), labels = VeryBestModels_crossV[,nameIndex],
tick = FALSE, las = 2, cex.axis = 0.8)
abline(v = (1:ncol(ParamMat)) + 0.5)
abline(h = (1:nrow(ParamMat)) + 0.5)
arrows(0.5, nrow(ParamMat) + (nrow(ParamMat)/4.5), ncol(ParamMat) + 0.5,
nrow(ParamMat) + (nrow(ParamMat)/4.5), xpd = TRUE,
angle = 20, length = 0.15)
text((ncol(ParamMat) + 0.5)/2, nrow(ParamMat) + (nrow(ParamMat)/4),
"+++ From Best to less best model +",
xpd = TRUE, cex = 1.5)
arrows(ncol(ParamMat) + 0.5 + 0.03 * ncol(ParamMat), nrow(ParamMat) + 0.5,
ncol(ParamMat) + 0.5 + 0.03 * ncol(ParamMat),
0.5, xpd = TRUE, angle = 15, length = 0.1)
text(ncol(ParamMat) + 0.5 + 0.05 * ncol(ParamMat), 0.5 * nrow(ParamMat) + 0.5,
"+++ From Best to less best factor +",
xpd = TRUE, cex = 1.5, srt = 270)
mtext(paste0(nameIndex, ": "), side = 1, line = 1,
at = 0.5, adj = 1, cex = 1)
dev.off()
} # end of plot
# Save the table of the very best models
utils::write.table(VeryBestModels_crossV,
file = paste0(saveWD, "/", imgprefix,
"VeryBestModels_crossV.csv"),
sep = ";", col.names = TRUE, row.names = FALSE)
save(VeryBestModels_crossV,
file = paste0(saveWD, "/", imgprefix, "VeryBestModels_crossV.RData"))
# Save the 2 best models for each modeltypes
if (length(modeltypes) > 1) {
w.bestmodeltype <- NULL
for (modeltype in levels(as.factor(modeltypes))) {
w.bestmodeltype <- c(w.bestmodeltype, orderModels[which(
VeryBestModels_crossV_A[orderModels, "modeltype"] == modeltype)[1:2]])
}
BestForModeltypes <- VeryBestModels_crossV_A[w.bestmodeltype, ]
if (grepl("TweedGLM|KrigeGLM", datatype)) {
BestForModeltypes <- cbind(BestForModeltypes, resParam_unlist[w.bestmodeltype])
names(BestForModeltypes)[ncol(BestForModeltypes)] <- "Param"
}
utils::write.table(BestForModeltypes, file = paste0(saveWD, "/", imgprefix,
"BestForModeltypes.txt"),
col.names = TRUE, row.names = FALSE)
} else {
BestForModeltypes <- VeryBestModels_crossV
}
# Zip all outputs in a unique file.
if (zip.file != FALSE) {
# Options j allows to save directly files without path
utils::zip(zip.file, files = saveWD, flags = "-urj9X", extras = "",
zip = Sys.getenv("R_ZIPCMD", "zip"))
# Return the file path of the zip file
return(list(VeryBestModels_crossV = VeryBestModels_crossV,
BestForModeltypes = BestForModeltypes,
zip.file = zip.file))
} else {
return(list(VeryBestModels_crossV = VeryBestModels_crossV,
BestForModeltypes = BestForModeltypes))
}
} # end of ModelOrder function
#' Characteristics of the model on which to produce outputs
#'
#' @param saveWD directory where outputs of model selection are saved, including
#' AllModels_crossV_ordered.
#' @param new.data SpatialPointsDataFrame dataset used to fit the model.
#' @param modeltype The model type as chosen among modeltypes available
#' (see \code{\link{modelselect_opt}})
#' @inheritParams ModelResults
#'
#' @return Num, modeltype, Family, formulaX
#' @importFrom splines ns
#' @importFrom mgcv gam
#'
#' @export
model_select <- function(saveWD, new.data, Num = NULL, model = NULL,
modeltype = NULL, powerXI = NULL)
{
Param <- NULL
# Read list of models
AllModels_crossV_ordered <- readr::read_delim(
file = paste0(saveWD, "/", basename(saveWD), "-AllModels_crossV_ordered.csv"),
delim = ";")#, col_types = "ncnnncn")
new.data.orig <- new.data
if (is(new.data)[1] == "SpatialPointsDataFrame") {
new.data <- tibble::as_tibble(new.data@data)
} else {
new.data <- tibble::as_tibble(new.data)
}
# If Num is not specified, choose the first best model
if (is.null(Num)) {
Num <- AllModels_crossV_ordered$Num[1]
}
if (!is.numeric(Num)) {Num <- as.numeric(as.character(Num))}
# Verify if model defined by user exists in already fitted models
if (!is.null(model)) {
if (sum(AllModels_crossV_ordered$model == model) == 1) {
Num <- AllModels_crossV_ordered$Num[which(
AllModels_crossV_ordered$model == model)]
Num <- as.numeric(as.character(Num))
message(c("Your model corresponds to model Num = ", Num))
} else {
Num <- "UserModel"
}
}
if (Num != "UserModel") {
# Usual case with model already fitted in crossV
modeltype <- as.character(AllModels_crossV_ordered[
which(AllModels_crossV_ordered$Num == Num), "modeltype"])
formulaX <- as.character(AllModels_crossV_ordered[
which(AllModels_crossV_ordered$Num == Num), "model"])
if (grepl("PA|Tweed", modeltype)) {
load(file = paste0(saveWD, "/BestTHD_crossV_unlist.RData"))
load(file = paste0(saveWD, "/MinUn_crossV.RData"))
load(file = paste0(saveWD, "/MaxZero_crossV.RData"))
if (grepl("Tweed", modeltype)) {
# THD values saved only for Tweed model, not for other Cont ones.
ord.Num <- order(unlist(AllModels_crossV_ordered[,"Num"]))
Num.thd <- which(unlist(AllModels_crossV_ordered[ord.Num,][
which(grepl("Tweed", unlist(AllModels_crossV_ordered[ord.Num,"modeltype"]))), "Num"]) == Num)
} else {
Num.thd <- Num
}
Seuil <- BestTHD_crossV_unlist[Num.thd]
# Minimum value where we see presence
SeuilMinUn <- mean(MinUn_crossV[Num.thd, ][
is.finite(MinUn_crossV[Num.thd, ])], na.rm = TRUE)
# Maximum value where we see absence
SeuilMaxZero <- mean(MaxZero_crossV[Num.thd, ][
is.finite(MaxZero_crossV[Num.thd, ])], na.rm = TRUE)
}
} else {
# Case with User defined model not already in crossV
# No guaranty on the utility of this type of operation
formulaX <- model
if (grepl("PA|Tweed", modeltype)) {
## Write the function to calculate Seuil(s) by crossV if model not
## already estimated
Seuil <- 0.5
SeuilMinUn <- 0.95 # Minimum value where we see presence
SeuilMaxZero <- 0.05 # Maximum value where we see absence
warning(c("Presence-absence 'Seuil(s)' values have been fixed for",
" compatibility purpose but they have not any sense for the",
" model chosen"))
}
}
# Modify formulaX for factor covariates
formulaX.tmp <- as.character(formulaX)
w.NotNum <- which(unlist(lapply(new.data[,all.vars(as.formula(formulaX.tmp))],
function(x) {!is.numeric(x)})))
if (length(w.NotNum) > 0) {
for (var in w.NotNum) {
if (!grepl(paste0("as.factor(as.character(",
all.vars(as.formula(formulaX.tmp))[var], "))"),
formulaX.tmp)) {
formulaX <- gsub(all.vars(as.formula(formulaX.tmp))[var],
paste0("as.factor(as.character(", all.vars(as.formula(formulaX.tmp))[var], "))"),
formulaX.tmp, fixed = TRUE)
}
}
}
if (grepl("PA", modeltype)) {
Family <- "binomial"
} else if (grepl("Cont", modeltype)) {
Family <- "gaussian"
} else if (grepl("Gamma", modeltype)) {
Family <- "Gamma(link=\"log\")"
} else if (grepl("Count", modeltype)) {
Family <- "poisson"
} else if (grepl("Tweed", modeltype)) {
if (Num != "UserModel") {
Param <- unlist(AllModels_crossV_ordered[
which(AllModels_crossV_ordered$Num == Num), "Param"])
} else {
Param <- tweedie::tweedie.profile(as.formula(formulaX), data = new.data,
xi.vec = seq(1.1, 1.9, 0.1), do.plot = FALSE, fit.glm = FALSE,
do.ci = FALSE, method = "series")$xi.max[1]
}
Family <- statmod::tweedie(var.power = Param, link.power = 0)
} else if (grepl("KrigeGLM", modeltype)) {
## To do
}
## Add data + 1
## Add warning + output param to say it is + 1 data
# For box-cox or Log transformation, data should be strictly positive Add +1 to
# data if needed
Sup <- 0
## Add for KrigeGLM with lambda
if (grepl("Log|Gamma", modeltype)) {
if (min(new.data$dataY) < 0) {
stop("For Box-Cox or Log transformation or Gamma model, data should be strictly positive")
}
if (min(new.data$dataY) == 0) {
Sup <- 1
warning("For Box-Cox or Log transformation or Gamma model, +1 was added to data")
}
}
new.data$dataY <- new.data$dataY + Sup
# For future KrigeGLM
# if (!is.na(Y_data_sample_lcc)) {
# Y_data_sample_lcc$dataY <- Y_data_sample_lcc$dataY + Sup
# }
if (grepl("GLM", modeltype)) {
modelX <- glm(as.formula(formulaX), data = new.data, family = Family,
control = list(epsilon = 1e-05, maxit = 1000))
} else {
modelX <- mgcv::gam(as.formula(formulaX), method = "REML", data = new.data,
family = Family)
}
if (grepl("Tweed", modeltype)) {
## Verify with TweedGAM
# 1-proba because output p is proba of absence
modelX$proba <- 1 - (apply(t(modelX$fitted), 2, function(i) tweedie::dtweedie(y = 0,
xi = Param, mu = i, phi = summary(modelX)$dispersion)))
}
res <- list(Num = Num, modeltype = as.character(modeltype), Family = Family,
formulaX = formulaX, modelX = modelX, Param = Param,
new.data = new.data.orig, Sup = Sup
)
if (grepl("PA|Tweed", modeltype)) {
res$Seuil <- Seuil
res$SeuilMinUn <- SeuilMinUn
res$SeuilMaxZero <- SeuilMaxZero
}
return(res)
}
#' Study the outputs and predictions of a specific model
#'
#' @param saveWD directory where outputs of the cross-validation procedure have
#' been saved or zip.file of this directory.
#' All necessary information have been saved in this directory to be
#' able to compile results. This is the only output of findBestModel in the
#' global R environment.
#' @param plot logical Whether to do plot outputs or not. Although there are not
#' a lot of other types of outputs...
#' @param zip.file TRUE (default) to save all outputs in a zipfile with saveWD,
#' FALSE for no zipfile output, or path to a new zip file
#' @param Num numeric The 'Num' value of the model retained for further analysis
#' like those saved in AllModels_crossV_ordered. Not useful if model and Family
#' are set. Default to the first model in AllModels_crossV_ordered.
#' @param model character string A user-defined model specification. This requires
#' to set the Family parameter. This overrides effects of 'Num', however, if the
#' model exists with the exact same expression in the list of model fitted,
#' 'Num' will be re-attributed.
#' @param modeltype The type of the model as chosen among modeltypes available
##' (see \code{\link{modelselect_opt}})
#' @param powerXI XI parameter for a tweedie model.
#' @param Marginals Calculate full marginal prediction for each covariate
#' @param cl a cluster as made with \code{\link[snow]{makeCluster}}.
#' If cl is empty, nbclust in \code{\link{modelselect_opt}} will be used
#' to create a cluster.
#' @param n.ech.marginal 5000 by default. Number of random samples for marginals
#' estimations.
#'
#' @importFrom sp spTransform CRS
#' @import graphics
#' @importFrom grDevices dev.off png heat.colors colorRampPalette
#' @importFrom ggplot2 ggplot geom_pointrange aes facet_wrap ggsave
#' @importFrom ggplot2 labs
#' @importFrom yarrr pirateplot
#' @import stats
#'
#' @export
ModelResults <- function(saveWD, plot, Num = NULL, model = NULL,
modeltype = NULL, powerXI = NULL, Marginals = FALSE,
zip.file = TRUE, cl = NULL, n.ech.marginal = 5000)
{
# browser()
if (utils::file_test("-f", saveWD) & file.exists(saveWD) & grepl("zip", saveWD)) {
if (zip.file == TRUE) {zip.file <- saveWD}
utils::unzip(saveWD, exdir = gsub(".zip", "", saveWD))
saveWD <- gsub(".zip", "", saveWD)
} else if (utils::file_test("-d", saveWD)) {
if (zip.file == TRUE) {zip.file <- paste0(saveWD, ".zip")}
} else {
stop("saveWD is neither an existing directory nor a zip file")
}
if (is.null(cl)) {
cl_inside <- TRUE
} else {
cl_inside <- FALSE
}
if (!is.null(Num) & !is.numeric(Num)) {
Num <- as.numeric(as.character(Num))
}
imgprefix <- paste0(basename(saveWD), "-")
saveWD <- normalizePath(saveWD)
message("Image outputs will be saved in ", saveWD)
# Load information
# load(paste0(saveWD, "/Allinfo_all.RData"))
Allinfo_all <- readr::read_rds(paste0(saveWD, "/Allinfo_all.rds"))
datatype <- Allinfo_all$datatype
nbclust <- modelselect_opt$nbclust
# Load variables of model configuration that need to be equivalent as fit
opt_saved <- readr::read_rds(paste0(saveWD, "/modelselect_opt.save.rds"))
# Options ----
nbMC <- opt_saved$nbMC
seqthd <- opt_saved$seqthd
MaxDist <- opt_saved$MaxDist
Phi <- opt_saved$Phi
Model <- opt_saved$Model
Lambda <- opt_saved$Lambda
modeltypes <- opt_saved$modeltypes
lcc_proj <- opt_saved$lcc_proj
if (grepl("KrigeGLM", datatype)) {
Y_data_sample_lcc <- spTransform(Allinfo_all$data, CRS(lcc_proj))
} else {
Y_data_sample_lcc <- NA
}
if (is(Allinfo_all$data)[1] == "SpatialPointsDataFrame") {
Y_data_sample <- tibble::as_tibble(Allinfo_all$data@data)
} else {
Y_data_sample <- tibble::as_tibble(Allinfo_all$data)
}
# Precision to keep for predictions
prec.data <- prec_data(Y_data_sample$dataY) - 1
# Define the model on which to produce outputs
model_selected <- model_select(saveWD = saveWD,
new.data = Y_data_sample,
Num = Num, model = model,
modeltype = modeltype, powerXI = powerXI)
Num <- model_selected$Num
modeltype <- model_selected$modeltype
Family <- model_selected$Family
formulaX <- model_selected$formulaX
modelX <- model_selected$modelX
Param <- model_selected$Param
if (grepl("PA|Tweed", modeltype)) {
Seuil <- model_selected$Seuil
SeuilMinUn <- model_selected$SeuilMinUn
SeuilMaxZero <- model_selected$SeuilMaxZero
}
# Outputs of the best chosen model ====
# Find the prediction closest to mean average prediction ----
# This is to build some marginal distributions of covariates
datapred.tbl <- model_selected$new.data[,all.vars(stats::as.formula(modelX))] %>%
tibble::as_tibble() %>%
dplyr::mutate_at(dplyr::vars(-dataY), .funs = function(x) {
if (is.numeric(x)) {
minmax <- stats::quantile(x, probs = c(0.1, 0.9), na.rm = TRUE)
x[(x <= minmax[1] | x >= minmax[2])] <- NA
}
x
}) %>%
dplyr::mutate(pred = stats::predict(modelX),
na.row = apply(., 1, function(x) sum(is.na(x)) != 0),
mean = ifelse(grepl("PA", modeltype), 0, mean(dataY)),
pred.absmean = abs(pred - mean)) %>%
dplyr::filter(!na.row) %>%
dplyr::arrange(pred.absmean)
CovForMeanPred <- datapred.tbl[1,]
readr::write_rds(CovForMeanPred,
paste0(saveWD, "/", basename(saveWD),
"-CovForMeanPred_", model_selected$Num, ".rds"))
# Deviance explained ----
## Also add AUC and RMSE
w.dataY <- "dataY"
if (model_selected$Sup != 0) {
w.dataY <- "dataY + 1"
}
if (grepl("Log", modeltype)) {
factlist <- c(paste0("log(", w.dataY, ") ~ 1"), gsub("dataY", w.dataY,
unlist(strsplit(formulaX, "+", fixed = TRUE))))
} else {
factlist <- c(paste(w.dataY, "~ 1"), gsub("dataY", w.dataY, unlist(strsplit(
formulaX,
"+", fixed = TRUE))))
}
aov_save <- as.data.frame(matrix(ncol = 5, nrow = length(factlist)))
rownames(aov_save) <- factlist
# For crossV indices
# load(file = paste0(saveWD, "/saveAleaM1.RData"))
saveAlea <- readr::read_rds(paste0(saveWD, "/saveAleaM1.rds"))
RMSE_crossV_save <- matrix(0, nrow = length(factlist), ncol = 2)
if (cl_inside) {
cl <- parallel::makePSOCKcluster(nbclust)
}
for (fl in 1:length(factlist)) {
if (fl == 1) {
model <- factlist[1]
if (grepl("GLM", modeltype)) {
assign(paste0("modelX", fl), stats::glm(as.formula(model),
data = Y_data_sample, family = Family, control = list(epsilon = 1e-06,
maxit = 1000)))
} else {
assign(paste0("modelX", fl), mgcv::gam(as.formula(model),
method = "REML", data = Y_data_sample, family = Family))
}
} else {
model <- paste(factlist[2:fl], collapse = "+")
if (grepl("GLM", modeltype)) {
assign(paste0("modelX", fl), stats::glm(as.formula(paste(factlist[2:fl],
collapse = "+")), data = Y_data_sample, family = Family,
control = list(epsilon = 1e-06, maxit = 1000)))
} else {
assign(paste0("modelX", fl), mgcv::gam(as.formula(paste(factlist[2:fl],
collapse = "+")), method = "REML", data = Y_data_sample,
family = Family))
}
# Compare anova
if (fl == 2) {
aov1 <- anova(get(paste0("modelX", fl - 1)), get(paste0("modelX",
fl)), test = "Chisq")
aov_save[1:2, ] <- aov1
names(aov_save) <- names(aov1)
} else {
aov_save[fl, ] <- anova(get(paste0("modelX", fl - 1)),
get(paste0("modelX", fl)), test = "Chisq")[2,]
}
}
print(model)
# Calculate crossV indices ----
RMSE_crossV <- snow::parApply(
cl, t(1:nbMC), 2,
function(MC,
formula, modeltype, saveAlea, Y_data_sample,
seqthd, resParam_save, nb, Y_data_sample_lcc,
MaxDist, Phi, Model, lambda) {
res <- crossV_indices(
MC = MC, formulas = t(t(formula)),
modeltype = modeltype, saveAlea = saveAlea, Y_data_sample = Y_data_sample,
seqthd = seqthd,
resParam_save = resParam_save, Y_data_sample_lcc = Y_data_sample_lcc,
MaxDist = MaxDist, Phi = Phi, model = Model,
lambda = lambda)
if (grepl("PA", modeltype)) {
res <- res["ROC_crossV",]
# Test for threshold value
# res <- res[grep("DiffSelSpe", rownames(res)),]
} else {
res <- res["RMSE_crossV",]
}
return(unlist(res))
c(res)
}, formula = gsub(" + 1", "", model, fixed = TRUE),
modeltype = modeltype,
saveAlea = saveAlea, Y_data_sample = Y_data_sample,
seqthd = seqthd, resParam_save = Param,
Y_data_sample_lcc = Y_data_sample_lcc, MaxDist = MaxDist, #nb = nb,
Phi = Phi, Model = Model[which(modeltypes == modeltype)],
lambda = Lambda[which(modeltypes == modeltype)])
# Test for threshold value
# plot(seqthd, RMSE_crossV[,1], type = "l")
# apply(RMSE_crossV, 2, function(x) lines(seqthd, x))
# lines(seqthd,
# apply(RMSE_crossV, 1, function(x) mean(x, na.rm = TRUE)),
# col = "red", lwd = 2)
RMSE_crossV_save[fl,1] <- mean(RMSE_crossV, na.rm = TRUE)
if (fl >= 2) {
RMSE_crossV_save[fl,2] <- RMSE_crossV_save[fl,1] - RMSE_crossV_save[fl - 1,1]
}
}
# Round values of RMSE properly
diff.rmse <- max(RMSE_crossV_save[,2]) - min(RMSE_crossV_save[fl,2])
if (grepl("PA", modeltype)) {
prec <- 2
} else {
prec <- 1
}
if (diff.rmse > 1) {
# precision defined by length of the number
n <- nchar(round(diff.rmse))
} else {