lgb.Booster.R 28 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_,
9
    params = list(),
Guolin Ke's avatar
Guolin Ke committed
10
    record_evals = list(),
11

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

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

29
30
      # Create parameters and handle
      params <- append(params, list(...))
31
      handle <- NULL
32

33
34
      # Attempts to create a handle for the dataset
      try({
35

36
37
38
        # Check if training dataset is not null
        if (!is.null(train_set)) {
          # Check if training dataset is lgb.Dataset or not
39
          if (!lgb.is.Dataset(train_set)) {
40
41
            stop("lgb.Booster: Can only use lgb.Dataset as training data")
          }
42
43
          train_set_handle <- train_set$.__enclos_env__$private$get_handle()
          params <- modifyList(params, train_set$get_params())
44
          params_str <- lgb.params2str(params = params)
45
          # Store booster handle
46
          handle <- .Call(
47
            LGBM_BoosterCreate_R
48
            , train_set_handle
49
50
            , params_str
          )
51

52
53
          # Create private booster information
          private$train_set <- train_set
54
          private$train_set_version <- train_set$.__enclos_env__$private$version
55
          private$num_dataset <- 1L
56
          private$init_predictor <- train_set$.__enclos_env__$private$predictor
57

58
59
          # Check if predictor is existing
          if (!is.null(private$init_predictor)) {
60

61
            # Merge booster
62
63
            .Call(
              LGBM_BoosterMerge_R
64
65
66
              , handle
              , private$init_predictor$.__enclos_env__$private$handle
            )
67

68
          }
69

70
71
          # Check current iteration
          private$is_predicted_cur_iter <- c(private$is_predicted_cur_iter, FALSE)
72

73
        } else if (!is.null(modelfile)) {
74

75
76
77
78
          # Do we have a model file as character?
          if (!is.character(modelfile)) {
            stop("lgb.Booster: Can only use a string as model file path")
          }
79

80
          # Create booster from model
81
          handle <- .Call(
82
            LGBM_BoosterCreateFromModelfile_R
83
            , modelfile
84
          )
85

86
        } else if (!is.null(model_str)) {
87

88
          # Do we have a model_str as character?
89
90
91
          if (!is.character(model_str)) {
            stop("lgb.Booster: Can only use a string as model_str")
          }
92

93
          # Create booster from model
94
          handle <- .Call(
95
            LGBM_BoosterLoadModelFromString_R
96
            , model_str
97
          )
98

99
        } else {
100

101
          # Booster non existent
102
103
104
105
          stop(
            "lgb.Booster: Need at least either training dataset, "
            , "model file, or model_str to create booster instance"
          )
106

107
        }
108

109
      })
110

111
      # Check whether the handle was created properly if it was not stopped earlier by a stop call
112
      if (isTRUE(lgb.is.null.handle(x = handle))) {
113

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

Guolin Ke's avatar
Guolin Ke committed
116
      } else {
117

Guolin Ke's avatar
Guolin Ke committed
118
119
120
121
        # Create class
        class(handle) <- "lgb.Booster.handle"
        private$handle <- handle
        private$num_class <- 1L
122
123
        .Call(
          LGBM_BoosterGetNumClasses_R
124
          , private$handle
125
          , private$num_class
126
        )
127

Guolin Ke's avatar
Guolin Ke committed
128
      }
129

130
131
      self$params <- params

132
133
      return(invisible(NULL))

Guolin Ke's avatar
Guolin Ke committed
134
    },
135

136
    # Set training data name
Guolin Ke's avatar
Guolin Ke committed
137
    set_train_data_name = function(name) {
138

139
      # Set name
Guolin Ke's avatar
Guolin Ke committed
140
      private$name_train_set <- name
141
      return(invisible(self))
142

Guolin Ke's avatar
Guolin Ke committed
143
    },
144

145
    # Add validation data
