lgb.Booster.R 29.2 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
42
43
44
        # Check if training dataset is not null
        if (!is.null(train_set)) {
          # Check if training dataset is lgb.Dataset or not
          if (!lgb.check.r6.class(train_set, "lgb.Dataset")) {
            stop("lgb.Booster: Can only use lgb.Dataset as training data")
          }
45
46
47
          train_set_handle <- train_set$.__enclos_env__$private$get_handle()
          params <- modifyList(params, train_set$get_params())
          params_str <- lgb.params2str(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
87
88
89
90
          handle <- lgb.call(
            "LGBM_BoosterCreateFromModelfile_R"
            , 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
101
102
103
104
          handle <- lgb.call(
            "LGBM_BoosterLoadModelFromString_R"
            , 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
Guolin Ke's avatar
Guolin Ke committed
119
      if (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
130
131
132
133
        private$num_class <- lgb.call(
          "LGBM_BoosterGetNumClasses_R"
          , 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
Guolin Ke's avatar
Guolin Ke committed
152
      if (!lgb.check.r6.class(data, "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)
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
Guolin Ke's avatar
Guolin Ke committed
219
220
221
        if (!lgb.check.r6.class(train_set, "lgb.Dataset")) {
          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
271
272
273
274
275
276
277
        ret <- lgb.call(
          "LGBM_BoosterUpdateOneIterCustom_R"
          , 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
314
315
316
317
      lgb.call(
        "LGBM_BoosterGetCurrentIteration_R"
        , 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
326
327
328
329
330
331
332
333
      lgb.call(
        "LGBM_BoosterGetUpperBoundValue_R"
        , ret = upper_bound
        , private$handle
      )

    },

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

336
      lower_bound <- 0.0
337
338
      lgb.call(
        "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
Guolin Ke's avatar
Guolin Ke committed
349
      if (!lgb.check.r6.class(data, "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
      private$inner_eval(name, data_idx, feval)
391

Guolin Ke's avatar
Guolin Ke committed
392
    },
393

394
    # Evaluation training data
Guolin Ke's avatar
Guolin Ke committed
395
    eval_train = function(feval = NULL) {
396
      private$inner_eval(private$name_train_set, 1L, feval)
Guolin Ke's avatar
Guolin Ke committed
397
    },
398

399
    # Evaluation validation data
Guolin Ke's avatar
Guolin Ke committed
400
    eval_valid = function(feval = NULL) {
401

402
      # Create ret list
403
      ret <- list()
404

405
      # Check if validation is empty
406
      if (length(private$valid_sets) <= 0L) {
407
408
        return(ret)
      }
409

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

418
      return(ret)
419

Guolin Ke's avatar
Guolin Ke committed
420
    },
421

422
    # Save model
423
    save_model = function(filename, num_iteration = NULL, feature_importance_type = 0L) {
424

425
426
427
428
      # Check if number of iteration is non existent
      if (is.null(num_iteration)) {
        num_iteration <- self$best_iter
      }
429

430
      # Save booster model
431
432
433
434
435
      lgb.call(
        "LGBM_BoosterSaveModel_R"
        , ret = NULL
        , private$handle
        , as.integer(num_iteration)
436
        , as.integer(feature_importance_type)
437
438
        , lgb.c_str(filename)
      )
439

440
      return(invisible(self))
Guolin Ke's avatar
Guolin Ke committed
441
    },
442

443
    # Save model to string
444
    save_model_to_string = function(num_iteration = NULL, feature_importance_type = 0L) {
445

446
447
448
449
      # Check if number of iteration is non existent
      if (is.null(num_iteration)) {
        num_iteration <- self$best_iter
      }
450

451
      # Return model string
452
453
454
455
      return(lgb.call.return.str(
        "LGBM_BoosterSaveModelToString_R"
        , private$handle
        , as.integer(num_iteration)
456
        , as.integer(feature_importance_type)
457
      ))
458

459
    },
460

461
    # Dump model in memory
462
    dump_model = function(num_iteration = NULL, feature_importance_type = 0L) {
463

464
465
466
467
      # Check if number of iteration is non existent
      if (is.null(num_iteration)) {
        num_iteration <- self$best_iter
      }
468

469
470
471
472
      lgb.call.return.str(
        "LGBM_BoosterDumpModel_R"
        , private$handle
        , as.integer(num_iteration)
473
        , as.integer(feature_importance_type)
474
      )
475

Guolin Ke's avatar
Guolin Ke committed
476
    },
477

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

488
      # Check if number of iteration is non existent
489
490
491
      if (is.null(num_iteration)) {
        num_iteration <- self$best_iter
      }
492
      # Check if start iteration is non existent
493
494
495
      if (is.null(start_iteration)) {
        start_iteration <- 0L
      }
496

497
      # Predict on new data
498
      predictor <- Predictor$new(private$handle, ...)
499
      predictor$predict(data, start_iteration, num_iteration, rawscore, predleaf, predcontrib, header, reshape)
500

501
    },
502

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

508
    # Used for save
509
    raw = NA,
510

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

514
      # Overwrite model in object
515
      self$raw <- self$save_model_to_string(NULL)
516

517
    }
518

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

538
      # Store data name
Guolin Ke's avatar
Guolin Ke committed
539
      data_name <- private$name_train_set
540

541
      # Check for id bigger than 1
542
543
      if (idx > 1L) {
        data_name <- private$name_valid_sets[[idx - 1L]]
544
      }
545

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

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

554
        # Store predictions
555
        npred <- 0L
556
557
558
559
        npred <- lgb.call(
          "LGBM_BoosterGetNumPredict_R"
          , ret = npred
          , private$handle
560
          , as.integer(idx - 1L)
561
        )
562
        private$predict_buffer[[data_name]] <- numeric(npred)
563

Guolin Ke's avatar
Guolin Ke committed
564
      }
565

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

569
        # Use buffer
570
571
572
573
        private$predict_buffer[[data_name]] <- lgb.call(
          "LGBM_BoosterGetPredict_R"
          , ret = private$predict_buffer[[data_name]]
          , private$handle
574
          , as.integer(idx - 1L)
575
        )
Guolin Ke's avatar
Guolin Ke committed
576
577
        private$is_predicted_cur_iter[[idx]] <- TRUE
      }
578

579
      return(private$predict_buffer[[data_name]])
Guolin Ke's avatar
Guolin Ke committed
580
    },
581

582
    # Get evaluation information
Guolin Ke's avatar
Guolin Ke committed
583
    get_eval_info = function() {
584

585
      # Check for evaluation names emptiness
Guolin Ke's avatar
Guolin Ke committed
586
      if (is.null(private$eval_names)) {
587

588
        # Get evaluation names
589
590
591
592
        names <- lgb.call.return.str(
          "LGBM_BoosterGetEvalNames_R"
          , private$handle
        )
593

594
        # Check names' length
595
        if (nchar(names) > 0L) {
596

597
          # Parse and store privately names
598
          names <- strsplit(names, "\t")[[1L]]
Guolin Ke's avatar
Guolin Ke committed
599
          private$eval_names <- names
600
601
602
603
604

          # 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]
605

Guolin Ke's avatar
Guolin Ke committed
606
        }
607

Guolin Ke's avatar
Guolin Ke committed
608
      }
609

610
      return(private$eval_names)
611

Guolin Ke's avatar
Guolin Ke committed
612
    },
613

614
    # Perform inner evaluation
Guolin Ke's avatar
Guolin Ke committed
615
    inner_eval = function(data_name, data_idx, feval = NULL) {
616

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

622
      # Get evaluation information
Guolin Ke's avatar
Guolin Ke committed
623
      private$get_eval_info()
624

625
      # Prepare return
Guolin Ke's avatar
Guolin Ke committed
626
      ret <- list()
627

628
      # Check evaluation names existence
629
      if (length(private$eval_names) > 0L) {
630

631
632
        # Create evaluation values
        tmp_vals <- numeric(length(private$eval_names))
633
634
635
636
        tmp_vals <- lgb.call(
          "LGBM_BoosterGetEval_R"
          , ret = tmp_vals
          , private$handle
637
          , as.integer(data_idx - 1L)
638
        )
639

640
        # Loop through all evaluation names
641
        for (i in seq_along(private$eval_names)) {
642

643
644
645
646
647
          # 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
648
          res$higher_better <- private$higher_better_inner_eval[i]
649
          ret <- append(ret, list(res))
650

Guolin Ke's avatar
Guolin Ke committed
651
        }
652

Guolin Ke's avatar
Guolin Ke committed
653
      }
654

655
      # Check if there are evaluation metrics
Guolin Ke's avatar
Guolin Ke committed
656
      if (!is.null(feval)) {
657

658
        # Check if evaluation metric is a function
659
        if (!is.function(feval)) {
Guolin Ke's avatar
Guolin Ke committed
660
661
          stop("lgb.Booster.eval: feval should be a function")
        }
662

663
        # Prepare data
Guolin Ke's avatar
Guolin Ke committed
664
        data <- private$train_set
665

666
        # Check if data to assess is existing differently
667
668
        if (data_idx > 1L) {
          data <- private$valid_sets[[data_idx - 1L]]
669
        }
670

671
        # Perform function evaluation
672
        res <- feval(private$inner_predict(data_idx), data)
673

674
        # Check for name correctness
675
        if (is.null(res$name) || is.null(res$value) ||  is.null(res$higher_better)) {
676
          stop("lgb.Booster.eval: custom eval function should return a
677
678
            list with attribute (name, value, higher_better)");
        }
679

680
        # Append names and evaluation
Guolin Ke's avatar
Guolin Ke committed
681
        res$data_name <- data_name
682
        ret <- append(ret, list(res))
Guolin Ke's avatar
Guolin Ke committed
683
      }
684

685
      return(ret)
686

Guolin Ke's avatar
Guolin Ke committed
687
    }
688

Guolin Ke's avatar
Guolin Ke committed
689
690
691
  )
)

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

755
756
  if (!lgb.is.Booster(object)) {
    stop("predict.lgb.Booster: object should be an ", sQuote("lgb.Booster"))
Guolin Ke's avatar
Guolin Ke committed
757
  }
758

759
  # Return booster predictions
760
761
  object$predict(
    data
762
    , start_iteration
763
764
765
766
767
768
769
770
    , num_iteration
    , rawscore
    , predleaf
    , predcontrib
    , header
    , reshape
    , ...
  )
Guolin Ke's avatar
Guolin Ke committed
771
772
}

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

810
811
  filename_provided <- !is.null(filename)
  model_str_provided <- !is.null(model_str)
812

813
814
815
816
817
818
819
  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))
    }
820
821
    return(invisible(Booster$new(modelfile = filename)))
  }
822

823
824
825
826
  if (model_str_provided) {
    if (!is.character(model_str)) {
      stop("lgb.load: model_str should be character")
    }
827
828
    return(invisible(Booster$new(model_str = model_str)))
  }
829

830
  stop("lgb.load: either filename or model_str must be given")
Guolin Ke's avatar
Guolin Ke committed
831
832
}

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

