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

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

13
14
    # Finalize will free up the handles
    finalize = function() {
15
16
17
18
19
      .Call(
        LGBM_BoosterFree_R
        , private$handle
      )
      private$handle <- NULL
20
      return(invisible(NULL))
21
    },
22

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

29
      handle <- NULL
30

31
      if (!is.null(train_set)) {
32

33
34
35
36
37
38
39
40
41
42
43
44
        if (!lgb.is.Dataset(train_set)) {
          stop("lgb.Booster: Can only use lgb.Dataset as training data")
        }
        train_set_handle <- train_set$.__enclos_env__$private$get_handle()
        params <- utils::modifyList(params, train_set$get_params())
        params_str <- lgb.params2str(params = params)
        # Store booster handle
        handle <- .Call(
          LGBM_BoosterCreate_R
          , train_set_handle
          , params_str
        )
45

46
47
48
49
50
        # Create private booster information
        private$train_set <- train_set
        private$train_set_version <- train_set$.__enclos_env__$private$version
        private$num_dataset <- 1L
        private$init_predictor <- train_set$.__enclos_env__$private$predictor
51

52
        if (!is.null(private$init_predictor)) {
53

54
55
56
57
58
          # Merge booster
          .Call(
            LGBM_BoosterMerge_R
            , handle
            , private$init_predictor$.__enclos_env__$private$handle
59
          )
60

61
        }
62

63
64
        # Check current iteration
        private$is_predicted_cur_iter <- c(private$is_predicted_cur_iter, FALSE)
65

66
      } else if (!is.null(modelfile)) {
67

68
69
70
71
        # Do we have a model file as character?
        if (!is.character(modelfile)) {
          stop("lgb.Booster: Can only use a string as model file path")
        }
72

73
        modelfile <- path.expand(modelfile)
74

75
76
77
78
79
        # Create booster from model
        handle <- .Call(
          LGBM_BoosterCreateFromModelfile_R
          , modelfile
        )
80

81
      } else if (!is.null(model_str)) {
82

83
84
85
86
        # Do we have a model_str as character/raw?
        if (!is.raw(model_str) && !is.character(model_str)) {
          stop("lgb.Booster: Can only use a character/raw vector as model_str")
        }
87

88
89
90
91
92
        # Create booster from model
        handle <- .Call(
          LGBM_BoosterLoadModelFromString_R
          , model_str
        )
93

Guolin Ke's avatar
Guolin Ke committed
94
      } else {
95

96
97
98
99
        # Booster non existent
        stop(
          "lgb.Booster: Need at least either training dataset, "
          , "model file, or model_str to create booster instance"
100
        )
101

Guolin Ke's avatar
Guolin Ke committed
102
      }
103

104
105
106
107
108
109
110
111
112
      class(handle) <- "lgb.Booster.handle"
      private$handle <- handle
      private$num_class <- 1L
      .Call(
        LGBM_BoosterGetNumClasses_R
        , private$handle
        , private$num_class
      )

113
114
      self$params <- params

115
116
      return(invisible(NULL))

Guolin Ke's avatar
Guolin Ke committed
117
    },
118

119
    # Set training data name
Guolin Ke's avatar
Guolin Ke committed
120
    set_train_data_name = function(name) {
121

122
      # Set name
Guolin Ke's avatar
Guolin Ke committed
123
      private$name_train_set <- name
124
      return(invisible(self))
125

Guolin Ke's avatar
Guolin Ke committed
126
    },
127

128
    # Add validation data
Guolin Ke's avatar
Guolin Ke committed
129
    add_valid = function(data, name) {
130

131
      if (!lgb.is.Dataset(data)) {
132
        stop("lgb.Booster.add_valid: Can only use lgb.Dataset as validation data")
Guolin Ke's avatar
Guolin Ke committed
133
      }
134

Guolin Ke's avatar
Guolin Ke committed
135
      if (!identical(data$.__enclos_env__$private$predictor, private$init_predictor)) {
136
137
138
139
        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
140
      }
141

142
143
      if (!is.character(name)) {
        stop("lgb.Booster.add_valid: Can only use characters as data name")
Guolin Ke's avatar
Guolin Ke committed
144
      }
145

146
      # Add validation data to booster
147
148
      .Call(
        LGBM_BoosterAddValidData_R
149
150
151
        , private$handle
        , data$.__enclos_env__$private$get_handle()
      )
152

153
154
      private$valid_sets <- c(private$valid_sets, data)
      private$name_valid_sets <- c(private$name_valid_sets, name)
155
      private$num_dataset <- private$num_dataset + 1L
156
      private$is_predicted_cur_iter <- c(private$is_predicted_cur_iter, FALSE)
157

158
      return(invisible(self))
159

Guolin Ke's avatar
Guolin Ke committed
160
    },
