lgb.Booster.R 29.8 KB
Newer Older
James Lamb's avatar
James Lamb committed
1
2
#' @importFrom R6 R6Class
Booster <- R6::R6Class(
3
  classname = "lgb.Booster",
4
  cloneable = FALSE,
Guolin Ke's avatar
Guolin Ke committed
5
  public = list(
6

7
    best_iter = -1L,
8
    best_score = NA_real_,
Guolin Ke's avatar
Guolin Ke committed
9
    record_evals = list(),
10

11
12
    # Finalize will free up the handles
    finalize = function() {
13

14
      # Check the need for freeing handle
15
      if (!lgb.is.null.handle(private$handle)) {
16

17
        # Freeing up handle
18
        lgb.call("LGBM_BoosterFree_R", ret = NULL, private$handle)
Guolin Ke's avatar
Guolin Ke committed
19
        private$handle <- NULL
20

Guolin Ke's avatar
Guolin Ke committed
21
      }
22

23
    },
24

25
26
    # Initialize will create a starter booster
    initialize = function(params = list(),
Guolin Ke's avatar
Guolin Ke committed
27
28
                          train_set = NULL,
                          modelfile = NULL,
29
                          model_str = NULL,
Guolin Ke's avatar
Guolin Ke committed
30
                          ...) {
31

32
33
      # Create parameters and handle
      params <- append(params, list(...))
Guolin Ke's avatar
Guolin Ke committed
34
      handle <- lgb.null.handle()
35

36
37
      # Attempts to create a handle for the dataset
      try({
38

39
40
41
        # Check if training dataset is not null
        if (!is.null(train_set)) {
          # Check if training dataset is lgb.Dataset or not
42
          if (!lgb.check.r6.class(object = train_set, name = "lgb.Dataset")) {
43
44
            stop("lgb.Booster: Can only use lgb.Dataset as training data")
          }
45
46
          train_set_handle <- train_set$.__enclos_env__$private$get_handle()
          params <- modifyList(params, train_set$get_params())
47
          params_str <- lgb.params2str(params = params)
48
          # Store booster handle
49
50
51
          handle <- lgb.call(
            "LGBM_BoosterCreate_R"
            , ret = handle
52
            , train_set_handle
53
54
            , params_str
          )
55

56
57
          # Create private booster information
          private$train_set <- train_set
58
          private$train_set_version <- train_set$.__enclos_env__$private$version
59
          private$num_dataset <- 1L
60
          private$init_predictor <- train_set$.__enclos_env__$private$predictor
61

62
63
          # Check if predictor is existing
          if (!is.null(private$init_predictor)) {
64

65
            # Merge booster
66
67
68
69
70
71
            lgb.call(
              "LGBM_BoosterMerge_R"
              , ret = NULL
              , handle
              , private$init_predictor$.__enclos_env__$private$handle
            )
72

73
          }
74

75
76
          # Check current iteration
          private$is_predicted_cur_iter <- c(private$is_predicted_cur_iter, FALSE)
77

78
        } else if (!is.null(modelfile)) {
79

80
81
82
83
          # Do we have a model file as character?
          if (!is.character(modelfile)) {
            stop("lgb.Booster: Can only use a string as model file path")
          }
84

85
          # Create booster from model
86
          handle <- lgb.call(
87
            fun_name = "LGBM_BoosterCreateFromModelfile_R"
88
89
90
            , ret = handle
            , lgb.c_str(modelfile)
          )
91

92
        } else if (!is.null(model_str)) {
93

94
          # Do we have a model_str as character?
95
96
97
          if (!is.character(model_str)) {
            stop("lgb.Booster: Can only use a string as model_str")
          }
98

99
          # Create booster from model
100
          handle <- lgb.call(
101
            fun_name = "LGBM_BoosterLoadModelFromString_R"
102
103
104
            , ret = handle
            , lgb.c_str(model_str)
          )
105

106
        } else {
107

108
          # Booster non existent
109
110
111
112
          stop(
            "lgb.Booster: Need at least either training dataset, "
            , "model file, or model_str to create booster instance"
          )
113

114
        }
115

116
      })
117

118
      # Check whether the handle was created properly if it was not stopped earlier by a stop call
119
      if (isTRUE(lgb.is.null.handle(handle))) {
120

Guolin Ke's avatar
Guolin Ke committed
121
        stop("lgb.Booster: cannot create Booster handle")
122

Guolin Ke's avatar
Guolin Ke committed
123
      } else {
124

Guolin Ke's avatar
Guolin Ke committed
125
126
127
128
        # Create class
        class(handle) <- "lgb.Booster.handle"
        private$handle <- handle
        private$num_class <- 1L
129
        private$num_class <- lgb.call(
130
          fun_name = "LGBM_BoosterGetNumClasses_R"
131
132
133
          , ret = private$num_class
          , private$handle
        )
134

Guolin Ke's avatar
Guolin Ke committed
135
      }
136

Guolin Ke's avatar
Guolin Ke committed
137
    },
138

139
    # Set training data name
Guolin Ke's avatar
Guolin Ke committed
140
    set_train_data_name = function(name) {
141

142
      # Set name
Guolin Ke's avatar
Guolin Ke committed
143
      private$name_train_set <- name
144
      return(invisible(self))
145

Guolin Ke's avatar
Guolin Ke committed
146
    },
147

148
    # Add validation data
Guolin Ke's avatar
Guolin Ke committed
149
    add_valid = function(data, name) {
150

151
      # Check if data is lgb.Dataset
152
      if (!lgb.check.r6.class(object = data, name = "lgb.Dataset")) {
153
        stop("lgb.Booster.add_valid: Can only use lgb.Dataset as validation data")
Guolin Ke's avatar
Guolin Ke committed
154
      }
155

156
      # Check if predictors are identical
Guolin Ke's avatar
Guolin Ke committed
157
      if (!identical(data$.__enclos_env__$private$predictor, private$init_predictor)) {
158
159
160
161
        stop(
          "lgb.Booster.add_valid: Failed to add validation data; "
          , "you should use the same predictor for these data"
        )
Guolin Ke's avatar
Guolin Ke committed
162
      }
163

164
      # Check if names are character
165
166
      if (!is.character(name)) {
        stop("lgb.Booster.add_valid: Can only use characters as data name")
Guolin Ke's avatar
Guolin Ke committed
167
      }
168

169
      # Add validation data to booster
170
171
172
173
174
175
      lgb.call(
        "LGBM_BoosterAddValidData_R"
        , ret = NULL
        , private$handle
        , data$.__enclos_env__$private$get_handle()
      )
176

177
178
179
      # Store private information
      private$valid_sets <- c(private$valid_sets, data)
      private$name_valid_sets <- c(private$name_valid_sets, name)
180
      private$num_dataset <- private$num_dataset + 1L
181
      private$is_predicted_cur_iter <- c(private$is_predicted_cur_iter, FALSE)
182

183
      return(invisible(self))
184

Guolin Ke's avatar
Guolin Ke committed
185
    },
186

187
    # Reset parameters of booster
Guolin Ke's avatar
Guolin Ke committed
188
    reset_parameter = function(params, ...) {
189

190
191
      # Append parameters
      params <- append(params, list(...))
192
      params_str <- lgb.params2str(params = params)
193

194
      # Reset parameters
195
196
197
198
199
200
      lgb.call(
        "LGBM_BoosterResetParameter_R"
        , ret = NULL
        , private$handle
        , params_str
      )
201

202
      return(invisible(self))
203

Guolin Ke's avatar
Guolin Ke committed
204
    },
205

206
    # Perform boosting update iteration
Guolin Ke's avatar
Guolin Ke committed
207
    update = function(train_set = NULL, fobj = NULL) {
208

209
210
211
212
213
214
      if (is.null(train_set)) {
        if (private$train_set$.__enclos_env__$private$version != private$train_set_version) {
          train_set <- private$train_set
        }
      }

215
      # Check if training set is not null
Guolin Ke's avatar
Guolin Ke committed
216
      if (!is.null(train_set)) {
217

218
        # Check if training set is lgb.Dataset
219
        if (!lgb.check.r6.class(object = train_set, name = "lgb.Dataset")) {
Guolin Ke's avatar
Guolin Ke committed
220
221
          stop("lgb.Booster.update: Only can use lgb.Dataset as training data")
        }
222

223
        # Check if predictors are identical
Guolin Ke's avatar
Guolin Ke committed
224
        if (!identical(train_set$predictor, private$init_predictor)) {
225
          stop("lgb.Booster.update: Change train_set failed, you should use the same predictor for these data")
Guolin Ke's avatar
Guolin Ke committed
226
        }
227

228
        # Reset training data on booster
229
230
231
232
233
234
        lgb.call(
          "LGBM_BoosterResetTrainingData_R"
          , ret = NULL
          , private$handle
          , train_set$.__enclos_env__$private$get_handle()
        )
235

236
        # Store private train set
237
        private$train_set <- train_set
238
        private$train_set_version <- train_set$.__enclos_env__$private$version
239

Guolin Ke's avatar
Guolin Ke committed
240
      }
241

242
      # Check if objective is empty
Guolin Ke's avatar
Guolin Ke committed
243
      if (is.null(fobj)) {
244
245
246
        if (private$set_objective_to_none) {
          stop("lgb.Booster.update: cannot update due to null objective function")
        }
247
        # Boost iteration from known objective
248
        ret <- lgb.call("LGBM_BoosterUpdateOneIter_R", ret = NULL, private$handle)
249

Guolin Ke's avatar
Guolin Ke committed
250
      } else {
251

252
253
254
255
        # Check if objective is function
        if (!is.function(fobj)) {
          stop("lgb.Booster.update: fobj should be a function")
        }
256
        if (!private$set_objective_to_none) {
257
          self$reset_parameter(params = list(objective = "none"))
258
          private$set_objective_to_none <- TRUE
259
        }
260
        # Perform objective calculation
261
        gpair <- fobj(private$inner_predict(1L), private$train_set)
262

263
        # Check for gradient and hessian as list
264
        if (is.null(gpair$grad) || is.null(gpair$hess)) {
265
          stop("lgb.Booster.update: custom objective should
266
267
            return a list with attributes (hess, grad)")
        }
268

269
        # Return custom boosting gradient/hessian
270
        ret <- lgb.call(
271
          fun_name = "LGBM_BoosterUpdateOneIterCustom_R"
272
273
274
275
276
277
          , ret = NULL
          , private$handle
          , gpair$grad
          , gpair$hess
          , length(gpair$grad)
        )
278

Guolin Ke's avatar
Guolin Ke committed
279
      }
280

281
      # Loop through each iteration
282
      for (i in seq_along(private$is_predicted_cur_iter)) {
Guolin Ke's avatar
Guolin Ke committed
283
284
        private$is_predicted_cur_iter[[i]] <- FALSE
      }
285

286
      return(ret)
287

Guolin Ke's avatar
Guolin Ke committed
288
    },
289

290
    # Return one iteration behind
Guolin Ke's avatar
Guolin Ke committed
291
    rollback_one_iter = function() {
292

293
      # Return one iteration behind
294
295
296
297
298
      lgb.call(
        "LGBM_BoosterRollbackOneIter_R"
        , ret = NULL
        , private$handle
      )
299

300
      # Loop through each iteration
301
      for (i in seq_along(private$is_predicted_cur_iter)) {
Guolin Ke's avatar
Guolin Ke committed
302
303
        private$is_predicted_cur_iter[[i]] <- FALSE
      }
304

305
      return(invisible(self))
306

Guolin Ke's avatar
Guolin Ke committed
307
    },
308

309
    # Get current iteration
Guolin Ke's avatar
Guolin Ke committed
310
    current_iter = function() {
311

312
      cur_iter <- 0L
313
      lgb.call(
314
        fun_name = "LGBM_BoosterGetCurrentIteration_R"
315
316
317
        , ret = cur_iter
        , private$handle
      )
318

Guolin Ke's avatar
Guolin Ke committed
319
    },
320

321
    # Get upper bound
322
    upper_bound = function() {
323

324
      upper_bound <- 0.0
325
      lgb.call(
326
        fun_name = "LGBM_BoosterGetUpperBoundValue_R"
327
328
329
330
331
332
333
        , ret = upper_bound
        , private$handle
      )

    },

    # Get lower bound
334
    lower_bound = function() {
335

336
      lower_bound <- 0.0
337
      lgb.call(
338
        fun_name = "LGBM_BoosterGetLowerBoundValue_R"
339
        , ret = lower_bound
340
341
342
343
344
        , private$handle
      )

    },

345
    # Evaluate data on metrics
Guolin Ke's avatar
Guolin Ke committed
346
    eval = function(data, name, feval = NULL) {
347

348
      # Check if dataset is lgb.Dataset
349
      if (!lgb.check.r6.class(object = data, name = "lgb.Dataset")) {
350
        stop("lgb.Booster.eval: Can only use lgb.Dataset to eval")
Guolin Ke's avatar
Guolin Ke committed
351
      }
352

353
      # Check for identical data
354
      data_idx <- 0L
355
      if (identical(data, private$train_set)) {
356
        data_idx <- 1L
357
      } else {
358

359
        # Check for validation data
360
        if (length(private$valid_sets) > 0L) {
361

362
          # Loop through each validation set
363
          for (i in seq_along(private$valid_sets)) {
364

365
            # Check for identical validation data with training data
Guolin Ke's avatar
Guolin Ke committed
366
            if (identical(data, private$valid_sets[[i]])) {
367

368
              # Found identical data, skip
369
              data_idx <- i + 1L
Guolin Ke's avatar
Guolin Ke committed
370
              break
371

Guolin Ke's avatar
Guolin Ke committed
372
            }
373

Guolin Ke's avatar
Guolin Ke committed
374
          }
375

Guolin Ke's avatar
Guolin Ke committed
376
        }
377

Guolin Ke's avatar
Guolin Ke committed
378
      }
379

380
      # Check if evaluation was not done
381
      if (data_idx == 0L) {
382

383
        # Add validation data by name
Guolin Ke's avatar
Guolin Ke committed
384
385
        self$add_valid(data, name)
        data_idx <- private$num_dataset
386

Guolin Ke's avatar
Guolin Ke committed
387
      }
388

389
      # Evaluate data
390
391
392
393
394
      private$inner_eval(
        data_name = name
        , data_idx = data_idx
        , feval = feval
      )
395

Guolin Ke's avatar
Guolin Ke committed
396
    },
397

398
    # Evaluation training data
Guolin Ke's avatar
Guolin Ke committed
399
    eval_train = function(feval = NULL) {
400
      private$inner_eval(private$name_train_set, 1L, feval)
Guolin Ke's avatar
Guolin Ke committed
401
    },
402

403
    # Evaluation validation data
Guolin Ke's avatar
Guolin Ke committed
404
    eval_valid = function(feval = NULL) {
405

406
      # Create ret list
407
      ret <- list()
408

409
      # Check if validation is empty
410
      if (length(private$valid_sets) <= 0L) {
411
412
        return(ret)
      }
413

414
      # Loop through each validation set
415
      for (i in seq_along(private$valid_sets)) {
416
417
        ret <- append(
          x = ret
418
          , values = private$inner_eval(private$name_valid_sets[[i]], i + 1L, feval)
419
        )
Guolin Ke's avatar
Guolin Ke committed
420
      }
421

422
      return(ret)
423

Guolin Ke's avatar
Guolin Ke committed
424
    },
425

426
    # Save model
427
    save_model = function(filename, num_iteration = NULL, feature_importance_type = 0L) {
428

429
430
431
432
      # Check if number of iteration is non existent
      if (is.null(num_iteration)) {
        num_iteration <- self$best_iter
      }
433

434
      # Save booster model
435
      lgb.call(
436
        fun_name = "LGBM_BoosterSaveModel_R"
437
438
439
        , ret = NULL
        , private$handle
        , as.integer(num_iteration)
440
        , as.integer(feature_importance_type)
441
442
        , lgb.c_str(filename)
      )
443

444
      return(invisible(self))
Guolin Ke's avatar
Guolin Ke committed
445
    },
446

447
    # Save model to string
448
    save_model_to_string = function(num_iteration = NULL, feature_importance_type = 0L) {
449

450
451
452
453
      # Check if number of iteration is non existent
      if (is.null(num_iteration)) {
        num_iteration <- self$best_iter
      }
454

455
      # Return model string
456
      return(lgb.call.return.str(
457
        fun_name = "LGBM_BoosterSaveModelToString_R"
458
459
        , private$handle
        , as.integer(num_iteration)
460
        , as.integer(feature_importance_type)
461
      ))
462

463
    },
464

465
    # Dump model in memory
466
    dump_model = function(num_iteration = NULL, feature_importance_type = 0L) {
467

468
469
470
471
      # Check if number of iteration is non existent
      if (is.null(num_iteration)) {
        num_iteration <- self$best_iter
      }
472

473
      lgb.call.return.str(
474
        fun_name = "LGBM_BoosterDumpModel_R"
475
476
        , private$handle
        , as.integer(num_iteration)
477
        , as.integer(feature_importance_type)
478
      )
479

Guolin Ke's avatar
Guolin Ke committed
480
    },
481

482
    # Predict on new data
Guolin Ke's avatar
Guolin Ke committed
483
    predict = function(data,
484
                       start_iteration = NULL,
485
486
487
                       num_iteration = NULL,
                       rawscore = FALSE,
                       predleaf = FALSE,
488
                       predcontrib = FALSE,
489
                       header = FALSE,
490
                       reshape = FALSE, ...) {
491

492
      # Check if number of iteration is non existent
493
494
495
      if (is.null(num_iteration)) {
        num_iteration <- self$best_iter
      }
496
      # Check if start iteration is non existent
497
498
499
      if (is.null(start_iteration)) {
        start_iteration <- 0L
      }
500

501
      # Predict on new data
502
      predictor <- Predictor$new(private$handle, ...)
503
504
505
506
507
508
509
510
511
512
      predictor$predict(
          data = data
          , start_iteration = start_iteration
          , num_iteration = num_iteration
          , rawscore = rawscore
          , predleaf = predleaf
          , predcontrib = predcontrib
          , header = header
          , reshape = reshape
      )
513

514
    },
515

516
517
518
    # Transform into predictor
    to_predictor = function() {
      Predictor$new(private$handle)
Guolin Ke's avatar
Guolin Ke committed
519
    },
520

521
    # Used for save
522
    raw = NA,
523

524
    # Save model to temporary file for in-memory saving
525
    save = function() {
526

527
      # Overwrite model in object
528
      self$raw <- self$save_model_to_string(NULL)
529

530
    }
531

Guolin Ke's avatar
Guolin Ke committed
532
533
  ),
  private = list(
534
535
536
537
538
539
540
    handle = NULL,
    train_set = NULL,
    name_train_set = "training",
    valid_sets = list(),
    name_valid_sets = list(),
    predict_buffer = list(),
    is_predicted_cur_iter = list(),
541
542
    num_class = 1L,
    num_dataset = 0L,
543
544
    init_predictor = NULL,
    eval_names = NULL,
Guolin Ke's avatar
Guolin Ke committed
545
    higher_better_inner_eval = NULL,
546
    set_objective_to_none = FALSE,
547
    train_set_version = 0L,
548
549
    # Predict data
    inner_predict = function(idx) {
550

551
      # Store data name
Guolin Ke's avatar
Guolin Ke committed
552
      data_name <- private$name_train_set
553

554
      # Check for id bigger than 1
555
556
      if (idx > 1L) {
        data_name <- private$name_valid_sets[[idx - 1L]]
557
      }
558

559
      # Check for unknown dataset (over the maximum provided range)
Guolin Ke's avatar
Guolin Ke committed
560
561
562
      if (idx > private$num_dataset) {
        stop("data_idx should not be greater than num_dataset")
      }
563

564
      # Check for prediction buffer
Guolin Ke's avatar
Guolin Ke committed
565
      if (is.null(private$predict_buffer[[data_name]])) {
566

567
        # Store predictions
568
        npred <- 0L
569
        npred <- lgb.call(
570
          fun_name = "LGBM_BoosterGetNumPredict_R"
571
572
          , ret = npred
          , private$handle
573
          , as.integer(idx - 1L)
574
        )
575
        private$predict_buffer[[data_name]] <- numeric(npred)
576

Guolin Ke's avatar
Guolin Ke committed
577
      }
578

579
      # Check if current iteration was already predicted
Guolin Ke's avatar
Guolin Ke committed
580
      if (!private$is_predicted_cur_iter[[idx]]) {
581

582
        # Use buffer
583
584
585
586
        private$predict_buffer[[data_name]] <- lgb.call(
          "LGBM_BoosterGetPredict_R"
          , ret = private$predict_buffer[[data_name]]
          , private$handle
587
          , as.integer(idx - 1L)
588
        )
Guolin Ke's avatar
Guolin Ke committed
589
590
        private$is_predicted_cur_iter[[idx]] <- TRUE
      }
591

592
      return(private$predict_buffer[[data_name]])
Guolin Ke's avatar
Guolin Ke committed
593
    },
594

595
    # Get evaluation information
Guolin Ke's avatar
Guolin Ke committed
596
    get_eval_info = function() {
597

598
      # Check for evaluation names emptiness
Guolin Ke's avatar
Guolin Ke committed
599
      if (is.null(private$eval_names)) {
600

601
        # Get evaluation names
602
        names <- lgb.call.return.str(
603
          fun_name = "LGBM_BoosterGetEvalNames_R"
604
605
          , private$handle
        )
606

607
        # Check names' length
608
        if (nchar(names) > 0L) {
609

610
          # Parse and store privately names
611
          names <- strsplit(names, "\t")[[1L]]
Guolin Ke's avatar
Guolin Ke committed
612
          private$eval_names <- names
613
614
615
616
617

          # some metrics don't map cleanly to metric names, for example "ndcg@1" is just the
          # ndcg metric evaluated at the first "query result" in learning-to-rank
          metric_names <- gsub("@.*", "", names)
          private$higher_better_inner_eval <- .METRICS_HIGHER_BETTER()[metric_names]
618

Guolin Ke's avatar
Guolin Ke committed
619
        }
620

Guolin Ke's avatar
Guolin Ke committed
621
      }
622

623
      return(private$eval_names)
624

Guolin Ke's avatar
Guolin Ke committed
625
    },
626

627
    # Perform inner evaluation
Guolin Ke's avatar
Guolin Ke committed
628
    inner_eval = function(data_name, data_idx, feval = NULL) {
629

630
      # Check for unknown dataset (over the maximum provided range)
Guolin Ke's avatar
Guolin Ke committed
631
632
633
      if (data_idx > private$num_dataset) {
        stop("data_idx should not be greater than num_dataset")
      }
634

635
      # Get evaluation information
Guolin Ke's avatar
Guolin Ke committed
636
      private$get_eval_info()
637

638
      # Prepare return
Guolin Ke's avatar
Guolin Ke committed
639
      ret <- list()
640

641
      # Check evaluation names existence
642
      if (length(private$eval_names) > 0L) {
643

644
645
        # Create evaluation values
        tmp_vals <- numeric(length(private$eval_names))
646
        tmp_vals <- lgb.call(
647
          fun_name = "LGBM_BoosterGetEval_R"
648
649
          , ret = tmp_vals
          , private$handle
650
          , as.integer(data_idx - 1L)
651
        )
652

653
        # Loop through all evaluation names
654
        for (i in seq_along(private$eval_names)) {
655

656
657
658
659
660
          # Store evaluation and append to return
          res <- list()
          res$data_name <- data_name
          res$name <- private$eval_names[i]
          res$value <- tmp_vals[i]
Guolin Ke's avatar
Guolin Ke committed
661
          res$higher_better <- private$higher_better_inner_eval[i]
662
          ret <- append(ret, list(res))
663

Guolin Ke's avatar
Guolin Ke committed
664
        }
665

Guolin Ke's avatar
Guolin Ke committed
666
      }
667

668
      # Check if there are evaluation metrics
Guolin Ke's avatar
Guolin Ke committed
669
      if (!is.null(feval)) {
670

671
        # Check if evaluation metric is a function
672
        if (!is.function(feval)) {
Guolin Ke's avatar
Guolin Ke committed
673
674
          stop("lgb.Booster.eval: feval should be a function")
        }
675

676
        # Prepare data
Guolin Ke's avatar
Guolin Ke committed
677
        data <- private$train_set
678

679
        # Check if data to assess is existing differently
680
681
        if (data_idx > 1L) {
          data <- private$valid_sets[[data_idx - 1L]]
682
        }
683

684
        # Perform function evaluation
685
        res <- feval(private$inner_predict(data_idx), data)
686

687
        # Check for name correctness
688
        if (is.null(res$name) || is.null(res$value) ||  is.null(res$higher_better)) {
689
          stop("lgb.Booster.eval: custom eval function should return a
690
691
            list with attribute (name, value, higher_better)");
        }
692

693
        # Append names and evaluation
Guolin Ke's avatar
Guolin Ke committed
694
        res$data_name <- data_name
695
        ret <- append(ret, list(res))
Guolin Ke's avatar
Guolin Ke committed
696
      }
697

698
      return(ret)
699

Guolin Ke's avatar
Guolin Ke committed
700
    }
701

Guolin Ke's avatar
Guolin Ke committed
702
703
704
  )
)

705
706
707
#' @name predict.lgb.Booster
#' @title Predict method for LightGBM model
#' @description Predicted values based on class \code{lgb.Booster}
Guolin Ke's avatar
Guolin Ke committed
708
709
#' @param object Object of class \code{lgb.Booster}
#' @param data a \code{matrix} object, a \code{dgCMatrix} object or a character representing a filename
710
711
712
713
714
715
716
717
#' @param start_iteration int or None, optional (default=None)
#'                        Start index of the iteration to predict.
#'                        If None or <= 0, starts from the first iteration.
#' @param num_iteration int or None, optional (default=None)
#'                      Limit number of iterations in the prediction.
#'                      If None, if the best iteration exists and start_iteration is None or <= 0, the
#'                      best iteration is used; otherwise, all iterations from start_iteration are used.
#'                      If <= 0, all iterations from start_iteration are used (no limits).
718
#' @param rawscore whether the prediction should be returned in the for of original untransformed
719
720
#'                 sum of predictions from boosting iterations' results. E.g., setting \code{rawscore=TRUE}
#'                 for logistic regression would result in predictions for log-odds instead of probabilities.
721
#' @param predleaf whether predict leaf index instead.
722
#' @param predcontrib return per-feature contributions for each record.
Guolin Ke's avatar
Guolin Ke committed
723
#' @param header only used for prediction for text file. True if text file has header
724
#' @param reshape whether to reshape the vector of predictions to a matrix form when there are several
725
#'                prediction outputs per case.
James Lamb's avatar
James Lamb committed
726
727
#' @param ... Additional named arguments passed to the \code{predict()} method of
#'            the \code{lgb.Booster} object passed to \code{object}.
728
729
730
731
#' @return For regression or binary classification, it returns a vector of length \code{nrows(data)}.
#'         For multiclass classification, either a \code{num_class * nrows(data)} vector or
#'         a \code{(nrows(data), num_class)} dimension matrix is returned, depending on
#'         the \code{reshape} value.
732
#'
733
734
#'         When \code{predleaf = TRUE}, the output is a matrix object with the
#'         number of columns corresponding to the number of trees.
735
#'
Guolin Ke's avatar
Guolin Ke committed
736
#' @examples
737
#' \donttest{
738
739
740
741
742
743
744
745
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' data(agaricus.test, package = "lightgbm")
#' test <- agaricus.test
#' dtest <- lgb.Dataset.create.valid(dtrain, test$data, label = test$label)
#' params <- list(objective = "regression", metric = "l2")
#' valids <- list(test = dtest)
746
747
748
#' model <- lgb.train(
#'   params = params
#'   , data = dtrain
749
#'   , nrounds = 5L
750
#'   , valids = valids
751
752
#'   , min_data = 1L
#'   , learning_rate = 1.0
753
#' )
754
#' preds <- predict(model, test$data)
755
#' }
Guolin Ke's avatar
Guolin Ke committed
756
#' @export
James Lamb's avatar
James Lamb committed
757
758
predict.lgb.Booster <- function(object,
                                data,
759
                                start_iteration = NULL,
James Lamb's avatar
James Lamb committed
760
761
762
763
764
                                num_iteration = NULL,
                                rawscore = FALSE,
                                predleaf = FALSE,
                                predcontrib = FALSE,
                                header = FALSE,
765
                                reshape = FALSE,
James Lamb's avatar
James Lamb committed
766
                                ...) {
767

768
769
  if (!lgb.is.Booster(object)) {
    stop("predict.lgb.Booster: object should be an ", sQuote("lgb.Booster"))
Guolin Ke's avatar
Guolin Ke committed
770
  }
771

772
  # Return booster predictions
773
  object$predict(
774
775
776
777
778
779
780
781
    data = data
      , start_iteration = start_iteration
      , num_iteration = num_iteration
      , rawscore = rawscore
      , predleaf =  predleaf
      , predcontrib =  predcontrib
      , header = header
      , reshape = reshape
782
783
    , ...
  )
Guolin Ke's avatar
Guolin Ke committed
784
785
}

786
787
788
789
#' @name lgb.load
#' @title Load LightGBM model
#' @description  Load LightGBM takes in either a file path or model string.
#'               If both are provided, Load will default to loading from file
Guolin Ke's avatar
Guolin Ke committed
790
#' @param filename path of model file
791
#' @param model_str a str containing the model
792
#'
793
#' @return lgb.Booster
794
#'
Guolin Ke's avatar
Guolin Ke committed
795
#' @examples
796
#' \donttest{
797
798
799
800
801
802
803
804
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' data(agaricus.test, package = "lightgbm")
#' test <- agaricus.test
#' dtest <- lgb.Dataset.create.valid(dtrain, test$data, label = test$label)
#' params <- list(objective = "regression", metric = "l2")
#' valids <- list(test = dtest)
805
806
807
#' model <- lgb.train(
#'   params = params
#'   , data = dtrain
808
#'   , nrounds = 5L
809
#'   , valids = valids
810
811
#'   , min_data = 1L
#'   , learning_rate = 1.0
812
#'   , early_stopping_rounds = 3L
813
#' )
814
815
816
#' model_file <- tempfile(fileext = ".txt")
#' lgb.save(model, model_file)
#' load_booster <- lgb.load(filename = model_file)
817
818
#' model_string <- model$save_model_to_string(NULL) # saves best iteration
#' load_booster_from_str <- lgb.load(model_str = model_string)
819
#' }
Guolin Ke's avatar
Guolin Ke committed
820
#' @export
821
lgb.load <- function(filename = NULL, model_str = NULL) {
822

823
824
  filename_provided <- !is.null(filename)
  model_str_provided <- !is.null(model_str)
825

826
827
828
829
830
831
832
  if (filename_provided) {
    if (!is.character(filename)) {
      stop("lgb.load: filename should be character")
    }
    if (!file.exists(filename)) {
      stop(sprintf("lgb.load: file '%s' passed to filename does not exist", filename))
    }
833
834
    return(invisible(Booster$new(modelfile = filename)))
  }
835

836
837
838
839
  if (model_str_provided) {
    if (!is.character(model_str)) {
      stop("lgb.load: model_str should be character")
    }
840
841
    return(invisible(Booster$new(model_str = model_str)))
  }
842

843
  stop("lgb.load: either filename or model_str must be given")
Guolin Ke's avatar
Guolin Ke committed
844
845
}

846
847
848
#' @name lgb.save
#' @title Save LightGBM model
#' @description Save LightGBM model
Guolin Ke's avatar
Guolin Ke committed
849
850
851
#' @param booster Object of class \code{lgb.Booster}
#' @param filename saved filename
#' @param num_iteration number of iteration want to predict with, NULL or <= 0 means use best iteration
852
#'
853
#' @return lgb.Booster
854
#'
Guolin Ke's avatar
Guolin Ke committed
855
#' @examples
856
#' \donttest{
857
858
859
860
861
862
863
864
865
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' data(agaricus.test, package = "lightgbm")
#' test <- agaricus.test
#' dtest <- lgb.Dataset.create.valid(dtrain, test$data, label = test$label)
#' params <- list(objective = "regression", metric = "l2")
#' valids <- list(test = dtest)
866
867
868
#' model <- lgb.train(
#'   params = params
#'   , data = dtrain
869
#'   , nrounds = 10L
870
#'   , valids = valids
871
872
873
#'   , min_data = 1L
#'   , learning_rate = 1.0
#'   , early_stopping_rounds = 5L
874
#' )
875
#' lgb.save(model, tempfile(fileext = ".txt"))
876
#' }
Guolin Ke's avatar
Guolin Ke committed
877
#' @export
878
lgb.save <- function(booster, filename, num_iteration = NULL) {
879

880
881
882
  if (!lgb.is.Booster(booster)) {
    stop("lgb.save: booster should be an ", sQuote("lgb.Booster"))
  }
883

884
885
  if (!(is.character(filename) && length(filename) == 1L)) {
    stop("lgb.save: filename should be a string")
886
  }
887

888
  # Store booster
889
890
891
892
  invisible(booster$save_model(
    filename = filename
    , num_iteration = num_iteration
  ))
893

Guolin Ke's avatar
Guolin Ke committed
894
895
}

896
897
898
#' @name lgb.dump
#' @title Dump LightGBM model to json
#' @description Dump LightGBM model to json
Guolin Ke's avatar
Guolin Ke committed
899
900
#' @param booster Object of class \code{lgb.Booster}
#' @param num_iteration number of iteration want to predict with, NULL or <= 0 means use best iteration
901
#'
Guolin Ke's avatar
Guolin Ke committed
902
#' @return json format of model
903
#'
Guolin Ke's avatar
Guolin Ke committed
904
#' @examples
905
#' \donttest{
906
907
908
909
910
911
912
913
914
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' data(agaricus.test, package = "lightgbm")
#' test <- agaricus.test
#' dtest <- lgb.Dataset.create.valid(dtrain, test$data, label = test$label)
#' params <- list(objective = "regression", metric = "l2")
#' valids <- list(test = dtest)
915
916
917
#' model <- lgb.train(
#'   params = params
#'   , data = dtrain
918
#'   , nrounds = 10L
919
#'   , valids = valids
920
921
922
#'   , min_data = 1L
#'   , learning_rate = 1.0
#'   , early_stopping_rounds = 5L
923
#' )
924
#' json_model <- lgb.dump(model)
925
#' }
Guolin Ke's avatar
Guolin Ke committed
926
#' @export
927
lgb.dump <- function(booster, num_iteration = NULL) {
928

929
930
931
  if (!lgb.is.Booster(booster)) {
    stop("lgb.save: booster should be an ", sQuote("lgb.Booster"))
  }
932

933
  # Return booster at requested iteration
934
  booster$dump_model(num_iteration =  num_iteration)
935

Guolin Ke's avatar
Guolin Ke committed
936
937
}

938
939
#' @name lgb.get.eval.result
#' @title Get record evaluation result from booster
940
941
#' @description Given a \code{lgb.Booster}, return evaluation results for a
#'              particular metric on a particular dataset.
Guolin Ke's avatar
Guolin Ke committed
942
#' @param booster Object of class \code{lgb.Booster}
943
944
945
946
#' @param data_name Name of the dataset to return evaluation results for.
#' @param eval_name Name of the evaluation metric to return results for.
#' @param iters An integer vector of iterations you want to get evaluation results for. If NULL
#'              (the default), evaluation results for all iterations will be returned.
Guolin Ke's avatar
Guolin Ke committed
947
#' @param is_err TRUE will return evaluation error instead
948
#'
949
#' @return numeric vector of evaluation result
950
#'
951
#' @examples
952
#' \donttest{
953
#' # train a regression model
954
955
956
957
958
959
960
961
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' data(agaricus.test, package = "lightgbm")
#' test <- agaricus.test
#' dtest <- lgb.Dataset.create.valid(dtrain, test$data, label = test$label)
#' params <- list(objective = "regression", metric = "l2")
#' valids <- list(test = dtest)
962
963
964
#' model <- lgb.train(
#'   params = params
#'   , data = dtrain
965
#'   , nrounds = 5L
966
#'   , valids = valids
967
968
#'   , min_data = 1L
#'   , learning_rate = 1.0
969
#' )
970
971
972
973
974
975
976
977
#'
#' # Examine valid data_name values
#' print(setdiff(names(model$record_evals), "start_iter"))
#'
#' # Examine valid eval_name values for dataset "test"
#' print(names(model$record_evals[["test"]]))
#'
#' # Get L2 values for "test" dataset
978
#' lgb.get.eval.result(model, "test", "l2")
979
#' }
Guolin Ke's avatar
Guolin Ke committed
980
#' @export
981
lgb.get.eval.result <- function(booster, data_name, eval_name, iters = NULL, is_err = FALSE) {
982

983
  # Check if booster is booster
984
985
  if (!lgb.is.Booster(booster)) {
    stop("lgb.get.eval.result: Can only use ", sQuote("lgb.Booster"), " to get eval result")
Guolin Ke's avatar
Guolin Ke committed
986
  }
987

988
  # Check if data and evaluation name are characters or not
989
990
  if (!is.character(data_name) || !is.character(eval_name)) {
    stop("lgb.get.eval.result: data_name and eval_name should be characters")
Guolin Ke's avatar
Guolin Ke committed
991
  }
992

993
994
995
996
997
998
999
1000
1001
1002
  # NOTE: "start_iter" exists in booster$record_evals but is not a valid data_name
  data_names <- setdiff(names(booster$record_evals), "start_iter")
  if (!(data_name %in% data_names)) {
    stop(paste0(
      "lgb.get.eval.result: data_name "
      , shQuote(data_name)
      , " not found. Only the following datasets exist in record evals: ["
      , paste(data_names, collapse = ", ")
      , "]"
    ))
Guolin Ke's avatar
Guolin Ke committed
1003
  }
1004

1005
  # Check if evaluation result is existing
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
  eval_names <- names(booster$record_evals[[data_name]])
  if (!(eval_name %in% eval_names)) {
    stop(paste0(
      "lgb.get.eval.result: eval_name "
      , shQuote(eval_name)
      , " not found. Only the following eval_names exist for dataset "
      , shQuote(data_name)
      , ": ["
      , paste(eval_names, collapse = ", ")
      , "]"
    ))
Guolin Ke's avatar
Guolin Ke committed
1017
1018
    stop("lgb.get.eval.result: wrong eval name")
  }
1019

1020
  result <- booster$record_evals[[data_name]][[eval_name]][[.EVAL_KEY()]]
1021

1022
  # Check if error is requested
1023
  if (is_err) {
1024
    result <- booster$record_evals[[data_name]][[eval_name]][[.EVAL_ERR_KEY()]]
Guolin Ke's avatar
Guolin Ke committed
1025
  }
1026

1027
  # Check if iteration is non existant
1028
  if (is.null(iters)) {
Guolin Ke's avatar
Guolin Ke committed
1029
1030
    return(as.numeric(result))
  }
1031

1032
  # Parse iteration and booster delta
Guolin Ke's avatar
Guolin Ke committed
1033
  iters <- as.integer(iters)
1034
  delta <- booster$record_evals$start_iter - 1.0
Guolin Ke's avatar
Guolin Ke committed
1035
  iters <- iters - delta
1036

1037
  # Return requested result
1038
  as.numeric(result[iters])
Guolin Ke's avatar
Guolin Ke committed
1039
}