Guolin Ke's avatar
Guolin Ke committed
146
    add_valid = function(data, name) {
147

148
      if (!lgb.is.Dataset(data)) {
149
        stop("lgb.Booster.add_valid: Can only use lgb.Dataset as validation data")
Guolin Ke's avatar
Guolin Ke committed
150
      }
151

Guolin Ke's avatar
Guolin Ke committed
152
      if (!identical(data$.__enclos_env__$private$predictor, private$init_predictor)) {
153
154
155
156
        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
157
      }
158

159
160
      if (!is.character(name)) {
        stop("lgb.Booster.add_valid: Can only use characters as data name")
Guolin Ke's avatar
Guolin Ke committed
161
      }
162

163
      # Add validation data to booster
164
165
      .Call(
        LGBM_BoosterAddValidData_R
166
167
168
        , private$handle
        , data$.__enclos_env__$private$get_handle()
      )
169

170
171
      private$valid_sets <- c(private$valid_sets, data)
      private$name_valid_sets <- c(private$name_valid_sets, name)
172
      private$num_dataset <- private$num_dataset + 1L
173
      private$is_predicted_cur_iter <- c(private$is_predicted_cur_iter, FALSE)
174

175
      return(invisible(self))
176

Guolin Ke's avatar
Guolin Ke committed
177
    },
178

Guolin Ke's avatar
Guolin Ke committed
179
    reset_parameter = function(params, ...) {
180

181
182
183
184
185
      if (methods::is(self$params, "list")) {
        params <- modifyList(self$params, params)
      }

      params <- modifyList(params, list(...))
186
      params_str <- lgb.params2str(params = params)
187

188
189
      .Call(
        LGBM_BoosterResetParameter_R
190
191
192
        , private$handle
        , params_str
      )
193
      self$params <- params
194

195
      return(invisible(self))
196

Guolin Ke's avatar
Guolin Ke committed
197
    },
198

199
    # Perform boosting update iteration