161

162
    reset_parameter = function(params) {
163

164
      if (methods::is(self$params, "list")) {
165
        params <- utils::modifyList(self$params, params)
166
167
      }

168
      params_str <- lgb.params2str(params = params)
169

170
171
      self$restore_handle()

172
173
      .Call(
        LGBM_BoosterResetParameter_R
174
175
176
        , private$handle
        , params_str
      )
177
      self$params <- params
178

179
      return(invisible(self))
180

Guolin Ke's avatar
Guolin Ke committed
181
    },
182

183
    # Perform boosting update iteration
Guolin Ke's avatar
Guolin Ke committed
184
    update = function(train_set = NULL, fobj = NULL) {
185

186
187
188
189
190
191
      if (is.null(train_set)) {
        if (private$train_set$.__enclos_env__$private$version != private$train_set_version) {
          train_set <- private$train_set
        }
      }

Guolin Ke's avatar
Guolin Ke committed
192
      if (!is.null(train_set)) {
193

194
        if (!lgb.is.Dataset(train_set)) {
Guolin Ke's avatar
Guolin Ke committed
195
196
          stop("lgb.Booster.update: Only can use lgb.Dataset as training data")
        }
197

Guolin Ke's avatar
Guolin Ke committed
198
        if (!identical(train_set$predictor, private$init_predictor)) {
199
          stop("lgb.Booster.update: Change train_set failed, you should use the same predictor for these data")
Guolin Ke's avatar
Guolin Ke committed
200
        }
201

202
203
        .Call(
          LGBM_BoosterResetTrainingData_R
204
205
206
          , private$handle
          , train_set$.__enclos_env__$private$get_handle()
        )
207

208
        private$train_set <- train_set
209
        private$train_set_version <- train_set$.__enclos_env__$private$version
210

Guolin Ke's avatar
Guolin Ke committed
211
      }
212

213
      # Check if objective is empty
Guolin Ke's avatar
Guolin Ke committed
214
      if (is.null(fobj)) {
215
216
217
        if (private$set_objective_to_none) {
          stop("lgb.Booster.update: cannot update due to null objective function")
        }
218
        # Boost iteration from known objective
219
220
        .Call(
          LGBM_BoosterUpdateOneIter_R
221
222
          , private$handle
        )
223

Guolin Ke's avatar
Guolin Ke committed
224
      } else {
225

226
227
228
        if (!is.function(fobj)) {
          stop("lgb.Booster.update: fobj should be a function")
        }
229
        if (!private$set_objective_to_none) {
230
          self$reset_parameter(params = list(objective = "none"))
231
          private$set_objective_to_none <- TRUE
232
        }
233
        # Perform objective calculation
234
        gpair <- fobj(private$inner_predict(1L), private$train_set)
235

236
        # Check for gradient and hessian as list
237
        if (is.null(gpair$grad) || is.null(gpair$hess)) {
238
          stop("lgb.Booster.update: custom objective should
239
240
            return a list with attributes (hess, grad)")
        }
241

242
        # Return custom boosting gradient/hessian
243
244
        .Call(
          LGBM_BoosterUpdateOneIterCustom_R
245
246
247
248
249
          , private$handle
          , gpair$grad
          , gpair$hess
          , length(gpair$grad)
        )
250

Guolin Ke's avatar
Guolin Ke committed
251
      }
252

253
      # Loop through each iteration
254
      for (i in seq_along(private$is_predicted_cur_iter)) {
Guolin Ke's avatar
Guolin Ke committed
255
256
        private$is_predicted_cur_iter[[i]] <- FALSE
      }
257

258
      return(invisible(self))
259

Guolin Ke's avatar
Guolin Ke committed
260
    },
261

262
    # Return one iteration behind
Guolin Ke's avatar
Guolin Ke committed
263
    rollback_one_iter = function() {
264

265
266
      self$restore_handle()

267
268
      .Call(
        LGBM_BoosterRollbackOneIter_R
269
270
        , private$handle
      )
271

272
      # Loop through each iteration
273
      for (i in seq_along(private$is_predicted_cur_iter)) {
Guolin Ke's avatar
Guolin Ke committed
274
275
        private$is_predicted_cur_iter[[i]] <- FALSE
      }
276

277
      return(invisible(self))
278

Guolin Ke's avatar
Guolin Ke committed
279
    },
280

281
    # Get current iteration
Guolin Ke's avatar
Guolin Ke committed
282
    current_iter = function() {
283

284
285
      self$restore_handle()

286
      cur_iter <- 0L
287
288
289
290
      .Call(
        LGBM_BoosterGetCurrentIteration_R
        , private$handle
        , cur_iter
291
      )
292
      return(cur_iter)
293

Guolin Ke's avatar
Guolin Ke committed
294
    },
295

296
    # Get upper bound
297
    upper_bound = function() {
298

299
300
      self$restore_handle()

301
      upper_bound <- 0.0
302
303
304
305
      .Call(
        LGBM_BoosterGetUpperBoundValue_R
        , private$handle
        , upper_bound
306
      )
307
      return(upper_bound)
308
309
310
311

    },

    # Get lower bound
312
    lower_bound = function() {
313

314
315
      self$restore_handle()

316
      lower_bound <- 0.0
317
318
319
320
      .Call(
        LGBM_BoosterGetLowerBoundValue_R
        , private$handle
        , lower_bound
321
      )
322
      return(lower_bound)
323
324
325

    },

326
    # Evaluate data on metrics
Guolin Ke's avatar
Guolin Ke committed
327
    eval = function(data, name, feval = NULL) {
328

329
      if (!lgb.is.Dataset(data)) {
330
        stop("lgb.Booster.eval: Can only use lgb.Dataset to eval")
Guolin Ke's avatar
Guolin Ke committed
331
      }
332

333
      # Check for identical data
334
      data_idx <- 0L
335
      if (identical(data, private$train_set)) {
336
        data_idx <- 1L
337
      } else {
338

339
        # Check for validation data
340
        if (length(private$valid_sets) > 0L) {
341

342
          for (i in seq_along(private$valid_sets)) {
343

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

347
              # Found identical data, skip
348
              data_idx <- i + 1L
Guolin Ke's avatar
Guolin Ke committed
349
              break
350

Guolin Ke's avatar
Guolin Ke committed
351
            }
352

Guolin Ke's avatar
Guolin Ke committed
353
          }
354

Guolin Ke's avatar
Guolin Ke committed
355
        }
356

Guolin Ke's avatar
Guolin Ke committed
357
      }
358

359
      # Check if evaluation was not done
360
      if (data_idx == 0L) {
361

362
        # Add validation data by name
Guolin Ke's avatar
Guolin Ke committed
363
364
        self$add_valid(data, name)
        data_idx <- private$num_dataset
365

Guolin Ke's avatar
Guolin Ke committed
366
      }
367

368
      # Evaluate data
369
370
371
372
373
374
      return(
        private$inner_eval(
          data_name = name
          , data_idx = data_idx
          , feval = feval
        )
375
      )
376

Guolin Ke's avatar
Guolin Ke committed
377
    },
