forked from boost-R/FDboost
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrossvalidation.R
More file actions
1747 lines (1468 loc) · 71.9 KB
/
crossvalidation.R
File metadata and controls
1747 lines (1468 loc) · 71.9 KB
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
#' Cross-Validation and Bootstrapping over Curves
#'
#' Cross-validation and bootstrapping over curves to compute the empirical risk for
#' hyper-parameter selection.
#'
#' @param object fitted FDboost-object
#' @param folds a weight matrix with number of rows equal to the number of observed trajectories.
#' @param grid the grid over which the optimal number of boosting iterations (mstop) is searched.
#' @param showProgress logical, defaults to \code{TRUE}.
#' @param compress logical, defaults to \code{FALSE}. Only used to force a meaningful
#' behaviour of \code{applyFolds} with hmatrix objects when using nested resampling.
#' @param papply (parallel) apply function, defaults to \code{\link{mclapply}} from
#' R package \code{parallel}, see \code{\link[mboost]{cvrisk}} for details.
#' @param fun if \code{fun} is \code{NULL}, the out-of-bag risk is returned.
#' \code{fun}, as a function of \code{object},
#' may extract any other characteristic of the cross-validated models. These are returned as is.
#' @param riskFun only exists in \code{applyFolds}; allows to compute other risk functions than the risk
#' of the family that was specified in object.
#' Must be specified as function of arguments \code{(y, f, w = 1)}, where \code{y} is the
#' observed response, \code{f} is the prediction from the model and \code{w} is the weight.
#' The risk function must return a scalar numeric value for vector valued input.
#' @param numInt only exists in \code{applyFolds}; the scheme for numerical integration,
#' see \code{numInt} in \code{\link{FDboost}}.
#' @param mc.preschedule Defaults to \code{FALSE}. Preschedule tasks if they are parallelized using \code{mclapply}.
#' For details see \code{\link{mclapply}}.
#' @param ... further arguments passed to the (parallel) apply function.
#'
#' @param id the id-vector as integers 1, 2, ... specifying which observations belong to the same curve,
#' deprecated in \code{cvMa()}.
#' @param weights a numeric vector of (integration) weights, defaults to 1.
#' @param type character argument for specifying the cross-validation
#' method. Currently (stratified) bootstrap, k-fold cross-validation, subsampling and
#' leaving-one-curve-out cross validation (i.e. jack knife on curves) are implemented.
#' @param B number of folds, per default 25 for \code{bootstrap} and
#' \code{subsampling} and 10 for \code{kfold}.
#' @param prob percentage of observations to be included in the learning samples
#' for subsampling.
#' @param strata a factor of the same length as \code{weights} for stratification.
#'
#' @param ydim dimensions of response-matrix
#'
#' @details The number of boosting iterations is an important hyper-parameter of boosting.
#' It be chosen using the functions \code{applyFolds} or \code{cvrisk.FDboost}. Those functions
#' compute honest, i.e., out-of-bag, estimates of the empirical risk for different
#' numbers of boosting iterations.
#' The weights (zero weights correspond to test cases) are defined via the folds matrix,
#' see \code{\link[mboost]{cvrisk}} in package mboost.
#'
#' In case of functional response, we recommend to use \code{applyFolds}.
#' It recomputes the model in each fold using \code{FDboost}. Thus, all parameters are recomputed,
#' including the smooth offset (if present) and the identifiability constraints (if present, only
#' relevant for \code{bolsc}, \code{brandomc} and \code{bbsc}).
#' Note, that the function \code{applyFolds} expects folds that give weights
#' per curve without considering integration weights.
#'
#' The function \code{cvrisk.FDboost} is a wrapper for \code{\link[mboost]{cvrisk}} in package mboost.
#' It overrides the default for the folds, so that the folds are sampled on the level of curves
#' (not on the level of single observations, which does not make sense for functional response).
#' Note that the smooth offset and the computation of the identifiability constraints
#' are not part of the refitting if \code{cvrisk} is used.
#' Per default the integration weights of the model fit are used to compute the prediction errors
#' (as the integration weights are part of the default folds).
#' Note that in \code{cvrisk} the weights are rescaled to sum up to one.
#'
#' The functions \code{cvMa} and \code{cvLong} can be used to build an appropriate
#' weight matrix for functional response to be used with \code{cvrisk} as sampling
#' is done on the level of curves. The probability for each
#' curve to enter a fold is equal over all curves.
#' The function \code{cvMa} takes the dimensions of the response matrix as input argument and thus
#' can only be used for regularly observed response.
#' The function \code{cvLong} takes the id variable and the weights as arguments and thus can be used
#' for responses in long format that are potentially observed irregularly.
#'
#' If \code{strata} is defined
#' sampling is performed in each stratum separately thus preserving
#' the distribution of the \code{strata} variable in each fold.
#'
#' @note Use argument \code{mc.cores = 1L} to set the numbers of cores that is used in
#' parallel computation. On Windows only 1 core is possible, \code{mc.cores = 1}, which is the default.
#'
#' @seealso \code{\link[mboost]{cvrisk}} to perform cross-validation with scalar response.
#'
#' @return \code{cvMa} and \code{cvLong} return a matrix of sampling weights to be used in \code{cvrisk}.
#'
#' The functions \code{applyFolds} and \code{cvrisk.FDboost} return a \code{cvrisk}-object,
#' which is a matrix of the computed out-of-bag risk. The matrix has the folds in rows and the
#' number of boosting iteratins in columns. Furhtermore, the matrix has attributes including:
#' \item{risk}{name of the applied risk function}
#' \item{call}{model call of the model object}
#' \item{mstop}{gird of stopping iterations that is used}
#' \item{type}{name for the type of folds}
#'
#' @examples
#' Ytest <- matrix(rnorm(15), ncol = 3) # 5 trajectories, each with 3 observations
#' Ylong <- as.vector(Ytest)
#' ## 4-folds for bootstrap for the response in long format without integration weights
#' cvMa(ydim = c(5,3), type = "bootstrap", B = 4)
#' cvLong(id = rep(1:5, times = 3), type = "bootstrap", B = 4)
#'
#' if(require(fda)){
#' ## load the data
#' data("CanadianWeather", package = "fda")
#'
#' ## use data on a daily basis
#' canada <- with(CanadianWeather,
#' list(temp = t(dailyAv[ , , "Temperature.C"]),
#' l10precip = t(dailyAv[ , , "log10precip"]),
#' l10precip_mean = log(colMeans(dailyAv[ , , "Precipitation.mm"]), base = 10),
#' lat = coordinates[ , "N.latitude"],
#' lon = coordinates[ , "W.longitude"],
#' region = factor(region),
#' place = factor(place),
#' day = 1:365, ## corresponds to t: evaluation points of the fun. response
#' day_s = 1:365)) ## corresponds to s: evaluation points of the fun. covariate
#'
#' ## center temperature curves per day
#' canada$tempRaw <- canada$temp
#' canada$temp <- scale(canada$temp, scale = FALSE)
#' rownames(canada$temp) <- NULL ## delete row-names
#'
#' ## fit the model
#' mod <- FDboost(l10precip ~ 1 + bolsc(region, df = 4) +
#' bsignal(temp, s = day_s, cyclic = TRUE, boundary.knots = c(0.5, 365.5)),
#' timeformula = ~ bbs(day, cyclic = TRUE, boundary.knots = c(0.5, 365.5)),
#' data = canada)
#' mod <- mod[75]
#'
#' \donttest{
#' #### create folds for 3-fold bootstrap: one weight for each curve
#' set.seed(123)
#' folds_bs <- cv(weights = rep(1, mod$ydim[1]), type = "bootstrap", B = 3)
#'
#' ## compute out-of-bag risk on the 3 folds for 1 to 75 boosting iterations
#' cvr <- applyFolds(mod, folds = folds_bs, grid = 1:75)
#'
#' ## weights per observation point
#' folds_bs_long <- folds_bs[rep(seq_len(nrow(folds_bs)), times = mod$ydim[2]), ]
#' attr(folds_bs_long, "type") <- "3-fold bootstrap"
#' ## compute out-of-bag risk on the 3 folds for 1 to 75 boosting iterations
#' cvr3 <- cvrisk(mod, folds = folds_bs_long, grid = 1:75)
#' }
#'
#' \donttest{
#' ## plot the out-of-bag risk
#' oldpar <- par(mfrow = c(1,3))
#' plot(cvr); legend("topright", lty=2, paste(mstop(cvr)))
#' plot(cvr3); legend("topright", lty=2, paste(mstop(cvr3)))
#' par(oldpar)
#' }
#'
#'}
#'
#' @aliases cvMa cvLong cvrisk.FDboost
#'
#' @export
## computes the empirical out-of-bag risk for each fold
applyFolds <- function(object, folds = cv(rep(1, length(unique(object$id))), type = "bootstrap"),
grid = 1:mstop(object), fun = NULL,
riskFun = NULL, numInt = object$numInt,
papply = mclapply,
mc.preschedule = FALSE,
showProgress = TRUE,
compress = FALSE,
...) {
if (is.null(folds)) {
stop("Specify folds.")
}
## check that folds are given on the level of curves
if(length(unique(object$id)) != nrow(folds)){
stop("The folds-matrix must have one row per observed trajectory.")
}
if(inherits(object, "FDboostLong")){ # irregular response
nObs <- length(unique(object$id)) # number of curves
Gy <- NULL # number of time-points per curve
}else{ # regular response / scalar response
nObs <- object$ydim[1] # number of curves
Gy <- object$ydim[2] # number of time-points per curve
if(class(object)[1] == "FDboostScalar"){
nObs <- length(object$response)
Gy <- 1
}
}
sample_weights <- rep(1, length(unique(object$id))) # length N
# if(any(sample_weights == 0)) warning("zero weights") # fullfilled per construction
# save integration weights of original model
if(is.null(numInt)){
numInt <- "equal"
warning("'numInt' is NULL. It is set to 'equal' which means that all integration weights are set to 1.")
}
if(!numInt %in% c("equal", "Riemann"))
warning("argument 'numInt' is ignored as it is none of 'equal' and 'Riemann'.")
if(is.numeric(numInt)){ # use the integration scheme specified in applyFolds
if(length(numInt) != length(object$yind)) stop("Length of integration weights and time vector are not equal.")
integration_weights <- numInt
}else{
if(numInt == "Riemann"){ # use the integration scheme specified in applyFolds
if(!inherits(object, "FDboostLong")){
integration_weights <- as.vector(integrationWeights(X1 = matrix(object$response,
ncol = object$ydim[2]), object$yind))
}else{
integration_weights <- integrationWeights(X1 = object$response, object$yind, object$id)
}
}else{ ## numInt == "equal"
integration_weights <- rep(1, length(object$response))
## correct integration weights for matrix valued response like possibly in Binomial()
if( class(object)[1] == "FDboostScalar") integration_weights <- rep(1, NROW(object$response))
}
}
### get yind in long format
yindLong <- object$yind
if(!inherits(object, "FDboostLong")){
yindLong <- rep(object$yind, each = nObs)
}
### compute ("length of each trajectory")^-1 in the response
### more precisely ("sum of integration weights")^-1 is used
if(numInt == "equal"){
lengthTi1 <- rep(1, l = length(unique(object$id)))
}else{
if(length(object$yind) > 1){
# lengthTi1 <- 1/tapply(yindLong[!is.na(response)], object$id[!is.na(response)], function(x) max(x) - min(x))
lengthTi1 <- 1/tapply(integration_weights, object$id, function(x) sum(x))
if(any(is.infinite(lengthTi1))) lengthTi1[is.infinite(lengthTi1)] <- max(lengthTi1[!is.infinite(lengthTi1)])
}else{
lengthTi1 <- rep(1, l = length(object$response))
}
}
# Function to suppress the warning of missings in the response
h <- function(w){
if( any( grepl( "response contains missing values;", w, fixed = TRUE) ) )
invokeRestart( "muffleWarning" )
}
### start preparing the data
dathelp <- object$data
nameyind <- attr(object$yind, "nameyind")
dathelp[[nameyind]] <- object$yind
## try to set up data using $get_data()
## problem with index for bl containing index, and you do not get s for bsignal/bhist
if(FALSE){
dathelp2 <- list()
for(j in seq_along(object$baselearner)){
dat_bl_j <- object$baselearner[[j]]$get_data() ## object$baselearner[[j]]$model.frame()
# if the variable is already present, do not add it again
dathelp2 <- c(dathelp2, dat_bl_j[!names(dat_bl_j) %in% names(dathelp2)])
}
}
if(!inherits(object, "FDboostLong") && !inherits(object, "FDboostScalar")){
dathelp[[object$yname]] <- matrix(object$response, ncol=object$ydim[2])
dathelp$integration_weights <- matrix(integration_weights, ncol=object$ydim[2])
dathelp$object_id <- object$id
}else{
dathelp[[object$yname]] <- object$response
dathelp$integration_weights <- integration_weights
}
## get the names of all variables x_i, i = 1, ... , N
names_variables <- unlist(lapply(object$baselearner, function(x) x$get_names() ))
## check for index
has_index <- sapply(object$baselearner, function(x) !is.null(x$get_index()))
if( any( has_index )){
index_names <- sapply(lapply(object$baselearner[has_index], function(x) x$get_call()),
function(l) gsub("index[[:space:]*]=[[:space:]*]|\\,","",
regmatches(l, regexpr('index[[:space:]*]=.*\\,', l)))
)
} else index_names <- NULL
names(names_variables) <- NULL
names_variables <- names_variables[names_variables != nameyind]
names_variables <- names_variables[names_variables != "ONEx"]
names_variables <- names_variables[names_variables != "ONEtime"]
if(!inherits(object, "FDboostLong")) names_variables <- c(object$yname, "integration_weights", names_variables)
length_variables <- if(inherits(object, "FDboostScalar"))
lapply(dathelp[names_variables], length) else
lapply(dathelp[names_variables], NROW)
names_variables_long <- names_variables[ length_variables == length(object$id) ]
nothmatrix <- ! sapply(dathelp[names_variables_long], is.hmatrix)
names_variables_long <- names_variables_long[ nothmatrix ]
if(identical(names_variables_long, character(0))) names_variables_long <- NULL
names_variables <- names_variables[! names_variables %in% names_variables_long ]
if(identical(names_variables, character(0))) names_variables <- NULL
## check if there is a baselearner without brackets
# the probelm with such base-learners is that their data is not contained in object$data
# using object$baselearner[[j]]$get_data() is difficult as this can be blow up by index for %X%
singleBls <- gsub("\\s", "", unlist(lapply(strsplit(
strsplit(object$formulaFDboost, "~", fixed = TRUE)[[1]][2], # split formula
"+", fixed = TRUE)[[1]], # split additive terms
function(y) strsplit(y, split = "%.{1,3}%")) # split single baselearners
))
singleBls <- singleBls[singleBls != "1"]
if(any(!grepl("(", singleBls, fixed = TRUE)))
stop(paste0("applyFolds can not deal with the following base-learner(s) without brackets: ",
toString(singleBls[!grepl("(", singleBls, fixed = TRUE)])))
## check if data includes all variables
if(any(whMiss <- ! c(names_variables,
object$yname,
nameyind,
"integration_weights",
names_variables_long) %in% names(dathelp))){
# for each missing variable get the first baselearner, which contains the variable
blWithMissVars <- lapply(names_variables[whMiss], function(w)
unlist(lapply(seq_along(object$baselearner), function(i) if(
any( grepl(w, object$baselearner[[i]]$get_names() ) )) return(i))
)[1])
stop(paste0("base-learner(s) ", toString(unlist(list(1,2))),
" contain(s) variables, which are not part of the data object."))
}
## fitfct <- object$update
fitfct <- function(weights, oobweights){
## get data according to weights
if(inherits(object, "FDboostLong")){
dat_weights <- reweightData(data = dathelp, vars = names_variables,
longvars = c(object$yname, nameyind, "integration_weights", names_variables_long),
weights = weights, idvars = c(attr(object$id, "nameid"), index_names),
compress = compress)
}else if(class(object)[1] == "FDboostScalar"){
dat_weights <- reweightData(data = dathelp,
vars = c(names_variables, names_variables_long),
weights = weights)
}else{
dat_weights <- reweightData(data = dathelp, vars = names_variables,
longvars = names_variables_long,
weights = weights, idvars = c("object_id", index_names))
}
# check for factors
isFac <- sapply(dathelp, is.factor)
if(any(isFac)){
namesFac <- names(isFac)[isFac]
for(i in seq_along(namesFac)){
if(nlevels(droplevels(dathelp[[namesFac[i]]])) !=
nlevels(droplevels(dat_weights[[namesFac[i]]])))
stop(paste0("The factor variable '", namesFac[i], "' has unobserved levels in the training data. ",
"Make sure that training data in each fold contains all factor levels."))
}
}
call <- object$callEval
call$data <- dat_weights
if(! is.null(call$weights)) warning("Argument weights of original model is not considered.")
call$weights <- NULL
## fit the model for dat_weights
mod <- withCallingHandlers(suppressMessages(eval(call)), warning = h) # suppress the warning of missing responses
mod <- mod[max(grid)]
mod
}
## create data frame for model fit and use the weights vector for the CV
# oobrisk <- matrix(0, nrow = ncol(folds), ncol = length(grid))
if (!is.null(fun))
stopifnot(is.function(fun))
fam_name <- object$family@name
call <- deparse(object$call)
if (is.null(fun)) {
dummyfct <- function(weights, oobweights) {
mod <- fitfct(weights = weights, oobweights = oobweights)
mod <- mod[max(grid)]
# mod$risk()[grid]
# get risk function of the family
if(is.null(riskFun)){
myfamily <- get("family", environment(mod$update))
riskfct <- myfamily@risk
}else{
stopifnot(is.function(riskFun))
riskfct <- riskFun
}
## get data according to oobweights
if(inherits(object, "FDboostLong")){
dathelp$lengthTi1 <- c(lengthTi1)
dat_oobweights <- reweightData(data = dathelp, vars = c(names_variables, "lengthTi1"),
longvars = c(object$yname, nameyind,
"integration_weights", names_variables_long),
weights = oobweights,
idvars = c(attr(object$id, "nameid"), index_names),
compress = compress)
## funplot(dat_oobweights[[nameyind]], dat_oobweights[[object$yname]],
## id = dat_oobweights[[attr(object$id, "nameid")]])
for(v in names_variables){ ## blow up covariates by id so that data can be used with predict()
if(!is.null(dim(dat_oobweights[[v]]))){
dat_oobweights[[v]] <- dat_oobweights[[v]][dat_oobweights[[attr(object$id, "nameid")]], ]
}else{
dat_oobweights[[v]] <- dat_oobweights[[v]][dat_oobweights[[attr(object$id, "nameid")]]]
}
}
response_oobweights <- c(dat_oobweights[[object$yname]])
}else{ ## scalar or regular response
if(class(object)[1] == "FDboostScalar"){
dat_oobweights <- reweightData(data = dathelp,
vars = c(names_variables, names_variables_long),
weights = oobweights)
response_oobweights <- dat_oobweights[[object$yname]]
}else{
dat_oobweights <- reweightData(data = dathelp, vars = names_variables,
longvars = names_variables_long,
weights = oobweights, idvars = c("object_id", index_names))
response_oobweights <- c(dat_oobweights[[object$yname]])
}
}
if(is.character(response_oobweights)) response_oobweights <- factor(response_oobweights)
## this check is important for Binomial() as it recodes factor to -1, 1
response_oobweights <- myfamily@check_y(response_oobweights)
# Function to suppress the warning of extrapolation in bbs / bbsc
h2 <- function(w){
if( any( grepl( "Linear extrapolation used.", w) ) )
invokeRestart( "muffleWarning" )
}
if(inherits(object, "FDboostLong")){
if(numInt == "equal"){
oobwstand <- dat_oobweights$integration_weights * (1/sum(dat_oobweights$integration_weights))
}else{
# compute integration weights for standardizing risk
oobwstand <- dat_oobweights$lengthTi1[dat_oobweights[[attr(object$id, "nameid")]]] *
dat_oobweights$integration_weights * (1/sum(oobweights))
}
# compute risk with integration weights like in FDboost::validateFDboost
risk <- sapply(grid, function(g){riskfct(
response_oobweights,
withCallingHandlers(predict(mod[g], newdata = dat_oobweights, toFDboost = FALSE), warning = h2),
w = oobwstand )}) ## oobwstand[oobweights[object$id] != 0 ]
}else{
if(numInt == "equal"){ # oobweights for i = 1, ..., N
oobwstand <- oobweights[object$id]*(1/sum(oobweights[object$id]))
}else{
# compute integration weights for standardizing risk
oobwstand <- lengthTi1[object$id]*oobweights[object$id]*integration_weights*(1/sum(oobweights))
}
# compute risk with integration weights like in FDboost::validateFDboost
risk <- sapply(grid, function(g){riskfct(
response_oobweights,
withCallingHandlers(predict(mod[g], newdata = dat_oobweights, toFDboost = FALSE), warning = h2),
w = oobwstand[oobweights != 0 ])})
}
if(showProgress) cat(".")
risk
}
} else { ## !is.null(fun)
if(!is.null(riskFun)) warning("riskFun is ignored as fun is specified.")
dummyfct <- function(weights, oobweights) {
mod <- fitfct(weights = weights, oobweights = oobweights)
mod[max(grid)]
## make sure dispatch works correctly
class(mod) <- class(object)
fun(mod) # Provide an extra argument for dat_oobweights?
}
}
## use case weights as out-of-bag weights (but set inbag to 0)
OOBweights <- matrix(rep(sample_weights, ncol(folds)), ncol = ncol(folds))
OOBweights[folds > 0] <- 0
if (isTRUE(all.equal(papply, mclapply))) {
oobrisk <- papply(seq_len(ncol(folds)),
function(i) try(dummyfct(weights = folds[, i],
oobweights = OOBweights[, i]),
silent = TRUE),
mc.preschedule = mc.preschedule,
...)
} else {
oobrisk <- papply(seq_len(ncol(folds)),
function(i) try(dummyfct(weights = folds[, i],
oobweights = OOBweights[, i]),
silent = TRUE),
...)
}
## if any errors occured remove results and issue a warning
if (any(idx <- sapply(oobrisk, is.character))) {
if(sum(idx) == length(idx)){
stop("All folds encountered an error.\n",
"Original error message(s):\n",
sapply(oobrisk[idx], function(x) x))
}
warning(sum(idx), " fold(s) encountered an error. ",
"Results are based on ", ncol(folds) - sum(idx),
" folds only.\n",
"Original error message(s):\n",
sapply(oobrisk[idx], function(x) x))
oobrisk[idx] <- NULL
}
if (!is.null(fun))
return(oobrisk)
oobrisk <- t(as.data.frame(oobrisk))
## oobrisk <- oobrisk / colSums(OOBweights[object$id, ]) # is done in dummyfct()
colnames(oobrisk) <- grid
rownames(oobrisk) <- seq_len(nrow(oobrisk))
attr(oobrisk, "risk") <- fam_name
attr(oobrisk, "call") <- call
attr(oobrisk, "mstop") <- grid
attr(oobrisk, "type") <- ifelse(!is.null(attr(folds, "type")),
attr(folds, "type"), "user-defined")
class(oobrisk) <- c("cvrisk", "applyFolds")
oobrisk
}
#' Cross-Validation and Bootstrapping over Curves
#'
#' DEPRECATED!
#' The function \code{validateFDboost()} is deprecated,
#' use \code{\link{applyFolds}} and \code{\link{bootstrapCI}} instead.
#'
#' @param object fitted FDboost-object
#' @param response optional, specify a response vector for the computation of the prediction errors.
#' Defaults to \code{NULL} which means that the response of the fitted model is used.
#' @param folds a weight matrix with number of rows equal to the number of observed trajectories.
#' @param grid the grid over which the optimal number of boosting iterations (mstop) is searched.
#' @param getCoefCV logical, defaults to \code{TRUE}. Should the coefficients and predictions
#' be computed for all the models on the sampled data?
#' @param riskopt how is the optimal stopping iteration determined. Defaults to the mean,
#' but median is possible as well.
#' @param mrdDelete Delete values that are \code{mrdDelete} percent smaller than the mean
#' of the response. Defaults to 0 which means that only response values being 0
#' are not used in the calculation of the MRD (= mean relative deviation).
#' @param refitSmoothOffset logical, should the offset be refitted in each learning sample?
#' Defaults to \code{TRUE}. In \code{\link[mboost]{cvrisk}} the offset of the original model fit in
#' \code{object} is used in all folds.
#' @param showProgress logical, defaults to \code{TRUE}.
#' @param fun if \code{fun} is \code{NULL}, the out-of-bag risk is returned.
#' \code{fun}, as a function of \code{object},
#' may extract any other characteristic of the cross-validated models. These are returned as is.
#'
#' @param ... further arguments passed to \code{\link{mclapply}}
#'
#' @details The number of boosting iterations is an important hyper-parameter of boosting
#' and can be chosen using the function \code{validateFDboost} as they compute
#' honest, i.e., out-of-bag, estimates of the empirical risk for different numbers of boosting iterations.
#'
#' The function \code{validateFDboost} is especially suited to models with functional response.
#' Using the option \code{refitSmoothOffset} the offset is refitted on each fold.
#' Note, that the function \code{validateFDboost} expects folds that give weights
#' per curve without considering integration weights. The integration weights of
#' \code{object} are used to compute the empirical risk as integral. The argument \code{response}
#' can be useful in simulation studies where the true value of the response is known but for
#' the model fit the response is used with noise.
#'
#' @return The function \code{validateFDboost} returns a \code{validateFDboost}-object,
#' which is a named list containing:
#' \item{response}{the response}
#' \item{yind}{the observation points of the response}
#' \item{id}{the id variable of the response}
#' \item{folds}{folds that were used}
#' \item{grid}{grid of possible numbers of boosting iterations}
#' \item{coefCV}{if \code{getCoefCV} is \code{TRUE} the estimated coefficient functions in the folds}
#' \item{predCV}{if \code{getCoefCV} is \code{TRUE} the out-of-bag predicted values of the response}
#' \item{oobpreds}{if the type of folds is curves the out-of-bag predictions for each trajectory}
#' \item{oobrisk}{the out-of-bag risk}
#' \item{oobriskMean}{the out-of-bag risk at the minimal mean risk}
#' \item{oobmse}{the out-of-bag mean squared error (MSE)}
#' \item{oobrelMSE}{the out-of-bag relative mean squared error (relMSE)}
#' \item{oobmrd}{the out-of-bag mean relative deviation (MRD)}
#' \item{oobrisk0}{the out-of-bag risk without consideration of integration weights}
#' \item{oobmse0}{the out-of-bag mean squared error (MSE) without consideration of integration weights}
#' \item{oobmrd0}{the out-of-bag mean relative deviation (MRD) without consideration of integration weights}
#' \item{format}{one of "FDboostLong" or "FDboost" depending on the class of the object}
#' \item{fun_ret}{list of what fun returns if fun was specified}
#'
#' @examples
#' \donttest{
#' if(require(fda)){
#' ## load the data
#' data("CanadianWeather", package = "fda")
#'
#' ## use data on a daily basis
#' canada <- with(CanadianWeather,
#' list(temp = t(dailyAv[ , , "Temperature.C"]),
#' l10precip = t(dailyAv[ , , "log10precip"]),
#' l10precip_mean = log(colMeans(dailyAv[ , , "Precipitation.mm"]), base = 10),
#' lat = coordinates[ , "N.latitude"],
#' lon = coordinates[ , "W.longitude"],
#' region = factor(region),
#' place = factor(place),
#' day = 1:365, ## corresponds to t: evaluation points of the fun. response
#' day_s = 1:365)) ## corresponds to s: evaluation points of the fun. covariate
#'
#' ## center temperature curves per day
#' canada$tempRaw <- canada$temp
#' canada$temp <- scale(canada$temp, scale = FALSE)
#' rownames(canada$temp) <- NULL ## delete row-names
#'
#' ## fit the model
#' mod <- FDboost(l10precip ~ 1 + bolsc(region, df = 4) +
#' bsignal(temp, s = day_s, cyclic = TRUE, boundary.knots = c(0.5, 365.5)),
#' timeformula = ~ bbs(day, cyclic = TRUE, boundary.knots = c(0.5, 365.5)),
#' data = canada)
#' mod <- mod[75]
#'
#' #### create folds for 3-fold bootstrap: one weight for each curve
#' set.seed(124)
#' folds_bs <- cv(weights = rep(1, mod$ydim[1]), type = "bootstrap", B = 3)
#'
#' ## compute out-of-bag risk on the 3 folds for 1 to 75 boosting iterations
#' cvr <- applyFolds(mod, folds = folds_bs, grid = 1:75)
#'
#' ## compute out-of-bag risk and coefficient estimates on folds
#' cvr2 <- validateFDboost(mod, folds = folds_bs, grid = 1:75)
#'
#' ## weights per observation point
#' folds_bs_long <- folds_bs[rep(seq_len(nrow(folds_bs)), times = mod$ydim[2]), ]
#' attr(folds_bs_long, "type") <- "3-fold bootstrap"
#' ## compute out-of-bag risk on the 3 folds for 1 to 75 boosting iterations
#' cvr3 <- cvrisk(mod, folds = folds_bs_long, grid = 1:75)
#'
#' ## plot the out-of-bag risk
#' oldpar <- par(mfrow = c(1,3))
#' plot(cvr); legend("topright", lty=2, paste(mstop(cvr)))
#' plot(cvr2)
#' plot(cvr3); legend("topright", lty=2, paste(mstop(cvr3)))
#'
#' ## plot the estimated coefficients per fold
#' ## more meaningful for higher number of folds, e.g., B = 100
#' par(mfrow = c(2,2))
#' plotPredCoef(cvr2, terms = FALSE, which = 1)
#' plotPredCoef(cvr2, terms = FALSE, which = 3)
#'
#' ## compute out-of-bag risk and predictions for leaving-one-curve-out cross-validation
#' cvr_jackknife <- validateFDboost(mod, folds = cvLong(unique(mod$id),
#' type = "curves"), grid = 1:75)
#' plot(cvr_jackknife)
#' ## plot oob predictions per fold for 3rd effect
#' plotPredCoef(cvr_jackknife, which = 3)
#' ## plot coefficients per fold for 2nd effect
#' plotPredCoef(cvr_jackknife, which = 2, terms = FALSE)
#'
#' par(oldpar)
#'
#'}
#'}
#'
#' @export
validateFDboost <- function(object, response = NULL,
#folds=cvMa(ydim=object$ydim, weights=model.weights(object), type="bootstrap"),
folds = cv(rep(1, length(unique(object$id))), type = "bootstrap"),
grid = 1:mstop(object),
fun = NULL,
getCoefCV = TRUE, riskopt = c("mean","median"),
mrdDelete = 0, refitSmoothOffset = TRUE,
showProgress = TRUE, ...){
.Deprecated(new = "applyFolds",
msg = "'validateFDboost' is deprecated. Use 'applyFolds' and 'bootstrapCI' instead.")
names_bl <- names(object$baselearner)
if(any(grepl("brandomc", names_bl, fixed = TRUE))) message("For brandomc, the transformation matrix Z is fixed over all folds.")
if(any(grepl("bolsc", names_bl, fixed = TRUE))) message("For bolsc, the transformation matrix Z is fixed over all folds.")
if(any(grepl("bbsc", names_bl, fixed = TRUE))) message("For bbsc, the transformation matrix Z is fixed over all folds.")
type <- attr(folds, "type")
if(is.null(type)) type <- "unknown"
call <- match.call()
riskopt <- match.arg(riskopt)
## check that folds are given on the level of curves
if(length(unique(object$id)) != nrow(folds)){
stop("The folds-matrix must have one row per observed trajectory.")
}
if(inherits(object, "FDboostLong")){ # irregular response
nObs <- length(unique(object$id)) # number of curves
Gy <- NULL # number of time-points per curve
}else{ # regular response / scalar response
nObs <- object$ydim[1] # number of curves
Gy <- object$ydim[2] # number of time-points per curve
if(class(object)[1] == "FDboostScalar"){
nObs <- length(object$response)
Gy <- 1
}
}
myfamily <- get("family", environment(object$update))
if(is.null(response)) response <- object$response # response as vector!
# for Binomial() transform factor to -1/1 coding
response <- myfamily@check_y(response)
id <- object$id
# save integration weights of original model
# intWeights <- model.weights(object)
# weights are rescaled in mboost, see mboost:::rescale_weights
if(!is.null(object$callEval$numInt) && object$callEval$numInt == "Riemann"){
if(!inherits(object, "FDboostLong")){
intWeights <- as.vector(integrationWeights(X1 = matrix(object$response,
ncol = object$ydim[2]), object$yind))
}else{
intWeights <- integrationWeights(X1=object$response, object$yind, id)
}
}else{
intWeights <- model.weights(object)
}
# out-of-bag-weights: i.e. the left out curve/ the left out observations
OOBweights <- matrix(1, ncol = ncol(folds), nrow = nrow(folds))
OOBweights[folds > 0] <- 0
# Function to suppress the warning of missings in the response
h <- function(w){
if( any( grepl( "response contains missing values;", w, fixed = TRUE) ) )
invokeRestart( "muffleWarning" )
}
### get yind in long format
yindLong <- object$yind
if(!inherits(object, "FDboostLong")){
yindLong <- rep(object$yind, each = nObs)
}
### compute ("length of each trajectory")^-1 in the response
### more precisely ("sum of integration weights")^-1 is used
if(length(object$yind) > 1){
# lengthTi1 <- 1/tapply(yindLong[!is.na(response)], id[!is.na(response)], function(x) max(x) - min(x))
lengthTi1 <- 1/tapply(intWeights, id, function(x) sum(x))
if(any(is.infinite(lengthTi1))) lengthTi1[is.infinite(lengthTi1)] <- max(lengthTi1[!is.infinite(lengthTi1)])
}else{
lengthTi1 <- rep(1, l = length(response))
}
###### Function to fit the model
# function working with FDboost, thus the smooth offset is recalculated in each model
dummyfct <- function(weights, oobweights) {
# create data frame for model fit and use the weights vector for the CV
dathelp <- object$data
nameyind <- attr(object$yind, "nameyind")
dathelp[[nameyind]] <- object$yind
if(!inherits(object, "FDboostLong") && !inherits(object, "FDboostScalar")){
dathelp[[object$yname]] <- matrix(object$response, ncol = Gy)
}else{
dathelp[[object$yname]] <- object$response
}
call <- object$callEval
call$data <- dathelp
# use weights of training data expanded by id to suitable length
call$weights <- weights[id]
# use call$numInt of original model fit, as weights contains only resampling weights
# Using the offset of object with the following settings
# call$control <- boost_control(risk="oobag")
# call$oobweights <- oobweights[id]
if(!refitSmoothOffset && is.null(call$offset) ){
if(!inherits(object, "FDboostLong")){
call$offset <- matrix(object$offset, ncol = Gy)[1, ]
}else{
call$offset <- object$offset
}
}
# the model is the same for
# mod <- object$update(weights = weights, oobweights = oobweights) # (cvrisk)
# and
# mod <- withCallingHandlers(suppressMessages(eval(call)), warning = h)
# and then the risk can be computed by
# risk <- mod$risk()[grid]
## compute the model by FDboost() - the offset is computed on learning sample
mod <- withCallingHandlers(suppressMessages(eval(call)), warning = h) # suppress the warning of missing responses
mod <- mod[max(grid)]
# compute weights for standardizing risk, mse, ...
oobwstand <- lengthTi1[id]*oobweights[id]*intWeights*(1/sum(oobweights))
############# compute risk, mse, relMSE and mrd
# get risk function of the family
riskfct <- get("family", environment(mod$update))@risk
####################
### compute risk and mse without integration weights, like in cvrisk
risk0 <- sapply(grid, function(g){riskfct(response, mod[g]$fitted(),
w = oobweights[id])}) / sum(oobweights[id])
mse0 <- simplify2array(mclapply(grid, function(g){
sum( ((response - mod[g]$fitted())^2*oobweights[id]), na.rm = TRUE )
}, mc.cores=1) ) /sum(oobweights[id])
####################
# oobweights using riskfct() like in mboost, but with different weights!
risk <- sapply(grid, function(g){riskfct( response, mod[g]$fitted(), w=oobwstand)})
### mse (mean squared error) equals risk in the case of familiy=Gaussian()
mse <- simplify2array(mclapply(grid, function(g){
sum( ((response - mod[g]$fitted())^2*oobwstand), na.rm = TRUE )
}, mc.cores=1) )
# ### mse2 equals mse in the case of equal grids without missings at the ends
# mse2 <- simplify2array(mclapply(grid, function(g){
# sum( ((response - mod[g]$fitted())^2*oobweights[id]*intWeights), na.rm=TRUE )
# }, mc.cores=1) ) / (sum(oobweights)* (max(mod$yind)-min(mod$yind) ) )
### compute overall mean of response in learning sample
meanResp <- sum(response*intWeights*lengthTi1[id]*weights[id], na.rm = TRUE) / sum(weights)
# # compute overall mean of response in whole sample
# meanResp <- sum(response*intWeights*lengthTi1[id], na.rm=TRUE) / nObs
### compute relative mse
relMSE <- simplify2array(mclapply(grid, function(g){
sum( ((response - mod[g]$fitted())^2*oobwstand), na.rm = TRUE ) /
sum( ((response - meanResp)^2*oobwstand), na.rm = TRUE )
}, mc.cores=1) )
### mean relative deviation
resp0 <- response
resp0[abs(resp0) <= mrdDelete | round(resp0, 1) == 0] <- NA
mrd <- simplify2array(mclapply(grid, function(g){
sum( abs(resp0 - mod[g]$fitted())/abs(resp0)*oobwstand, na.rm = TRUE )
}, mc.cores=1) )
mrd0 <- simplify2array(mclapply(grid, function(g){
sum( abs(resp0 - mod[g]$fitted())/abs(resp0)*oobweights[id], na.rm = TRUE)
}, mc.cores=1) ) / sum(oobweights[id])
rm(resp0, meanResp)
####### prediction for all observations, not only oob!
# the predictions are in a long vector for all model types (regular, irregular, scalar)
predGrid <- predict(mod, aggregate = "cumsum", toFDboost = FALSE)
predGrid <- predGrid[ , grid] # save vectors of predictions for grid in matrix
if(showProgress) cat(".")
## user-specified function to use on FDboost-object
if(! is.null(fun) ){
fun_ret <- fun(mod)
}else{
fun_ret <- NULL
}
return(list(risk = risk, predGrid = predGrid, # predOOB = predOOB, respOOB = respOOB,
mse = mse, relMSE = relMSE, mrd = mrd, risk0 = risk0, mse0 = mse0, mrd0 = mrd0,
mod = mod, fun_ret = fun_ret))
}
### computation of models on partitions of data
if(Sys.info()["sysname"]=="Linux"){
modRisk <- mclapply(seq_len(ncol(folds)),
function(i) dummyfct(weights = folds[, i],
oobweights = OOBweights[, i]), ...)
}else{
modRisk <- mclapply(seq_len(ncol(folds)),
function(i) dummyfct(weights = folds[, i],
oobweights = OOBweights[, i]), mc.cores = 1)
}
# str(modRisk, max.level=2)
# str(modRisk, max.level=5)
# check whether model fit worked in all iterations
modFitted <- sapply(modRisk, is.list)
if(any(!modFitted)){
# stop() or warning()?
if(sum(!modFitted) > sum(modFitted)) warning("More than half of the models could not be fitted.")
warning("Model fit did not work in fold ", toString(which(!modFitted)))
modRisk <- modRisk[modFitted]
OOBweights <- OOBweights[,modFitted]
folds <- folds[,modFitted]
}
####### restructure the results
## get the out-of-bag risk
oobrisk <- t(sapply(modRisk, function(x) x$risk))
## get out-of-bag mse
oobmse <- t(sapply(modRisk, function(x) x$mse))
## get out-of-bag relMSE
oobrelMSE <- t(sapply(modRisk, function(x) x$relMSE))
## get out-of-bag mrd
oobmrd <- t(sapply(modRisk, function(x) x$mrd))
colnames(oobrisk) <- colnames(oobmse) <- colnames(oobrelMSE) <- colnames(oobmrd) <- grid
rownames(oobrisk) <- rownames(oobmse) <- rownames(oobrelMSE) <- rownames(oobmrd) <- which(modFitted)
## get out-of-bag risk without integration weights
oobrisk0 <- t(sapply(modRisk, function(x) x$risk0))
## get out-of-bag mse without integration weights
oobmse0 <- t(sapply(modRisk, function(x) x$mse0))
## get out-of-bag mrd without integration weights
oobmrd0 <- t(sapply(modRisk, function(x) x$mrd0))
colnames(oobrisk0) <- colnames(oobmse0) <- colnames(oobmrd0) <- grid
rownames(oobrisk0) <- rownames(oobmse0) <- rownames(oobmrd0) <- which(modFitted)
############# check for folds with extreme risk-values at the global median
riskOptimal <- oobrisk[ , which.min(apply(oobrisk, 2, median))]
bound <- median(riskOptimal) + 1.5*(quantile(riskOptimal, 0.75) - quantile(riskOptimal, 0.25))
# fold equals curve if type="curves"
if(any(riskOptimal>bound)){
message("Fold with high values in oobrisk (median is ", round(median(riskOptimal), 2), "):")
message(paste("In fold ", which(riskOptimal > bound), ": " ,
round(riskOptimal[which(riskOptimal > bound)], 2), collapse = ", ", sep = "" ) )
}
## only makes sense for type="curves" with leaving-out one curve per fold!!
if(grepl( "curves", type, fixed = TRUE)){
# predict response for all mstops in grid out of bag
# predictions for each response are in a vector!
oobpreds0 <- lapply(modRisk, function(x) x$predGrid)
oobpreds <- matrix(nrow = nrow(oobpreds0[[1]]), ncol = ncol(oobpreds0[[1]]))
if(inherits(object, "FDboostLong")){
for(i in seq_along(oobpreds0)){ # i runs over observed trajectories, i.e. over id
oobpreds[id == i, ] <- oobpreds0[[i]][id == i, ]
}
}else{
for(j in seq_along(oobpreds0)){
oobpreds[folds[ , j] == 0] <- oobpreds0[[j]][folds[ , j] == 0]
}
}
colnames(oobpreds) <- grid
rm(oobpreds0)
}else{
oobpreds <- NULL
}
# # alternative OOB-prediction: works for general folds not only oob
# predOOB <- lapply(modRisk, function(x) x$predOOB)
# predOOB <- do.call('rbind', predOOB)
# colnames(predOOB) <- grid
# respOOB <- lapply(modRisk, function(x) x$respOOB)
# respOOB <- do.call('c', respOOB)
# indexOOB <- lapply(modRisk, function(x) attr(x$respOOB, "curves"))
# if(is.null(object$id)){
# indexOOB <- lapply(indexOOB, function(x) rep(x, times=Gy) )
# indexOOB <- unlist(indexOOB)
# }else{
# indexOOB <- names(unlist(indexOOB))[unlist(indexOOB)]
# }
# attr(respOOB, "index") <- indexOOB
coefCV <- list()
predCV <- list()
if(getCoefCV){