Guolin Ke's avatar
Guolin Ke committed
200
    update = function(train_set = NULL, fobj = NULL) {
201

202
203
204
205
206
207
      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
208
      if (!is.null(train_set)) {
209

210
        if (!lgb.is.Dataset(train_set)) {
Guolin Ke's avatar
Guolin Ke committed
211
212
          stop("lgb.Booster.update: Only can use lgb.Dataset as training data")
        }
213

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

218
219
        .Call(
          LGBM_BoosterResetTrainingData_R
220
221
222
          , private$handle
          , train_set$.__enclos_env__$private$get_handle()
        )
223

224
        private$train_set <- train_set
225
        private$train_set_version <- train_set$.__enclos_env__$private$version
226

Guolin Ke's avatar
Guolin Ke committed
227
      }
228

229
      # Check if objective is empty
Guolin Ke's avatar
Guolin Ke committed
230
      if (is.null(fobj)) {
231
232
233
        if (private$set_objective_to_none) {
          stop("lgb.Booster.update: cannot update due to null objective function")
        }
234
        # Boost iteration from known objective
235
236
        .Call(
          LGBM_BoosterUpdateOneIter_R
237
238
          , private$handle
        )
239

Guolin Ke's avatar
Guolin Ke committed
240
      } else {
241

242
243
244
        if (!is.function(fobj)) {
          stop("lgb.Booster.update: fobj should be a function")
        }
245
        if (!private$set_objective_to_none) {
246
          self$reset_parameter(params = list(objective = "none"))
247
          private$set_objective_to_none <- TRUE
248
        }
249
        # Perform objective calculation
250
        gpair <- fobj(private$inner_predict(1L), private$train_set)
251

252
        # Check for gradient and hessian as list
253
        if (is.null(gpair$grad) || is.null(gpair$hess)) {
254
          stop("lgb.Booster.update: custom objective should
255
256
            return a list with attributes (hess, grad)")
        }
257

258
        # Return custom boosting gradient/hessian
259
260
        .Call(
          LGBM_BoosterUpdateOneIterCustom_R
261
262
263
264
265
          , private$handle
          , gpair$grad
          , gpair$hess
          , length(gpair$grad)
        )
266

Guolin Ke's avatar
Guolin Ke committed
267
      }
268

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

274
      return(invisible(self))
275

Guolin Ke's avatar
Guolin Ke committed
276
    },
277

278
    # Return one iteration behind
Guolin Ke's avatar
Guolin Ke committed
279
    rollback_one_iter = function() {
280

281
282
      .Call(
        LGBM_BoosterRollbackOneIter_R
283
284
        , private$handle
      )
285

286
      # Loop through each iteration
287
      for (i in seq_along(private$is_predicted_cur_iter)) {
Guolin Ke's avatar
Guolin Ke committed
288
289
        private$is_predicted_cur_iter[[i]] <- FALSE
      }
290

291
      return(invisible(self))
292

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

295
    # Get current iteration
Guolin Ke's avatar
Guolin Ke committed
296
    current_iter = function() {
297

298
      cur_iter <- 0L
299
300
301
302
      .Call(
        LGBM_BoosterGetCurrentIteration_R
        , private$handle
        , cur_iter
303
      )
304
      return(cur_iter)
305

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

308
    # Get upper bound
309
    upper_bound = function() {
310

311
      upper_bound <- 0.0
312
313
314
315
      .Call(
        LGBM_BoosterGetUpperBoundValue_R
        , private$handle
        , upper_bound
316
      )
317
      return(upper_bound)
318
319
320
321

    },

    # Get lower bound
322
    lower_bound = function() {
323

324
      lower_bound <- 0.0
325
326
327
328
      .Call(
        LGBM_BoosterGetLowerBoundValue_R
        , private$handle
        , lower_bound
329
      )
330
      return(lower_bound)
331
332
333

    },

334
    # Evaluate data on metrics
Guolin Ke's avatar
Guolin Ke committed
335
    eval = function(data, name, feval = NULL) {
336

337
      if (!lgb.is.Dataset(data)) {
338
        stop("lgb.Booster.eval: Can only use lgb.Dataset to eval")
Guolin Ke's avatar
Guolin Ke committed
339
      }
340

341
      # Check for identical data
342
      data_idx <- 0L
343
      if (identical(data, private$train_set)) {
344
        data_idx <- 1L
345
      } else {
346

347
        # Check for validation data
348
        if (length(private$valid_sets) > 0L) {
349

350
          for (i in seq_along(private$valid_sets)) {
351

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

355
              # Found identical data, skip
356
              data_idx <- i + 1L
Guolin Ke's avatar
Guolin Ke committed
357
              break
358

Guolin Ke's avatar
Guolin Ke committed
359
            }
360

Guolin Ke's avatar
Guolin Ke committed
361
          }
362

Guolin Ke's avatar
Guolin Ke committed
363
        }
364

Guolin Ke's avatar
Guolin Ke committed
365
      }
366

367
      # Check if evaluation was not done
368
      if (data_idx == 0L) {
369

370
        # Add validation data by name
Guolin Ke's avatar
Guolin Ke committed
371
372
        self$add_valid(data, name)
        data_idx <- private$num_dataset
373

Guolin Ke's avatar
Guolin Ke committed
374
      }
375

376
      # Evaluate data
377
378
379
380
381
382
      return(
        private$inner_eval(
          data_name = name
          , data_idx = data_idx
          , feval = feval
        )
383
      )
384

Guolin Ke's avatar
Guolin Ke committed
385
    },
386

387
    # Evaluation training data
Guolin Ke's avatar
Guolin Ke committed
388
    eval_train = function(feval = NULL) {
389
      return(private$inner_eval(private$name_train_set, 1L, feval))
Guolin Ke's avatar
Guolin Ke committed
390
    },
391

392
    # Evaluation validation data
Guolin Ke's avatar
Guolin Ke committed
393
    eval_valid = function(feval = NULL) {
394

395
      ret <- list()
396

397
      if (length(private$valid_sets) <= 0L) {
398
399
        return(ret)
      }
400

401
      for (i in seq_along(private$valid_sets)) {
402
403
        ret <- append(
          x = ret
404
          , values = private$inner_eval(private$name_valid_sets[[i]], i + 1L, feval)
405
        )
Guolin Ke's avatar
Guolin Ke committed
406
      }
407

408
      return(ret)
409

Guolin Ke's avatar
Guolin Ke committed
410
    },
411

412
    # Save model
413
    save_model = function(filename, num_iteration = NULL, feature_importance_type = 0L) {
414

415
416
417
      if (is.null(num_iteration)) {
        num_iteration <- self$best_iter
      }
418

419
420
      .Call(
        LGBM_BoosterSaveModel_R
421
422
        , private$handle
        , as.integer(num_iteration)
423
        , as.integer(feature_importance_type)
424
        , filename
425
      )
426

427
      return(invisible(self))
Guolin Ke's avatar
Guolin Ke committed
428
    },
429

430
    save_model_to_string = function(num_iteration = NULL, feature_importance_type = 0L) {
431

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

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

443
      return(model_str)
444

445
    },
446

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

450
451
452
      if (is.null(num_iteration)) {
        num_iteration <- self$best_iter
      }
453

454
      model_str <- .Call(
455
456
457
458
459
460
        LGBM_BoosterDumpModel_R
        , private$handle
        , as.integer(num_iteration)
        , as.integer(feature_importance_type)
      )

461
      return(model_str)
462

Guolin Ke's avatar
Guolin Ke committed
463
    },
464

465
    # Predict on new data
Guolin Ke's avatar
Guolin Ke committed
466
    predict = function(data,
467
                       start_iteration = NULL,
468
469
470
                       num_iteration = NULL,
                       rawscore = FALSE,
                       predleaf = FALSE,
471
                       predcontrib = FALSE,
472
                       header = FALSE,
473
474
                       reshape = FALSE,
                       ...) {
475

476
477
478
      if (is.null(num_iteration)) {
        num_iteration <- self$best_iter
      }
479

480
481
482
      if (is.null(start_iteration)) {
        start_iteration <- 0L
      }
483

484
      # Predict on new data
485
486
487
488
489
      params <- list(...)
      predictor <- Predictor$new(
        modelfile = private$handle
        , params = params
      )
490
491
      return(
        predictor$predict(
492
493
494
495
496
497
498
499
          data = data
          , start_iteration = start_iteration
          , num_iteration = num_iteration
          , rawscore = rawscore
          , predleaf = predleaf
          , predcontrib = predcontrib
          , header = header
          , reshape = reshape
500
        )
501
      )
502

503
    },
504

505
506
    # Transform into predictor
    to_predictor = function() {
507
      return(Predictor$new(modelfile = private$handle))
Guolin Ke's avatar
Guolin Ke committed
508
    },
509

510
    # Used for save
511
    raw = NA,
512

513
    # Save model to temporary file for in-memory saving
514
    save = function() {
515

516
      # Overwrite model in object
517
      self$raw <- self$save_model_to_string(NULL)
518

519
520
      return(invisible(NULL))

521
    }
522

Guolin Ke's avatar
Guolin Ke committed
523
524
  ),
  private = list(
525
526
527
528
529
530
531
    handle = NULL,
    train_set = NULL,
    name_train_set = "training",
    valid_sets = list(),
    name_valid_sets = list(),
    predict_buffer = list(),
    is_predicted_cur_iter = list(),
532
533
    num_class = 1L,
    num_dataset = 0L,
534
535
    init_predictor = NULL,
    eval_names = NULL,
Guolin Ke's avatar
Guolin Ke committed
536
    higher_better_inner_eval = NULL,
537
    set_objective_to_none = FALSE,
538
    train_set_version = 0L,
539
540
    # Predict data
    inner_predict = function(idx) {
541

542
      # Store data name
Guolin Ke's avatar
Guolin Ke committed
543
      data_name <- private$name_train_set
544

545
546
      if (idx > 1L) {
        data_name <- private$name_valid_sets[[idx - 1L]]
547
      }
548

549
      # Check for unknown dataset (over the maximum provided range)
Guolin Ke's avatar
Guolin Ke committed
550
551
552
      if (idx > private$num_dataset) {
        stop("data_idx should not be greater than num_dataset")
      }
553

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

557
        # Store predictions
558
        npred <- 0L
559
560
        .Call(
          LGBM_BoosterGetNumPredict_R
561
          , private$handle
562
          , as.integer(idx - 1L)
563
          , npred
564
        )
565
        private$predict_buffer[[data_name]] <- numeric(npred)
566

Guolin Ke's avatar
Guolin Ke committed
567
      }
568

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

572
        # Use buffer
573
574
        .Call(
          LGBM_BoosterGetPredict_R
575
          , private$handle
576
          , as.integer(idx - 1L)
577
          , private$predict_buffer[[data_name]]
578
        )
Guolin Ke's avatar
Guolin Ke committed
579
580
        private$is_predicted_cur_iter[[idx]] <- TRUE
      }