378

379
    # Evaluation training data
Guolin Ke's avatar
Guolin Ke committed
380
    eval_train = function(feval = NULL) {
381
      return(private$inner_eval(private$name_train_set, 1L, feval))
Guolin Ke's avatar
Guolin Ke committed
382
    },
383

384
    # Evaluation validation data
Guolin Ke's avatar
Guolin Ke committed
385
    eval_valid = function(feval = NULL) {
386

387
      ret <- list()
388

389
      if (length(private$valid_sets) <= 0L) {
390
391
        return(ret)
      }
392

393
      for (i in seq_along(private$valid_sets)) {
394
395
        ret <- append(
          x = ret
396
          , values = private$inner_eval(private$name_valid_sets[[i]], i + 1L, feval)
397
        )
Guolin Ke's avatar
Guolin Ke committed
398
      }
399

400
      return(ret)
401

Guolin Ke's avatar
Guolin Ke committed
402
    },
403

404
    # Save model
405
    save_model = function(filename, num_iteration = NULL, feature_importance_type = 0L) {
406

407
408
      self$restore_handle()

409
410
411
      if (is.null(num_iteration)) {
        num_iteration <- self$best_iter
      }
412

413
414
      filename <- path.expand(filename)

415
416
      .Call(
        LGBM_BoosterSaveModel_R
417
418
        , private$handle
        , as.integer(num_iteration)
419
        , as.integer(feature_importance_type)
420
        , filename
421
      )
422

423
      return(invisible(self))
Guolin Ke's avatar
Guolin Ke committed
424
    },
425