867
868
869
  if (!lgb.is.Booster(booster)) {
    stop("lgb.save: booster should be an ", sQuote("lgb.Booster"))
  }
870

871
872
  if (!(is.character(filename) && length(filename) == 1L)) {
    stop("lgb.save: filename should be a string")
873
  }
874

875
  # Store booster
876
  invisible(booster$save_model(filename, num_iteration))
877

Guolin Ke's avatar
Guolin Ke committed
878
879
}

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

913
914
915
  if (!lgb.is.Booster(booster)) {
    stop("lgb.save: booster should be an ", sQuote("lgb.Booster"))
  }
916

917
  # Return booster at requested iteration
Guolin Ke's avatar
Guolin Ke committed
918
  booster$dump_model(num_iteration)
919

Guolin Ke's avatar
Guolin Ke committed
920
921
}

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

967
  # Check if booster is booster
968
969
  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
970
  }
971

972
  # Check if data and evaluation name are characters or not
973
974
  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
975
  }
976

977
978
979
980
981
982
983
984
985
986
  # 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
987
  }
988

989
  # Check if evaluation result is existing
990
991
992
993
994
995
996
997
998
999
1000
  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
1001
1002
    stop("lgb.get.eval.result: wrong eval name")
  }
1003

1004
  result <- booster$record_evals[[data_name]][[eval_name]][[.EVAL_KEY()]]
1005

1006
  # Check if error is requested
1007
  if (is_err) {
1008
    result <- booster$record_evals[[data_name]][[eval_name]][[.EVAL_ERR_KEY()]]
Guolin Ke's avatar
Guolin Ke committed
1009
  }
1010

1011
  # Check if iteration is non existant
1012
  if (is.null(iters)) {
Guolin Ke's avatar
Guolin Ke committed
1013
1014
    return(as.numeric(result))
  }
1015

1016
  # Parse iteration and booster delta
Guolin Ke's avatar
Guolin Ke committed
1017
  iters <- as.integer(iters)
1018
  delta <- booster$record_evals$start_iter - 1.0
Guolin Ke's avatar
Guolin Ke committed
1019
  iters <- iters - delta
1020

1021
  # Return requested result
1022
  as.numeric(result[iters])
Guolin Ke's avatar
Guolin Ke committed
1023
}