581

582
      return(private$predict_buffer[[data_name]])
Guolin Ke's avatar
Guolin Ke committed
583
    },
584

585
    # Get evaluation information
Guolin Ke's avatar
Guolin Ke committed
586
    get_eval_info = function() {
587

Guolin Ke's avatar
Guolin Ke committed
588
      if (is.null(private$eval_names)) {
589
        eval_names <- .Call(
590
          LGBM_BoosterGetEvalNames_R
591
592
          , private$handle
        )
593

594
        if (length(eval_names) > 0L) {
595

596
          # Parse and store privately names
597
          private$eval_names <- eval_names
598
599
600

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

Guolin Ke's avatar
Guolin Ke committed
604
        }
605

Guolin Ke's avatar
Guolin Ke committed
606
      }
607

608
      return(private$eval_names)
609

Guolin Ke's avatar
Guolin Ke committed
610
    },
611

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

614
      # Check for unknown dataset (over the maximum provided range)
Guolin Ke's avatar
Guolin Ke committed
615
616
617
      if (data_idx > private$num_dataset) {
        stop("data_idx should not be greater than num_dataset")
      }
618

Guolin Ke's avatar
Guolin Ke committed
619
      private$get_eval_info()
620

Guolin Ke's avatar
Guolin Ke committed
621
      ret <- list()