426
427
428
    save_model_to_string = function(num_iteration = NULL, feature_importance_type = 0L, as_char = TRUE) {

      self$restore_handle()
429

430
431
432
      if (is.null(num_iteration)) {
        num_iteration <- self$best_iter
      }
433

434
      model_str <- .Call(
435
          LGBM_BoosterSaveModelToString_R
436
437
438
          , private$handle
          , as.integer(num_iteration)
          , as.integer(feature_importance_type)
439
440
      )

441
442
443
444
      if (as_char) {
        model_str <- rawToChar(model_str)
      }

445
      return(model_str)
446

447
    },
448

449
    # Dump model in memory
450
    dump_model = function(num_iteration = NULL, feature_importance_type = 0L) {
451

452
453
      self$restore_handle()

454
455
456
      if (is.null(num_iteration)) {
        num_iteration <- self$best_iter
      }
457

458
      model_str <- .Call(
459
460
461
462
463
464
        LGBM_BoosterDumpModel_R
        , private$handle
        , as.integer(num_iteration)
        , as.integer(feature_importance_type)
      )

465
      return(model_str)
466

Guolin Ke's avatar
Guolin Ke committed
467
    },
468

469
    # Predict on new data
Guolin Ke's avatar
Guolin Ke committed
470
    predict = function(data,
471
                       start_iteration = NULL,
472
473
474
                       num_iteration = NULL,
                       rawscore = FALSE,
                       predleaf = FALSE,
475
                       predcontrib = FALSE,
476
                       header = FALSE,
477
                       reshape = FALSE,
478
                       params = list()) {
479

480
481
      self$restore_handle()

482
483
484
      if (is.null(num_iteration)) {
        num_iteration <- self$best_iter
      }
485

486
487
488
      if (is.null(start_iteration)) {
        start_iteration <- 0L
      }
489

490
      # Predict on new data
491
492
493
494
      predictor <- Predictor$new(
        modelfile = private$handle
        , params = params
      )
495
496
      return(
        predictor$predict(
497
498
499
500
501
502
503
504
          data = data
          , start_iteration = start_iteration
          , num_iteration = num_iteration
          , rawscore = rawscore
          , predleaf = predleaf
          , predcontrib = predcontrib
          , header = header
          , reshape = reshape
505
        )
506
      )
507

508
    },
509

510
511
    # Transform into predictor
    to_predictor = function() {
512
      return(Predictor$new(modelfile = private$handle))
Guolin Ke's avatar
Guolin Ke committed
513
    },
514

515
516
    # Used for serialization
    raw = NULL,
517

518
519
520
521
522
523
    # Store serialized raw bytes in model object
    save_raw = function() {
      if (is.null(self$raw)) {
        self$raw <- self$save_model_to_string(NULL, as_char = FALSE)
      }
      return(invisible(NULL))
524

525
    },
526

527
528
    drop_raw = function() {
      self$raw <- NULL
529
      return(invisible(NULL))
530
    },
531

532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
    check_null_handle = function() {
      return(lgb.is.null.handle(private$handle))
    },

    restore_handle = function() {
      if (self$check_null_handle()) {
        if (is.null(self$raw)) {
          .Call(LGBM_NullBoosterHandleError_R)
        }
        private$handle <- .Call(LGBM_BoosterLoadModelFromString_R, self$raw)
      }
      return(invisible(NULL))
    },

    get_handle = function() {
      return(private$handle)
548
    }
549

Guolin Ke's avatar
Guolin Ke committed
550
551
  ),
  private = list(
552
553
554
555
556
557
558
    handle = NULL,
    train_set = NULL,
    name_train_set = "training",
    valid_sets = list(),
    name_valid_sets = list(),
    predict_buffer = list(),
    is_predicted_cur_iter = list(),
559
560
    num_class = 1L,
    num_dataset = 0L,
561
562
    init_predictor = NULL,
    eval_names = NULL,
Guolin Ke's avatar
Guolin Ke committed
563
    higher_better_inner_eval = NULL,
564
    set_objective_to_none = FALSE,
565
    train_set_version = 0L,
566
567
    # Predict data
    inner_predict = function(idx) {
568

569
      # Store data name
Guolin Ke's avatar
Guolin Ke committed
570
      data_name <- private$name_train_set
571

572
573
      if (idx > 1L) {
        data_name <- private$name_valid_sets[[idx - 1L]]
574
      }
575

576
      # Check for unknown dataset (over the maximum provided range)
Guolin Ke's avatar
Guolin Ke committed
577
578
579
      if (idx > private$num_dataset) {
        stop("data_idx should not be greater than num_dataset")
      }
580

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

584
        # Store predictions
585
        npred <- 0L
586
587
        .Call(
          LGBM_BoosterGetNumPredict_R
588
          , private$handle
589
          , as.integer(idx - 1L)
590
          , npred
591
        )
592
        private$predict_buffer[[data_name]] <- numeric(npred)
593

Guolin Ke's avatar
Guolin Ke committed
594
      }
595

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

599
        # Use buffer
600
601
        .Call(
          LGBM_BoosterGetPredict_R
602
          , private$handle
603
          , as.integer(idx - 1L)
604
          , private$predict_buffer[[data_name]]
605
        )
Guolin Ke's avatar
Guolin Ke committed
606
607
        private$is_predicted_cur_iter[[idx]] <- TRUE
      }
