-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathmodels.R
executable file
·7081 lines (6719 loc) · 275 KB
/
models.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
#
# H2O Model Related Functions
#
#' @importFrom graphics strwidth par legend polygon arrows points grid
#' @importFrom grDevices dev.copy dev.off png rainbow adjustcolor
#' @include classes.R
NULL
#-----------------------------------------------------------------------------------------------------------------------
# Helper Functions
#-----------------------------------------------------------------------------------------------------------------------
#'
#' Used to verify data, x, y and turn into the appropriate things
#'
#' @param data H2OFrame
#' @param x features
#' @param y response
#' @param autoencoder autoencoder flag
.verify_dataxy <- function(data, x, y, autoencoder = FALSE) {
if (is(x, "H2OInfogram"))
x<-x@admissible_features
if(!is.null(x) && !is.character(x) && !is.numeric(x)) # only check if x is not null
stop('`x` must be column names or indices')
if( !autoencoder )
if(!is.character(y) && !is.numeric(y))
stop('`y` must be a column name or index')
cc <- colnames(chk.H2OFrame(data))
if (!is.null(x)) {
if(is.character(x)) {
if(!all(x %in% cc))
stop("Invalid column names: ", paste(x[!(x %in% cc)], collapse = ','))
x_i <- match(x, cc)
} else {
if(any( x < 1L | x > attr(x,'ncol')))
stop('out of range explanatory variable ', paste(x[x < 1L | x > length(cc)], collapse = ','))
x_i <- x
x <- cc[x_i]
}
} else {
x_i <- NULL
}
x_ignore <- c()
if( !autoencoder ) {
if(is.character(y)){
if(!(y %in% cc))
stop(y, ' is not a column name')
y_i <- which(y == cc)
} else {
if(y < 1L || y > length(cc))
stop('response variable index ', y, ' is out of range')
y_i <- y
y <- cc[y]
}
if(!is.null(x) && !autoencoder && (y %in% x)) {
warning('removing response variable from the explanatory variables')
x <- setdiff(x,y)
}
x_ignore <- setdiff(setdiff(cc, x), y)
if( length(x_ignore) == 0L ) x_ignore <- ''
return(list(x=x, y=y, x_i=x_i, x_ignore=x_ignore, y_i=y_i))
} else {
x_ignore <- setdiff(cc, x)
if( !missing(y) ) stop("`y` should not be specified for autoencoder=TRUE, remove `y` input")
return(list(x=x,x_i=x_i,x_ignore=x_ignore))
}
}
.verify_datacols <- function(data, cols) {
if(!is.character(cols) && !is.numeric(cols))
stop('`cols` must be column names or indices')
cc <- colnames(chk.H2OFrame(data))
if(length(cols) == 1L && cols == '')
cols <- cc
if(is.character(cols)) {
if(!all(cols %in% cc))
stop("Invalid column names: ", paste(cols[which(!cols %in% cc)], collapse=", "))
cols_ind <- match(cols, cc)
} else {
if(any(cols < 1L | cols > length(cc)))
stop('out of range explanatory variable ', paste(cols[cols < 1L | cols > length(cc)], collapse=','))
cols_ind <- cols
cols <- cc[cols_ind]
}
cols_ignore <- setdiff(cc, cols)
if( length(cols_ignore) == 0L )
cols_ignore <- ''
list(cols=cols, cols_ind=cols_ind, cols_ignore=cols_ignore)
}
.build_cm <- function(cm, actual_names = NULL, predict_names = actual_names, transpose = TRUE) {
categories <- length(cm)
cf_matrix <- matrix(unlist(cm), nrow=categories)
if(transpose)
cf_matrix <- t(cf_matrix)
cf_total <- apply(cf_matrix, 2L, sum)
cf_error <- c(1 - diag(cf_matrix)/apply(cf_matrix,1L,sum), 1 - sum(diag(cf_matrix))/sum(cf_matrix))
cf_matrix <- rbind(cf_matrix, cf_total)
cf_matrix <- cbind(cf_matrix, round(cf_error, 3L))
if(!is.null(actual_names))
dimnames(cf_matrix) = list(Actual = c(actual_names, "Totals"), Predicted = c(predict_names, "Error"))
cf_matrix
}
.h2o.modelJob <- function( algo, params, h2oRestApiVersion=.h2o.__REST_API_VERSION, verbose=FALSE) {
if( !is.null(params$validation_frame) )
.eval.frame(params$training_frame)
if( !is.null(params$validation_frame) )
.eval.frame(params$validation_frame)
if (length(grep("stopping_metric", attributes(params)))>0) {
if (params$stopping_metric=="r2")
stop("r2 cannot be used as an early stopping_metric yet. Check this JIRA https://github.com/h2oai/h2o-3/issues/12248 for progress.")
}
if (algo=="pca" && is.null(params$k)) # make sure to set k=1 for default for pca
params$k=1
job <- .h2o.startModelJob(algo, params, h2oRestApiVersion)
.h2o.getFutureModel(job, verbose = verbose)
}
.h2o.startModelJob <- function(algo, params, h2oRestApiVersion) {
.key.validate(params$key)
#---------- Params ----------#
param_values <- .h2o.makeModelParams(algo, params, h2oRestApiVersion)
#---------- Build! ----------#
res <- .h2o.__remoteSend(method = "POST", .h2o.__MODEL_BUILDERS(algo), .params = param_values, h2oRestApiVersion = h2oRestApiVersion)
.h2o.processResponseWarnings(res)
#---------- Output ----------#
job_key <- res$job$key$name
dest_key <- res$job$dest$name
new("H2OModelFuture",job_key=job_key, model_id=dest_key)
}
.h2o.makeModelParams <- function(algo, params, h2oRestApiVersion) {
#---------- Force evaluate temporary ASTs ----------#
ALL_PARAMS <- .h2o.__remoteSend(method = "GET", h2oRestApiVersion = h2oRestApiVersion, .h2o.__MODEL_BUILDERS(algo))$model_builders[[algo]]$parameters
#---------- Check user parameter types ----------#
param_values <- .h2o.checkAndUnifyModelParameters(algo = algo, allParams = ALL_PARAMS, params = params)
#---------- Validate parameters ----------#
#.h2o.validateModelParameters(algo, param_values, h2oRestApiVersion)
return(param_values)
}
.h2o.processResponseWarnings <- function(res) {
if(length(res$messages) != 0L){
warn <- lapply(res$messages, function(y) {
if(is.list(y) && y$message_type == "WARN" )
paste0(y$message, ".\n")
else ""
})
if(any(nzchar(warn))) warning(warn)
}
}
.h2o.startSegmentModelsJob <- function(algo, segment_params, params, h2oRestApiVersion) {
#---------- Params ----------#
param_values <- .h2o.makeModelParams(algo, params, h2oRestApiVersion)
param_values$segment_models_id <- segment_params$segment_models_id
param_values$segment_columns <- .collapse.char(segment_params$segment_columns)
param_values$parallelism <- segment_params$parallelism
#---------- Build! ----------#
job <- .h2o.__remoteSend(method = "POST", .h2o.__SEGMENT_MODELS_BUILDERS(algo), .params = param_values, h2oRestApiVersion = h2oRestApiVersion)
job_key <- job$key$name
dest_key <- job$dest$name
new("H2OSegmentModelsFuture",job_key=job_key, segment_models_id=dest_key)
}
.h2o.segmentModelsJob <- function(algo, segment_params, params, h2oRestApiVersion) {
.key.validate(segment_params$segment_models_id)
sm <- .h2o.startSegmentModelsJob(algo, segment_params, params, h2oRestApiVersion)
.h2o.getFutureSegmentModels(sm)
}
.h2o.getFutureSegmentModels <- function(object) {
.h2o.__waitOnJob(object@job_key)
h2o.get_segment_models(object@segment_models_id)
}
#
# Validate given parameters against algorithm parameters validation
# REST end-point. Stop execution in case of validation error.
#
.h2o.validateModelParameters <- function(algo, params, h2oRestApiVersion = .h2o.__REST_API_VERSION) {
validation <- .h2o.__remoteSend(method = "POST", paste0(.h2o.__MODEL_BUILDERS(algo), "/parameters"), .params = params, h2oRestApiVersion = h2oRestApiVersion)
if(length(validation$messages) != 0L) {
error <- lapply(validation$messages, function(x) {
if( x$message_type == "ERRR" )
paste0(x$message, ".\n")
else ""
})
if(any(nzchar(error))) stop(error)
warn <- lapply(validation$messages, function(i) {
if( i$message_type == "WARN" )
paste0(i$message, ".\n")
else ""
})
if(any(nzchar(warn))) warning(warn)
}
}
.h2o.createModel <- function(algo, params, h2oRestApiVersion = .h2o.__REST_API_VERSION) {
.h2o.getFutureModel(.h2o.startModelJob(algo, params, h2oRestApiVersion))
}
.h2o.pollModelUpdates <- function(job) {
cat(paste0("\nScoring History for Model ",job$dest$name, " at ", Sys.time(),"\n"))
print(paste0("Model Build is ", job$progress*100, "% done..."))
if(!is.null(job$progress_msg)){
# print(tail(h2o.getModel(job$dest$name)@model$scoring_history))
}else{
print("Scoring history is not available yet...") #Catch 404 with scoring history. Can occur when nfolds >=2
}
}
.h2o.getFutureModel <- function(object, verbose=FALSE) {
.h2o.__waitOnJob(object@job_key, pollUpdates=ifelse(verbose, .h2o.pollModelUpdates, as.null))
h2o.getModel(object@model_id)
}
.h2o.prepareModelParameters <- function(algo, params, is_supervised) {
if (!is.null(params$training_frame))
params$training_frame <- chk.H2OFrame(params$training_frame)
if (!is.null(params$validation_frame))
params$validation_frame <- chk.H2OFrame(params$validation_frame)
# Check if specified model request is for supervised algo
isSupervised <- if (!is.null(is_supervised)) is_supervised else .isSupervised(algo, params)
if (isSupervised) {
if (!is.null(params$x)) { x <- params$x; params$x <- NULL }
if (!is.null(params$y)) { y <- params$y; params$y <- NULL }
args <- .verify_dataxy(params$training_frame, x, y)
if( !is.null(params$offset_column) && !is.null(params$offset_column)) args$x_ignore <- args$x_ignore[!( params$offset_column == args$x_ignore )]
if( !is.null(params$weights_column) && !is.null(params$weights_column)) args$x_ignore <- args$x_ignore[!( params$weights_column == args$x_ignore )]
if( !is.null(params$fold_column) && !is.null(params$fold_column)) args$x_ignore <- args$x_ignore[!( params$fold_column == args$x_ignore )]
params$ignored_columns <- args$x_ignore
params$response_column <- args$y
} else {
if (!is.null(params$x)) {
x <- params$x
params$x <- NULL
args <- .verify_datacols(params$training_frame, x)
params$ignored_columns <- args$cols_ignore
}
}
# Note: Magic copied from start .h2o.startModelJob
params <- lapply(params, function(x) { if(is.integer(x)) x <- as.numeric(x); x })
params
}
.h2o.getModelParameters <- function(algo, h2oRestApiVersion = .h2o.__REST_API_VERSION) {
.h2o.__remoteSend(method = "GET", .h2o.__MODEL_BUILDERS(algo), h2oRestApiVersion = h2oRestApiVersion)$model_builders[[algo]]$parameters
}
.h2o.checkAndUnifyModelParameters <- function(algo, allParams, params, hyper_params = list()) {
addGamCol <- FALSE
if (algo == "gam") {# gam_column is specified in subspace and need to fake something here
if (is.null(params$gam_columns) && !(is.null(hyper_params$subspaces)) && !(is.null(hyper_params$subspaces[[1]]$gam_columns))) {
addGamCol <- TRUE
params$gam_columns = list("C1") # set default gam_columns
}
}
# First verify all parameters
error <- lapply(allParams, function(i) {
e <- ""
name <- i$name
# R treats integer as not numeric
if(is.integer(params[[name]])){
params[[name]] <- as.numeric(params[[name]])
}
if (i$required && !((name %in% names(params)) || (name %in% names(hyper_params)))) {
e <- paste0("argument \"", name, "\" is missing, with no default\n")
} else if (name %in% names(params)) {
e <- .h2o.checkParam(i, params[[name]])
if (!nzchar(e)) {
params[[name]] <<- .h2o.transformParam(i, params[[name]])
}
}
e
})
if (addGamCol)
params$gam_columns <- NULL
if(any(nzchar(error)))
stop(error)
#---------- Create parameter list to pass ----------#
param_values <- lapply(params, function(i) {
if(is.H2OFrame(i)) h2o.getId(i)
else i
})
param_values
}
# Long precision
.is.int64 <- function(v) {
number <- suppressWarnings(as.numeric(v))
if(is.na(number)) FALSE
else number > -2^63 & number < 2^63 & (floor(number)==ceiling(number))
}
# Precise int in double presision
.is.int53 <- function(v) {
number <- suppressWarnings(as.numeric(v))
if(is.na(number)) FALSE
else number > -2^53 & number < 2^53 & (floor(number)==ceiling(number))
}
# Check definition of given parameters in given list of parameters
# Returns error message or empty string
# Note: this function has no side-effects!
.h2o.checkParam <- function(paramDef, paramValue) {
e <- ""
# Fetch mapping for given Java to R types
mapping <- .type.map[paramDef$type,]
type <- mapping[1L, 1L]
scalar <- mapping[1L, 2L]
name <- paramDef$name
if (is.na(type))
stop("Cannot find type ", paramDef$type, " in .type.map")
if (scalar) { # scalar == TRUE
if (type == "H2OModel")
type <- "character"
if (name == "seed") {
if(is.character(paramValue) && !.is.int64(paramValue))
e <- paste0("\"seed\" must be of type long or string long, but got a string which cannot be converted to long.\n")
else if(is.numeric(paramValue)){
if(!.is.int64(paramValue)){
e <- paste0("\"seed\" must be of type long or string long, but got a number which cannot be converted to long.\n")
} else if(!.is.int53(paramValue)) {
warning("R can handle only 53-bit integer without loss.
If you need to use a less/larger number than the integer, pass seed parameter as the string number. Otherwise, the seed could be inconsistent.
(For example, if you need to use autogenerated seed like -8664354335142703762 from H2O server.)")
}
}
} else {
if (!inherits(paramValue, type)) {
e <- paste0(e, "\"", name , "\" must be of type ", type, ", but got ", class(paramValue), ".\n")
} else if ((length(paramDef$values) > 1L) && (is.null(paramValue) || !(tolower(paramValue) %in% tolower(paramDef$values)))) {
e <- paste0(e, "\"", name,"\" must be in")
for (fact in paramDef$values)
e <- paste0(e, " \"", fact, "\",")
e <- paste(e, "but got", paramValue)
}
}
} else { # scalar == FALSE
if (!inherits(paramValue, type))
e <- paste0("vector of ", name, " must be of type ", type, ", but got ", class(paramValue), ".\n")
}
e
}
.h2o.transformParam <- function(paramDef, paramValue, collapseArrays = TRUE) {
# Fetch mapping for given Java to R types
mapping <- .type.map[paramDef$type,]
type <- mapping[1L, 1L]
scalar <- mapping[1L, 2L]
name <- paramDef$name
if (scalar) { # scalar == TRUE
if (inherits(paramValue, 'numeric') && paramValue == Inf) {
paramValue <- "Infinity"
} else if (inherits(paramValue, 'numeric') && paramValue == -Inf) {
paramValue <- "-Infinity"
}
} else { # scalar == FALSE
if (inherits(paramValue, 'numeric')) {
k = which(paramValue == Inf | paramValue == -Inf)
if (length(k) > 0)
for (n in k)
if (paramValue[n] == Inf)
paramValue[n] <- "Infinity"
else
paramValue[n] <- "-Infinity"
}
if (collapseArrays) {
if(any(sapply(paramValue, function(x) !is.null(x) && is.H2OFrame(x))))
paramValue <- lapply( paramValue, function(x) {
if (is.null(x)) NULL
else if (all(is.na(x))) NA
else paste0('"',h2o.getId(x),'"')
})
if (paramDef$type == "string[][]"){
paramValue <- .collapse.list.of.list.string(paramValue)
} else if (type == "character")
paramValue <- .collapse.char(paramValue)
else if (paramDef$type == "StringPair[]")
paramValue <- .collapse(sapply(paramValue, .collapse.tuple.string))
else if (paramDef$type == "KeyValue[]") {
f <- function(i) { .collapse.tuple.key_value(paramValue[i]) }
paramValue <- .collapse(sapply(seq(length(paramValue)), f))
} else
paramValue <- .collapse(paramValue)
}
}
if( is.H2OFrame(paramValue) )
paramValue <- h2o.getId(paramValue)
paramValue
}
.escape.string <- function(xi) { paste0("\"", xi, "\"") }
.collapse.tuple.string <- function(x) {
.collapse.tuple(x, .escape.string)
}
.collapse.list.of.list.string <- function(x){
parts <- c()
for (i in x) {
parts <- c(parts, paste0("[", paste0(i, collapse = ","), "]"))
}
paste0("[", paste0(parts, collapse = ","), "]")
}
.collapse.tuple.key_value <- function(x) {
.collapse.tuple(list(
key = .escape.string(names(x)),
value = x[[1]]
), identity)
}
.collapse.tuple <- function(x, escape) {
names <- names(x)
if (is.null(names))
names <- letters[1:length(x)]
r <- c()
for (i in 1:length(x)) {
s <- paste0(names[i], ": ", escape(x[i]))
r <- c(r, s)
}
paste0("{", paste0(r, collapse = ","), "}")
}
# Validate a given set of hyper parameters
# against algorithm definition.
# Transform all parameters in the same way as normal algorithm
# would do.
.h2o.checkAndUnifyHyperParameters <- function(algo, allParams, hyper_params, do_hyper_params_check) {
errors <- lapply(allParams, function(paramDef) {
e <- ""
name <- paramDef$name
hyper_names <- names(hyper_params)
# First reject all non-gridable hyper parameters
if (!paramDef$gridable && (name %in% hyper_names)) {
e <- paste0("argument \"", name, "\" is not gridable\n")
} else if (name %in% hyper_names) { # Check all specified hyper parameters
# Hyper values for `name` parameter
hyper_vals <- hyper_params[[name]]
# Collect all possible verification errors
if (do_hyper_params_check) {
he <- lapply(hyper_vals, function(hv) {
# Transform all integer values to numeric
hv <- if (is.integer(hv)) as.numeric(hv) else hv
.h2o.checkParam(paramDef, hv)
})
e <- paste(he, collapse='')
}
# If there is no error then transform hyper values
if (!nzchar(e)) {
is_scalar <- .type.map[paramDef$type,][1L, 2L]
transf_fce <- function(hv) {
# R does not treat integers as numeric
if (is.integer(hv)) {
hv <- as.numeric(hv)
}
mapping <- .type.map[paramDef$type,]
type <- mapping[1L, 1L]
# Note: we apply this transformatio also for types
# reported by the backend as scalar because of PUBDEV-1955
if (is.list(hv)) {
hv <- as.vector(hv, mode=type)
}
# Force evaluation of frames and fetch frame_id as
# a side effect
if (is.H2OFrame(hv) )
hv <- h2o.getId(hv)
.h2o.transformParam(paramDef, hv, collapseArrays = FALSE)
}
transf_hyper_vals <- if (is_scalar) sapply(hyper_vals,transf_fce) else lapply(hyper_vals, transf_fce)
hyper_params[[name]] <<- transf_hyper_vals
}
}
e
})
if(any(nzchar(errors)))
stop(errors)
hyper_params
}
#' Predict on an H2O Model
#'
#' Obtains predictions from various fitted H2O model objects.
#'
#' This method dispatches on the type of H2O model to select the correct
#' prediction/scoring algorithm.
#' The order of the rows in the results is the same as the order in which the
#' data was loaded, even if some rows fail (for example, due to missing
#' values or unseen factor levels).
#'
#' @param object a fitted \linkS4class{H2OModel} object for which prediction is
#' desired
#' @param newdata An H2OFrame object in which to look for
#' variables with which to predict.
#' @param ... additional arguments to pass on.
#' @return Returns an H2OFrame object with probabilites and
#' default predictions.
#' @seealso \code{\link{h2o.deeplearning}}, \code{\link{h2o.gbm}},
#' \code{\link{h2o.glm}}, \code{\link{h2o.randomForest}} for model
#' generation in h2o.
#' @examples
#' \dontrun{
#' library(h2o)
#' h2o.init()
#'
#' f <- "https://s3.amazonaws.com/h2o-public-test-data/smalldata/glm_test/insurance.csv"
#' insurance <- h2o.importFile(f)
#' predictors <- colnames(insurance)[1:4]
#' response <- "Claims"
#' insurance['Group'] <- as.factor(insurance['Group'])
#' insurance['Age'] <- as.factor(insurance['Age'])
#' splits <- h2o.splitFrame(data = insurance, ratios = 0.8, seed = 1234)
#' train <- splits[[1]]
#' valid <- splits[[2]]
#' insurance_gbm <- h2o.gbm(x = predictors, y = response,
#' training_frame = train,
#' validation_frame = valid,
#' distribution = "huber",
#' huber_alpha = 0.9, seed = 1234)
#' h2o.predict(insurance_gbm, newdata = insurance)
#' }
#' @export
predict.H2OModel <- function(object, newdata, ...) {
h2o.predict.H2OModel(object, newdata, ...)
}
#' Predict on an H2O Model
#'
#' @param object a fitted model object for which prediction is desired.
#' @param newdata An H2OFrame object in which to look for
#' variables with which to predict.
#' @param ... additional arguments to pass on.
#' @return Returns an H2OFrame object with probabilites and
#' default predictions.
#' @export
h2o.predict <- function(object, newdata, ...){
UseMethod("h2o.predict", object)
}
#' Use H2O Transformation model and apply the underlying transformation
#'
#' @param model A trained model representing the transformation strategy
#' @param ... Transformation model-specific parameters
#' @return Returns an H2OFrame object with data transformed.
#' @export
setGeneric("h2o.transform", function(model, ...) {
if(!is(model, "H2OModel")) {
stop(paste("Argument 'model' must be an H2O Model. Received:", class(model)))
}
standardGeneric("h2o.transform")
})
#' Applies target encoding to a given dataset
#'
#' @param model A trained model representing the transformation strategy
#' @param data An H2OFrame with data to be transformed
#' @param blending Use blending during the transformation. Respects model settings when not set.
#' @param inflection_point Blending parameter. Only effective when blending is enabled.
#' By default, model settings are respected, if not overridden by this setting.
#' @param smoothing Blending parameter. Only effective when blending is enabled.
#' By default, model settings are respected, if not overridden by this setting.
#' @param noise An amount of random noise added to the encoding, this helps prevent overfitting.
#' By default, model settings are respected, if not overridden by this setting.
#' @param as_training Must be set to True when encoding the training frame. Defaults to False.
#' @param ... Mainly used for backwards compatibility, to allow deprecated parameters.
#' @return Returns an H2OFrame object with data transformed.
#' @export
setMethod("h2o.transform", signature("H2OTargetEncoderModel"), function(model, data,
blending = NULL,
inflection_point = -1,
smoothing = -1,
noise = NULL,
as_training = FALSE,
...) {
varargs <- list(...)
for (arg in names(varargs)) {
if (arg %in% c('data_leakage_handling', 'seed')) {
warning(paste0("argument '", arg, "' is deprecated and will be ignored; please define it instead on model creation using `h2o.targetencoder`."))
argval <- varargs[[arg]]
if (arg == 'data_leakage_handling' && argval != "None") {
warning(paste0("Deprecated `data_leakage_handling=",argval,"` is replaced by `as_training=True`. ",
"Please update your code."))
as_training <- TRUE
}
} else if (arg == 'use_blending') {
warning("argument 'use_blending' is deprecated; please use 'blending' instead.")
if (missing(blending)) blending <- varargs$use_blending else warning("ignoring 'use_blending' as 'blending' was also provided.")
} else {
stop(paste("unused argument", arg, "=", varargs[[arg]]))
}
}
params <- list()
params$model <- model@model_id
params$frame <- h2o.getId(data)
if (is.null(blending)){
params$blending <- model@allparameters$blending
} else {
params$blending <- blending
}
if (params$blending) {
params$inflection_point <- inflection_point
params$smoothing <- smoothing
}
if (!is.null(noise)){
params$noise <- noise
}
params$as_training <- as_training
res <- .h2o.__remoteSend(
"TargetEncoderTransform",
method = "GET",
h2oRestApiVersion = 3,.params = params
)
h2o.getFrame(res$name)
})
#'
#' Transform words (or sequences of words) to vectors using a word2vec model.
#'
#' @param model A word2vec model.
#' @param words An H2OFrame made of a single column containing source words.
#' @param aggregate_method Specifies how to aggregate sequences of words. If method is `NONE`
#' then no aggregation is performed and each input word is mapped to a single word-vector.
#' If method is 'AVERAGE' then input is treated as sequences of words delimited by NA.
#' Each word of a sequences is internally mapped to a vector and vectors belonging to
#' the same sentence are averaged and returned in the result.
#' @examples
#' \dontrun{
#' h2o.init()
#'
#' # Build a simple word2vec model
#' data <- as.character(as.h2o(c("a", "b", "a")))
#' w2v_model <- h2o.word2vec(data, sent_sample_rate = 0, min_word_freq = 0, epochs = 1, vec_size = 2)
#'
#' # Transform words to vectors without aggregation
#' sentences <- as.character(as.h2o(c("b", "c", "a", NA, "b")))
#' h2o.transform(w2v_model, sentences) # -> 5 rows total, 2 rows NA ("c" is not in the vocabulary)
#'
#' # Transform words to vectors and return average vector for each sentence
#' h2o.transform(w2v_model, sentences, aggregate_method = "AVERAGE") # -> 2 rows
#' }
#' @export
setMethod("h2o.transform", signature("H2OWordEmbeddingModel"), function(model, words, aggregate_method = c("NONE", "AVERAGE")) {
if (!is(model, "H2OModel")) stop(paste("The argument 'model' must be a word2vec model. Received:", class(model)))
if (missing(words)) stop("`words` must be specified")
if (!is.H2OFrame(words)) stop("`words` must be an H2OFrame")
if (ncol(words) != 1) stop("`words` frame must contain a single string column")
if (length(aggregate_method) > 1)
aggregate_method <- aggregate_method[1]
res <- .h2o.__remoteSend(method="GET", "Word2VecTransform", model = model@model_id,
words_frame = h2o.getId(words), aggregate_method = aggregate_method)
key <- res$vectors_frame$name
h2o.getFrame(key)
})
#'
#' @rdname predict.H2OModel
#' @export
h2o.predict.H2OModel <- function(object, newdata, ...) {
if (missing(newdata)) {
stop("predictions with a missing `newdata` argument is not implemented yet")
}
# Send keys to create predictions
url <- paste0('Predictions/models/', object@model_id, '/frames/', h2o.getId(newdata))
res <- .h2o.__remoteSend(url, method = "POST", h2oRestApiVersion = 4)
job_key <- res$key$name
dest_key <- res$dest$name
.h2o.__waitOnJob(job_key)
h2o.getFrame(dest_key)
}
#' Predict the Leaf Node Assignment on an H2O Model
#'
#' Obtains leaf node assignment from fitted H2O model objects.
#'
#' For every row in the test set, return the leaf placements of the row in all the trees in the model.
#' Placements can be represented either by paths to the leaf nodes from the tree root or by H2O's internal identifiers.
#' The order of the rows in the results is the same as the order in which the
#' data was loaded
#'
#' @param object a fitted \linkS4class{H2OModel} object for which prediction is
#' desired
#' @param newdata An H2OFrame object in which to look for
#' variables with which to predict.
#' @param type choice of either "Path" when tree paths are to be returned (default); or "Node_ID" when the output
# should be the leaf node IDs.
#' @param ... additional arguments to pass on.
#' @return Returns an H2OFrame object with categorical leaf assignment identifiers for
#' each tree in the model.
#' @seealso \code{\link{h2o.gbm}} and \code{\link{h2o.randomForest}} for model
#' generation in h2o.
#' @examples
#' \dontrun{
#' library(h2o)
#' h2o.init()
#' prostate_path <- system.file("extdata", "prostate.csv", package = "h2o")
#' prostate <- h2o.uploadFile(path = prostate_path)
#' prostate$CAPSULE <- as.factor(prostate$CAPSULE)
#' prostate_gbm <- h2o.gbm(3:9, "CAPSULE", prostate)
#' h2o.predict(prostate_gbm, prostate)
#' h2o.predict_leaf_node_assignment(prostate_gbm, prostate)
#' }
#' @export
predict_leaf_node_assignment.H2OModel <- function(object, newdata, type = c("Path", "Node_ID"), ...) {
if (missing(newdata)) {
stop("predictions with a missing `newdata` argument is not implemented yet")
}
params <- list(leaf_node_assignment = TRUE)
if (!missing(type)) {
if (!(type %in% c("Path", "Node_ID"))) {
stop("type must be one of: Path, Node_ID")
}
params$leaf_node_assignment_type <- type
}
url <- paste0('Predictions/models/', object@model_id, '/frames/', h2o.getId(newdata))
res <- .h2o.__remoteSend(url, method = "POST", .params = params)
res <- res$predictions_frame
h2o.getFrame(res$name)
}
#' @rdname predict_leaf_node_assignment.H2OModel
#' @export
h2o.predict_leaf_node_assignment <- predict_leaf_node_assignment.H2OModel
#' Use GRLM to transform a frame.
#'
#' @param model H2O GRLM model
#' @param fr H2OFrame
#' @return Returns a transformed frame
#'
#' @examples
#' \dontrun{
#' library(h2o)
#' h2o.init()
#'
#' # Import the USArrests dataset into H2O:
#' arrests <- h2o.importFile(
#' "https://s3.amazonaws.com/h2o-public-test-data/smalldata/pca_test/USArrests.csv"
#' )
#'
#' # Split the dataset into a train and valid set:
#' arrests_splits <- h2o.splitFrame(data = arrests, ratios = 0.8, seed = 1234)
#' train <- arrests_splits[[1]]
#' valid <- arrests_splits[[2]]
#'
#' # Build and train the model:
#' glrm_model = h2o.glrm(training_frame = train,
#' k = 4,
#' loss = "Quadratic",
#' gamma_x = 0.5,
#' gamma_y = 0.5,
#' max_iterations = 700,
#' recover_svd = TRUE,
#' init = "SVD",
#' transform = "STANDARDIZE")
#'
#' # Eval performance:
#' arrests_perf <- h2o.performance(glrm_model)
#'
#' # Generate predictions on a validation set (if necessary):
#' arrests_pred <- h2o.predict(glrm_model, newdata = valid)
#'
#' # Transform the data using the dataset "valid" to retrieve the new coefficients:
#' glrm_transform <- h2o.transform_frame(glrm_model, valid)
#'}
#' @export
h2o.transform_frame <- function(model, fr) {
if (!is(model, "H2OModel") || (is(model, "H2OModel") && model@algorithm != "glrm")) stop("h2o.transform_frame can only be applied to GLRM H2OModel instance.")
return(.newExpr("transform", model@model_id, h2o.getId(fr)))
}
#' Retrieve the results to view the best predictor subsets.
#'
#' @param model H2OModelSelection object
#' @return Returns an H2OFrame object
#'
#' @examples
#' \dontrun{
#' library(h2o)
#' h2o.init()
#'
#' # Import the prostate dataset:
#' prostate <- h2o.importFile(
#' "http://s3.amazonaws.com/h2o-public-test-data/smalldata/logreg/prostate.csv"
#' )
#'
#' # Set the predictors & response:
#' predictors <- c("AGE", "RACE", "CAPSULE", "DCAPS", "PSA", "VOL", "DPROS")
#' response <- "GLEASON"
#'
#' # Build & train the model:
#' allsubsetsModel <- h2o.modelSelection(x = predictors,
#' y = response,
#' training_frame = prostate,
#' seed = 12345,
#' max_predictor_number = 7,
#' mode = "allsubsets")
#'
#' # Retrieve the results (H2OFrame containing best model_ids, best_r2_value, & predictor subsets):
#' results <- h2o.result(allsubsetsModel)
#' print(results)
#'
#' # Retrieve the list of coefficients:
#' coeff <- h2o.coef(allsubsetsModel)
#' print(coeff)
#'
#' # Retrieve the list of coefficients for a subset size of 3:
#' coeff3 <- h2o.coef(allsubsetsModel, 3)
#' print(coeff3)
#'
#' # Retrieve the list of standardized coefficients:
#' coeff_norm <- h2o.coef_norm(allsubsetsModel)
#' print(coeff_norm)
#'
#' # Retrieve the list of standardized coefficients for a subset size of 3:
#' coeff_norm3 <- h2o.coef_norm(allsubsetsModel)
#' print(coeff_norm3)
#'
#' # Check the variables that were added during this process:
#' h2o.get_predictors_added_per_step(allsubsetsModel)
#'
#' # To find out which variables get removed, build a new model with ``mode = "backward``
#' # using the above training information:
#' bwModel <- h2o.modelSelection(x = predictors,
#' y = response,
#' training_frame = prostate,
#' seed = 12345,
#' max_predictor_number = 7,
#' mode = "backward")
#' h2o.get_predictors_removed_per_step(bwModel)
#'
#' # To build the fastest model with ModelSelection, use ``mode = "maxrsweep"``:
#' sweepModel <- h2o.modelSelection(x = predictors,
#' y = response,
#' training_frame = prostate,
#' mode = "maxrsweep",
#' build_glm_model = FALSE,
#' max_predictor_number = 3,
#' seed = 12345)
#'
#' # Retrieve the results to view the best predictor subsets:
#' h2o.result(sweepModel)
#' }
#'
#' @export
h2o.result <- function(model) {
if (!is(model, "H2OModel")) stop("h2o.result can only be applied to H2OModel instances with constant results")
return(.newExpr("result", model@model_id))
}
h2o.crossValidate <- function(model, nfolds, model.type = c("gbm", "glm", "deeplearning"), params, strategy = c("mod1", "random")) {
output <- data.frame()
if( nfolds < 2 ) stop("`nfolds` must be greater than or equal to 2")
if( missing(model) & missing(model.type) ) stop("must declare `model` or `model.type`")
else if( missing(model) )
{
if(model.type == "gbm") model.type = "h2o.gbm"
else if(model.type == "glm") model.type = "h2o.glm"
else if(model.type == "deeplearning") model.type = "h2o.deeplearning"
model <- do.call(model.type, c(params))
}
output[1, "fold_num"] <- -1
output[1, "model_key"] <- model@model_id
# output[1, "model"] <- model@model$mse_valid
data <- params$training_frame
data <- eval(data)
data.len <- nrow(data)
# nfold_vec <- h2o.sample(fr, 1:nfolds)
nfold_vec <- sample(rep(1:nfolds, length.out = data.len), data.len)
fnum_id <- as.h2o(nfold_vec)
fnum_id <- h2o.cbind(fnum_id, data)
xval <- lapply(1:nfolds, function(i) {
params$training_frame <- data[fnum_id[,1] != i, ]
params$validation_frame <- data[fnum_id[,1] == i, ]
fold <- do.call(model.type, c(params))
output[(i+1), "fold_num"] <<- i - 1
output[(i+1), "model_key"] <<- fold@model_id
# output[(i+1), "cv_err"] <<- mean(as.vector(fold@model$mse_valid))
fold
})
model
}
#' Predict class probabilities at each stage of an H2O Model
#'
#' The output structure is analogous to the output of \link{h2o.predict_leaf_node_assignment}. For each tree t and
#' class c there will be a column Tt.Cc (eg. T3.C1 for tree 3 and class 1). The value will be the corresponding
#' predicted probability of this class by combining the raw contributions of trees T1.Cc,..,TtCc. Binomial models build
#' the trees just for the first class and values in columns Tx.C1 thus correspond to the the probability p0.
#'
#' @param object a fitted \linkS4class{H2OModel} object for which prediction is
#' desired
#' @param newdata An H2OFrame object in which to look for
#' variables with which to predict.
#' @param ... additional arguments to pass on.
#' @return Returns an H2OFrame object with predicted probability for each tree in the model.
#' @seealso \code{\link{h2o.gbm}} and \code{\link{h2o.randomForest}} for model
#' generation in h2o.
#' @examples
#' \dontrun{
#' library(h2o)
#' h2o.init()
#' prostate_path <- system.file("extdata", "prostate.csv", package = "h2o")
#' prostate <- h2o.uploadFile(path = prostate_path)
#' prostate$CAPSULE <- as.factor(prostate$CAPSULE)
#' prostate_gbm <- h2o.gbm(3:9, "CAPSULE", prostate)
#' h2o.predict(prostate_gbm, prostate)
#' h2o.staged_predict_proba(prostate_gbm, prostate)
#' }
#' @export
staged_predict_proba.H2OModel <- function(object, newdata, ...) {
if (missing(newdata)) {
stop("predictions with a missing `newdata` argument is not implemented yet")
}
url <- paste0('Predictions/models/', object@model_id, '/frames/', h2o.getId(newdata))
res <- .h2o.__remoteSend(url, method = "POST", predict_staged_proba=TRUE)
res <- res$predictions_frame
h2o.getFrame(res$name)
}
#' @rdname staged_predict_proba.H2OModel
#' @export
h2o.staged_predict_proba <- staged_predict_proba.H2OModel
#' Predict feature contributions - SHAP values on an H2O Model (only DRF, GBM, XGBoost models and equivalent imported MOJOs).
#'
#' Default implemntation return H2OFrame shape (#rows, #features + 1) - there is a feature contribution column for each input
#' feature, the last column is the model bias (same value for each row). The sum of the feature contributions
#' and the bias term is equal to the raw prediction of the model. Raw prediction of tree-based model is the sum
#' of the predictions of the individual trees before the inverse link function is applied to get the actual
#' prediction. For Gaussian distribution the sum of the contributions is equal to the model prediction.
#'
#' Note: Multinomial classification models are currently not supported.
#'
#' @param object a fitted \linkS4class{H2OModel} object for which prediction is
#' desired
#' @param newdata An H2OFrame object in which to look for
#' variables with which to predict.
#' @param output_format Specify how to output feature contributions in XGBoost - XGBoost by default outputs
#' contributions for 1-hot encoded features, specifying a compact output format will produce
#' a per-feature contribution. Defaults to original.
#' @param top_n Return only #top_n highest contributions + bias
#' If top_n<0 then sort all SHAP values in descending order
#' If top_n<0 && bottom_n<0 then sort all SHAP values in descending order
#' @param bottom_n Return only #bottom_n lowest contributions + bias
#' If top_n and bottom_n are defined together then return array of #top_n + #bottom_n + bias
#' If bottom_n<0 then sort all SHAP values in ascending order
#' If top_n<0 && bottom_n<0 then sort all SHAP values in descending order
#' @param compare_abs True to compare absolute values of contributions
#' @param background_frame Optional frame, that is used as the source of baselines for
#' the baseline SHAP (when output_per_reference == TRUE) or for
#' the marginal SHAP (when output_per_reference == FALSE).
#' @param output_space If TRUE, linearly scale the contributions so that they sum up to the prediction.
#' NOTE: This will result only in approximate SHAP values even if the model supports exact SHAP calculation.
#' NOTE: This will not have any effect if the estimator doesn't use a link function.
#' @param output_per_reference If TRUE, return baseline SHAP, i.e., contribution for each data point for each reference from the background_frame.
#' If FALSE, return TreeSHAP if no background_frame is provided, or marginal SHAP if background frame is provided.
#' Can be used only with background_frame.
#' @param ... additional arguments to pass on.
#' @return Returns an H2OFrame contain feature contributions for each input row.