622

623
      if (length(private$eval_names) > 0L) {
624

625
626
        # Create evaluation values
        tmp_vals <- numeric(length(private$eval_names))
627
628
        .Call(
          LGBM_BoosterGetEval_R
629
          , private$handle
630
          , as.integer(data_idx - 1L)
631
          , tmp_vals
632
        )
633

634
        for (i in seq_along(private$eval_names)) {
635

636
637
638
639
640
          # 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
641
          res$higher_better <- private$higher_better_inner_eval[i]
642
          ret <- append(ret, list(res))
643

Guolin Ke's avatar
Guolin Ke committed
644
        }
645

Guolin Ke's avatar
Guolin Ke committed
646
      }
647

648
      # Check if there are evaluation metrics
Guolin Ke's avatar
Guolin Ke committed
649
      if (!is.null(feval)) {
650

651
        # Check if evaluation metric is a function
652
        if (!is.function(feval)) {
Guolin Ke's avatar
Guolin Ke committed
653
654
          stop("lgb.Booster.eval: feval should be a function")
        }
655

Guolin Ke's avatar
Guolin Ke committed
656
        data <- private$train_set
657

658
        # Check if data to assess is existing differently
659
660
        if (data_idx > 1L) {
          data <- private$valid_sets[[data_idx - 1L]]
661
        }
662

663
        # Perform function evaluation
664
        res <- feval(private$inner_predict(data_idx), data)
665

666
        if (is.null(res$name) || is.null(res$value) ||  is.null(res$higher_better)) {
667
          stop("lgb.Booster.eval: custom eval function should return a
668
669
            list with attribute (name, value, higher_better)");
        }
670

671
        # Append names and evaluation
Guolin Ke's avatar
Guolin Ke committed
672
        res$data_name <- data_name
673
        ret <- append(ret, list(res))
Guolin Ke's avatar
Guolin Ke committed
674
      }
675

676
      return(ret)
677

Guolin Ke's avatar
Guolin Ke committed
678
    }
679

Guolin Ke's avatar
Guolin Ke committed
680
681
682
  )
)