608

609
      return(private$predict_buffer[[data_name]])
Guolin Ke's avatar
Guolin Ke committed
610
    },
611

612
    # Get evaluation information
Guolin Ke's avatar
Guolin Ke committed
613
    get_eval_info = function() {
614

Guolin Ke's avatar
Guolin Ke committed
615
      if (is.null(private$eval_names)) {
616
        eval_names <- .Call(
617
          LGBM_BoosterGetEvalNames_R
618
619
          , private$handle
        )
620

621
        if (length(eval_names) > 0L) {
622

623
          # Parse and store privately names
624
          private$eval_names <- eval_names
625
626
627

          # 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
628
          metric_names <- gsub("@.*", "", eval_names)
629
          private$higher_better_inner_eval <- .METRICS_HIGHER_BETTER()[metric_names]
630

Guolin Ke's avatar
Guolin Ke committed
631
        }
632

Guolin Ke's avatar
Guolin Ke committed
633
      }
634

635
      return(private$eval_names)
636

Guolin Ke's avatar
Guolin Ke committed
637
    },
638

Guolin Ke's avatar
Guolin Ke committed
639
    inner_eval = function(data_name, data_idx, feval = NULL) {
640

641
      # Check for unknown dataset (over the maximum provided range)
Guolin Ke's avatar
Guolin Ke committed
642
643
644
      if (data_idx > private$num_dataset) {
        stop("data_idx should not be greater than num_dataset")
      }
645

646
647
      self$restore_handle()

Guolin Ke's avatar
Guolin Ke committed
648
      private$get_eval_info()
649

Guolin Ke's avatar
Guolin Ke committed
650
      ret <- list()
651

652
      if (length(private$eval_names) > 0L) {
653

654
655
        # Create evaluation values
        tmp_vals <- numeric(length(private$eval_names))
656
657
        .Call(
          LGBM_BoosterGetEval_R
658
          , private$handle
659
          , as.integer(data_idx - 1L)
660
          , tmp_vals
661
        )
662

663
        for (i in seq_along(private$eval_names)) {
664

665
666
667
668
669
          # 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
670
          res$higher_better <- private$higher_better_inner_eval[i]
671
          ret <- append(ret, list(res))
672

Guolin Ke's avatar
Guolin Ke committed
673
        }
674

Guolin Ke's avatar
Guolin Ke committed
675
      }
676

677
      # Check if there are evaluation metrics
Guolin Ke's avatar
Guolin Ke committed
678
      if (!is.null(feval)) {
679

680
        # Check if evaluation metric is a function
681
        if (!is.function(feval)) {
Guolin Ke's avatar
Guolin Ke committed
682
683
          stop("lgb.Booster.eval: feval should be a function")
        }
684

Guolin Ke's avatar
Guolin Ke committed
685
        data <- private$train_set
686

687
        # Check if data to assess is existing differently
688
689
        if (data_idx > 1L) {
          data <- private$valid_sets[[data_idx - 1L]]
690
        }
691

692
        # Perform function evaluation
693
        res <- feval(private$inner_predict(data_idx), data)
694

695
        if (is.null(res$name) || is.null(res$value) ||  is.null(res$higher_better)) {
696
          stop("lgb.Booster.eval: custom eval function should return a
697
698
            list with attribute (name, value, higher_better)");
        }
699

700
        # Append names and evaluation
Guolin Ke's avatar
Guolin Ke committed
701
        res$data_name <- data_name
702
        ret <- append(ret, list(res))
Guolin Ke's avatar
Guolin Ke committed
703
      }
704

705
      return(ret)
706

Guolin Ke's avatar
Guolin Ke committed
707
    }
708

Guolin Ke's avatar
Guolin Ke committed
709
710
711
  )
)