683
684
685
#' @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
686
687
#' @param object Object of class \code{lgb.Booster}
#' @param data a \code{matrix} object, a \code{dgCMatrix} object or a character representing a filename
688
689
690
691
692
693
694
695
#' @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).
696
#' @param rawscore whether the prediction should be returned in the for of original untransformed
697
698
#'                 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.
699
#' @param predleaf whether predict leaf index instead.
700
#' @param predcontrib return per-feature contributions for each record.
Guolin Ke's avatar
Guolin Ke committed
701
#' @param header only used for prediction for text file. True if text file has header
702
#' @param reshape whether to reshape the vector of predictions to a matrix form when there are several
703
#'                prediction outputs per case.
James Lamb's avatar
James Lamb committed
704
705
#' @param ... Additional named arguments passed to the \code{predict()} method of
#'            the \code{lgb.Booster} object passed to \code{object}.
706
707
708
709
#' @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.
710
#'
711
712
#'         When \code{predleaf = TRUE}, the output is a matrix object with the
#'         number of columns corresponding to the number of trees.
713
#'
Guolin Ke's avatar
Guolin Ke committed
714
#' @examples
715
#' \donttest{
716
717
718
719
720
721
722
723
#' 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)
724
725
726
#' model <- lgb.train(
#'   params = params
#'   , data = dtrain
727
#'   , nrounds = 5L
728
#'   , valids = valids
729
730
#'   , min_data = 1L
#'   , learning_rate = 1.0
731
#' )
732
#' preds <- predict(model, test$data)
733
#' }
Guolin Ke's avatar
Guolin Ke committed
734
#' @export
James Lamb's avatar
James Lamb committed
735
736
predict.lgb.Booster <- function(object,
                                data,
737
                                start_iteration = NULL,
James Lamb's avatar
James Lamb committed
738
739
740
741
742
                                num_iteration = NULL,
                                rawscore = FALSE,
                                predleaf = FALSE,
                                predcontrib = FALSE,
                                header = FALSE,
743
                                reshape = FALSE,
James Lamb's avatar
James Lamb committed
744
                                ...) {
745

746
  if (!lgb.is.Booster(x = object)) {
747
    stop("predict.lgb.Booster: object should be an ", sQuote("lgb.Booster"))
Guolin Ke's avatar
Guolin Ke committed
748
  }
749

750
751
752
  return(
    object$predict(
      data = data
753
754
755
756
757
758
759
      , start_iteration = start_iteration
      , num_iteration = num_iteration
      , rawscore = rawscore
      , predleaf =  predleaf
      , predcontrib =  predcontrib
      , header = header
      , reshape = reshape
760
761
      , ...
    )
762
  )
Guolin Ke's avatar
Guolin Ke committed
763
764
}

765
766
#' @name lgb.load
#' @title Load LightGBM model
767
768
#' @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
769
#' @param filename path of model file
770
#' @param model_str a str containing the model
771
#'
772
#' @return lgb.Booster
773
#'
Guolin Ke's avatar
Guolin Ke committed
774
#' @examples
775
#' \donttest{
776
777
778
779
780
781
782
783
#' 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)
784
785
786
#' model <- lgb.train(
#'   params = params
#'   , data = dtrain
787
#'   , nrounds = 5L
788
#'   , valids = valids
789
790
#'   , min_data = 1L
#'   , learning_rate = 1.0
791
#'   , early_stopping_rounds = 3L
792
#' )
793
794
795
#' model_file <- tempfile(fileext = ".txt")
#' lgb.save(model, model_file)
#' load_booster <- lgb.load(filename = model_file)
796
797
#' model_string <- model$save_model_to_string(NULL) # saves best iteration
#' load_booster_from_str <- lgb.load(model_str = model_string)
798
#' }
Guolin Ke's avatar
Guolin Ke committed
799
#' @export
800
lgb.load <- function(filename = NULL, model_str = NULL) {
801

802
803
  filename_provided <- !is.null(filename)
  model_str_provided <- !is.null(model_str)
804

805
806
807
808
809
810
811
  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))
    }
812
813
    return(invisible(Booster$new(modelfile = filename)))
  }
814

815
816
817
818
  if (model_str_provided) {
    if (!is.character(model_str)) {
      stop("lgb.load: model_str should be character")
    }
819
820
    return(invisible(Booster$new(model_str = model_str)))
  }
821

822
  stop("lgb.load: either filename or model_str must be given")
Guolin Ke's avatar
Guolin Ke committed
823
824
}

825
826
827
#' @name lgb.save
#' @title Save LightGBM model
#' @description Save LightGBM model
Guolin Ke's avatar
Guolin Ke committed
828
829
830
#' @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
831
#'
832
#' @return lgb.Booster
833
#'
Guolin Ke's avatar
Guolin Ke committed
834
#' @examples
835
#' \donttest{
836
837
838
839
840
841
842
843
844
#' 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)
845
846
847
#' model <- lgb.train(
#'   params = params
#'   , data = dtrain
848
#'   , nrounds = 10L
849
#'   , valids = valids
850
851
852
#'   , min_data = 1L
#'   , learning_rate = 1.0
#'   , early_stopping_rounds = 5L
853
#' )
854
#' lgb.save(model, tempfile(fileext = ".txt"))
855
#' }
Guolin Ke's avatar
Guolin Ke committed
856
#' @export
857
lgb.save <- function(booster, filename, num_iteration = NULL) {
858

859
  if (!lgb.is.Booster(x = booster)) {
860
861
    stop("lgb.save: booster should be an ", sQuote("lgb.Booster"))
  }
862

863
864
  if (!(is.character(filename) && length(filename) == 1L)) {
    stop("lgb.save: filename should be a string")
865
  }
866

867
  # Store booster
868
869
870
871
872
873
  return(
    invisible(booster$save_model(
      filename = filename
      , num_iteration = num_iteration
    ))
  )
874

Guolin Ke's avatar
Guolin Ke committed
875
876
}

877
878
879
#' @name lgb.dump
#' @title Dump LightGBM model to json
#' @description Dump LightGBM model to json
Guolin Ke's avatar
Guolin Ke committed
880
881
#' @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
882
#'
Guolin Ke's avatar
Guolin Ke committed
883
#' @return json format of model
884
#'
Guolin Ke's avatar
Guolin Ke committed
885
#' @examples
886
#' \donttest{
887
888
889
890
891
892
893
894
895
#' 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)
896
897
898
#' model <- lgb.train(
#'   params = params
#'   , data = dtrain
899
#'   , nrounds = 10L
900
#'   , valids = valids
901
902
903
#'   , min_data = 1L
#'   , learning_rate = 1.0
#'   , early_stopping_rounds = 5L
904
#' )
905
#' json_model <- lgb.dump(model)
906
#' }
Guolin Ke's avatar
Guolin Ke committed
907
#' @export
908
lgb.dump <- function(booster, num_iteration = NULL) {
909

910
  if (!lgb.is.Booster(x = booster)) {
911
912
    stop("lgb.save: booster should be an ", sQuote("lgb.Booster"))
  }
913

914
  # Return booster at requested iteration
915
  return(booster$dump_model(num_iteration =  num_iteration))
916

Guolin Ke's avatar
Guolin Ke committed
917
918
}

919
920
#' @name lgb.get.eval.result
#' @title Get record evaluation result from booster
921
922
#' @description Given a \code{lgb.Booster}, return evaluation results for a
#'              particular metric on a particular dataset.
Guolin Ke's avatar
Guolin Ke committed
923
#' @param booster Object of class \code{lgb.Booster}
924
925
926
927
#' @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
928
#' @param is_err TRUE will return evaluation error instead
929
#'
930
#' @return numeric vector of evaluation result
931
#'
932
#' @examples
933
#' \donttest{
934
#' # train a regression model
935
936
937
938
939
940
941
942
#' 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)
943
944
945
#' model <- lgb.train(
#'   params = params
#'   , data = dtrain
946
#'   , nrounds = 5L
947
#'   , valids = valids
948
949
#'   , min_data = 1L
#'   , learning_rate = 1.0
950
#' )
951
952
953
954
955
956
957
958
#'
#' # 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
959
#' lgb.get.eval.result(model, "test", "l2")
960
#' }
Guolin Ke's avatar
Guolin Ke committed
961
#' @export
962
lgb.get.eval.result <- function(booster, data_name, eval_name, iters = NULL, is_err = FALSE) {
963

964
  if (!lgb.is.Booster(x = booster)) {
965
    stop("lgb.get.eval.result: Can only use ", sQuote("lgb.Booster"), " to get eval result")
Guolin Ke's avatar
Guolin Ke committed
966
  }
967

968
969
  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
970
  }
971

972
973
974
975
976
977
978
979
980
981
  # 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
982
  }
983

984
  # Check if evaluation result is existing
985
986
987
988
989
990
991
992
993
994
995
  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
996
997
    stop("lgb.get.eval.result: wrong eval name")
  }
998

999
  result <- booster$record_evals[[data_name]][[eval_name]][[.EVAL_KEY()]]
1000

1001
  # Check if error is requested
1002
  if (is_err) {
1003
    result <- booster$record_evals[[data_name]][[eval_name]][[.EVAL_ERR_KEY()]]
Guolin Ke's avatar
Guolin Ke committed
1004
  }
1005

1006
  if (is.null(iters)) {
Guolin Ke's avatar
Guolin Ke committed
1007
1008
    return(as.numeric(result))
  }
1009

1010
  # Parse iteration and booster delta
Guolin Ke's avatar
Guolin Ke committed
1011
  iters <- as.integer(iters)
1012
  delta <- booster$record_evals$start_iter - 1.0
Guolin Ke's avatar
Guolin Ke committed
1013
  iters <- iters - delta
1014

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