712
713
714
#' @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
715
#' @param object Object of class \code{lgb.Booster}
716
717
#' @param data a \code{matrix} object, a \code{dgCMatrix} object or
#'             a character representing a path to a text file (CSV, TSV, or LibSVM)
718
719
720
721
722
723
724
725
#' @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).
726
#' @param rawscore whether the prediction should be returned in the for of original untransformed
727
728
#'                 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.
729
#' @param predleaf whether predict leaf index instead.
730
#' @param predcontrib return per-feature contributions for each record.
Guolin Ke's avatar
Guolin Ke committed
731
#' @param header only used for prediction for text file. True if text file has header
732
#' @param reshape whether to reshape the vector of predictions to a matrix form when there are several
733
#'                prediction outputs per case.
734
735
736
737
#' @param params a list of additional named parameters. See
#'               \href{https://lightgbm.readthedocs.io/en/latest/Parameters.html#predict-parameters}{
#'               the "Predict Parameters" section of the documentation} for a list of parameters and
#'               valid values.
738
#' @param ... ignored
739
740
741
742
#' @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.
743
#'
744
745
#'         When \code{predleaf = TRUE}, the output is a matrix object with the
#'         number of columns corresponding to the number of trees.
746
#'
Guolin Ke's avatar
Guolin Ke committed
747
#' @examples
748
#' \donttest{
749
750
751
752
753
754
#' 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)
755
756
757
758
759
760
#' params <- list(
#'   objective = "regression"
#'   , metric = "l2"
#'   , min_data = 1L
#'   , learning_rate = 1.0
#' )
761
#' valids <- list(test = dtest)
762
763
764
#' model <- lgb.train(
#'   params = params
#'   , data = dtrain
765
#'   , nrounds = 5L
766
767
#'   , valids = valids
#' )
768
#' preds <- predict(model, test$data)
769
770
#'
#' # pass other prediction parameters
771
#' preds <- predict(
772
773
774
775
776
777
#'     model,
#'     test$data,
#'     params = list(
#'         predict_disable_shape_check = TRUE
#'    )
#' )
778
#' }
779
#' @importFrom utils modifyList
Guolin Ke's avatar
Guolin Ke committed
780
#' @export
James Lamb's avatar
James Lamb committed
781
782
predict.lgb.Booster <- function(object,
                                data,
783
                                start_iteration = NULL,
James Lamb's avatar
James Lamb committed
784
785
786
787
788
                                num_iteration = NULL,
                                rawscore = FALSE,
                                predleaf = FALSE,
                                predcontrib = FALSE,
                                header = FALSE,
789
                                reshape = FALSE,
790
                                params = list(),
James Lamb's avatar
James Lamb committed
791
                                ...) {
792

793
  if (!lgb.is.Booster(x = object)) {
794
    stop("predict.lgb.Booster: object should be an ", sQuote("lgb.Booster"))
Guolin Ke's avatar
Guolin Ke committed
795
  }
796

797
798
799
800
801
  additional_params <- list(...)
  if (length(additional_params) > 0L) {
    warning(paste0(
      "predict.lgb.Booster: Found the following passed through '...': "
      , paste(names(additional_params), collapse = ", ")
802
      , ". These are ignored. Use argument 'params' instead."
803
804
805
    ))
  }

806
807
808
  return(
    object$predict(
      data = data
809
810
811
812
813
814
815
      , start_iteration = start_iteration
      , num_iteration = num_iteration
      , rawscore = rawscore
      , predleaf =  predleaf
      , predcontrib =  predcontrib
      , header = header
      , reshape = reshape
816
      , params = params
817
    )
818
  )
Guolin Ke's avatar
Guolin Ke committed
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
#' @name print.lgb.Booster
#' @title Print method for LightGBM model
#' @description Show summary information about a LightGBM model object (same as \code{summary}).
#' @param x Object of class \code{lgb.Booster}
#' @param ... Not used
#' @return The same input `x`, returned as invisible.
#' @export
print.lgb.Booster <- function(x, ...) {
  # nolint start
  handle <- x$.__enclos_env__$private$handle
  handle_is_null <- lgb.is.null.handle(handle)

  if (!handle_is_null) {
    ntrees <- x$current_iter()
    if (ntrees == 1L) {
      cat("LightGBM Model (1 tree)\n")
    } else {
      cat(sprintf("LightGBM Model (%d trees)\n", ntrees))
    }
  } else {
    cat("LightGBM Model\n")
  }

  if (!handle_is_null) {
    obj <- x$params$objective
    if (obj == "none") {
      obj <- "custom"
    }
849
850
    num_class <- x$.__enclos_env__$private$num_class
    if (num_class == 1L) {
851
852
853
854
      cat(sprintf("Objective: %s\n", obj))
    } else {
      cat(sprintf("Objective: %s (%d classes)\n"
          , obj
855
          , num_class))
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
    }
  } else {
    cat("(Booster handle is invalid)\n")
  }

  if (!handle_is_null) {
    ncols <- .Call(LGBM_BoosterGetNumFeature_R, handle)
    cat(sprintf("Fitted to dataset with %d columns\n", ncols))
  }
  # nolint end

  return(invisible(x))
}

#' @name summary.lgb.Booster
#' @title Summary method for LightGBM model
#' @description Show summary information about a LightGBM model object (same as \code{print}).
#' @param object Object of class \code{lgb.Booster}
#' @param ... Not used
#' @return The same input `object`, returned as invisible.
#' @export
summary.lgb.Booster <- function(object, ...) {
  print(object)
}

881
882
#' @name lgb.load
#' @title Load LightGBM model
883
884
#' @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
885
#' @param filename path of model file
886
#' @param model_str a str containing the model (as a `character` or `raw` vector)
887
#'
888
#' @return lgb.Booster
889
#'
Guolin Ke's avatar
Guolin Ke committed
890
#' @examples
891
#' \donttest{
892
893
894
895
896
897
#' 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)
898
899
900
901
902
903
#' params <- list(
#'   objective = "regression"
#'   , metric = "l2"
#'   , min_data = 1L
#'   , learning_rate = 1.0
#' )
904
#' valids <- list(test = dtest)
905
906
907
#' model <- lgb.train(
#'   params = params
#'   , data = dtrain
908
#'   , nrounds = 5L
909
#'   , valids = valids
910
#'   , early_stopping_rounds = 3L
911
#' )
912
913
914
#' model_file <- tempfile(fileext = ".txt")
#' lgb.save(model, model_file)
#' load_booster <- lgb.load(filename = model_file)
915
916
#' model_string <- model$save_model_to_string(NULL) # saves best iteration
#' load_booster_from_str <- lgb.load(model_str = model_string)
917
#' }
Guolin Ke's avatar
Guolin Ke committed
918
#' @export
919
lgb.load <- function(filename = NULL, model_str = NULL) {
920

921
922
  filename_provided <- !is.null(filename)
  model_str_provided <- !is.null(model_str)
923

924
925
926
927
  if (filename_provided) {
    if (!is.character(filename)) {
      stop("lgb.load: filename should be character")
    }
928
    filename <- path.expand(filename)
929
930
931
    if (!file.exists(filename)) {
      stop(sprintf("lgb.load: file '%s' passed to filename does not exist", filename))
    }
932
933
    return(invisible(Booster$new(modelfile = filename)))
  }
934

935
  if (model_str_provided) {
936
937
    if (!is.raw(model_str) && !is.character(model_str)) {
      stop("lgb.load: model_str should be a character/raw vector")
938
    }
939
940
    return(invisible(Booster$new(model_str = model_str)))
  }
941

942
  stop("lgb.load: either filename or model_str must be given")
Guolin Ke's avatar
Guolin Ke committed
943
944
}

945
946
947
#' @name lgb.save
#' @title Save LightGBM model
#' @description Save LightGBM model
Guolin Ke's avatar
Guolin Ke committed
948
949
950
#' @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
951
#'
952
#' @return lgb.Booster
953
#'
Guolin Ke's avatar
Guolin Ke committed
954
#' @examples
955
#' \donttest{
956
957
958
959
960
961
962
#' 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)
963
964
965
966
967
968
#' params <- list(
#'   objective = "regression"
#'   , metric = "l2"
#'   , min_data = 1L
#'   , learning_rate = 1.0
#' )
969
#' valids <- list(test = dtest)
970
971
972
#' model <- lgb.train(
#'   params = params
#'   , data = dtrain
973
#'   , nrounds = 10L
974
#'   , valids = valids
975
#'   , early_stopping_rounds = 5L
976
#' )
977
#' lgb.save(model, tempfile(fileext = ".txt"))
978
#' }
Guolin Ke's avatar
Guolin Ke committed
979
#' @export
980
lgb.save <- function(booster, filename, num_iteration = NULL) {
981

982
  if (!lgb.is.Booster(x = booster)) {
983
984
    stop("lgb.save: booster should be an ", sQuote("lgb.Booster"))
  }
985

986
987
  if (!(is.character(filename) && length(filename) == 1L)) {
    stop("lgb.save: filename should be a string")
988
  }
989
  filename <- path.expand(filename)
990

991
  # Store booster
992
993
994
995
996
997
  return(
    invisible(booster$save_model(
      filename = filename
      , num_iteration = num_iteration
    ))
  )
998

Guolin Ke's avatar
Guolin Ke committed
999
1000
}

1001
1002
1003
#' @name lgb.dump
#' @title Dump LightGBM model to json
#' @description Dump LightGBM model to json
Guolin Ke's avatar
Guolin Ke committed
1004
1005
#' @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
1006
#'
Guolin Ke's avatar
Guolin Ke committed
1007
#' @return json format of model
1008
#'
Guolin Ke's avatar
Guolin Ke committed
1009
#' @examples
1010
#' \donttest{
1011
1012
1013
1014
1015
1016
1017
#' 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)
1018
1019
1020
1021
1022
1023
#' params <- list(
#'   objective = "regression"
#'   , metric = "l2"
#'   , min_data = 1L
#'   , learning_rate = 1.0
#' )
1024
#' valids <- list(test = dtest)
1025
1026
1027
#' model <- lgb.train(
#'   params = params
#'   , data = dtrain
1028
#'   , nrounds = 10L
1029
#'   , valids = valids
1030
#'   , early_stopping_rounds = 5L
1031
#' )
1032
#' json_model <- lgb.dump(model)
1033
#' }
Guolin Ke's avatar
Guolin Ke committed
1034
#' @export
1035
lgb.dump <- function(booster, num_iteration = NULL) {
1036

1037
  if (!lgb.is.Booster(x = booster)) {
1038
1039
    stop("lgb.save: booster should be an ", sQuote("lgb.Booster"))
  }
1040

1041
  # Return booster at requested iteration
1042
  return(booster$dump_model(num_iteration =  num_iteration))
1043

Guolin Ke's avatar
Guolin Ke committed
1044
1045
}

1046
1047
#' @name lgb.get.eval.result
#' @title Get record evaluation result from booster
1048
1049
#' @description Given a \code{lgb.Booster}, return evaluation results for a
#'              particular metric on a particular dataset.
Guolin Ke's avatar
Guolin Ke committed
1050
#' @param booster Object of class \code{lgb.Booster}
1051
1052
1053
1054
#' @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
1055
#' @param is_err TRUE will return evaluation error instead
1056
#'
1057
#' @return numeric vector of evaluation result
1058
#'
1059
#' @examples
1060
#' \donttest{
1061
#' # train a regression model
1062
1063
1064
1065
1066
1067
#' 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)
1068
1069
1070
1071
1072
1073
#' params <- list(
#'   objective = "regression"
#'   , metric = "l2"
#'   , min_data = 1L
#'   , learning_rate = 1.0
#' )
1074
#' valids <- list(test = dtest)
1075
1076
1077
#' model <- lgb.train(
#'   params = params
#'   , data = dtrain
1078
#'   , nrounds = 5L
1079
1080
#'   , valids = valids
#' )
1081
1082
1083
1084
1085
1086
1087
1088
#'
#' # 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
1089
#' lgb.get.eval.result(model, "test", "l2")
1090
#' }
Guolin Ke's avatar
Guolin Ke committed
1091
#' @export
1092
lgb.get.eval.result <- function(booster, data_name, eval_name, iters = NULL, is_err = FALSE) {
1093

1094
  if (!lgb.is.Booster(x = booster)) {
1095
    stop("lgb.get.eval.result: Can only use ", sQuote("lgb.Booster"), " to get eval result")
Guolin Ke's avatar
Guolin Ke committed
1096
  }
1097

1098
1099
  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
1100
  }
1101

1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
  # 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
1112
  }
1113

1114
  # Check if evaluation result is existing
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
  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
1126
1127
    stop("lgb.get.eval.result: wrong eval name")
  }
1128

1129
  result <- booster$record_evals[[data_name]][[eval_name]][[.EVAL_KEY()]]
1130

1131
  # Check if error is requested
1132
  if (is_err) {
1133
    result <- booster$record_evals[[data_name]][[eval_name]][[.EVAL_ERR_KEY()]]
Guolin Ke's avatar
Guolin Ke committed
1134
  }
1135

1136
  if (is.null(iters)) {
Guolin Ke's avatar
Guolin Ke committed
1137
1138
    return(as.numeric(result))
  }
1139

1140
  # Parse iteration and booster delta
Guolin Ke's avatar
Guolin Ke committed
1141
  iters <- as.integer(iters)
1142
  delta <- booster$record_evals$start_iter - 1.0
Guolin Ke's avatar
Guolin Ke committed
1143
  iters <- iters - delta
1144

1145
  return(as.numeric(result[iters]))
Guolin Ke's avatar
Guolin Ke committed
1146
}