lgb.Booster.R 26.3 KB
Newer Older
Guolin Ke's avatar
Guolin Ke committed
1
Booster <- R6Class(
2
  classname = "lgb.Booster",
3
  cloneable = FALSE,
Guolin Ke's avatar
Guolin Ke committed
4
  public = list(
5
6
    
    best_iter = -1,
Laurae's avatar
Laurae committed
7
    best_score = -1,
Guolin Ke's avatar
Guolin Ke committed
8
    record_evals = list(),
9
10
11
12
13
    
    # Finalize will free up the handles
    finalize = function() {
      
      # Check the need for freeing handle
14
      if (!lgb.is.null.handle(private$handle)) {
15
16
        
        # Freeing up handle
17
        lgb.call("LGBM_BoosterFree_R", ret = NULL, private$handle)
Guolin Ke's avatar
Guolin Ke committed
18
        private$handle <- NULL
19
        
Guolin Ke's avatar
Guolin Ke committed
20
      }
21
      
22
    },
23
24
25
    
    # Initialize will create a starter booster
    initialize = function(params = list(),
Guolin Ke's avatar
Guolin Ke committed
26
27
                          train_set = NULL,
                          modelfile = NULL,
28
                          model_str = NULL,
Guolin Ke's avatar
Guolin Ke committed
29
                          ...) {
30
31
32
      
      # Create parameters and handle
      params <- append(params, list(...))
Guolin Ke's avatar
Guolin Ke committed
33
      params_str <- lgb.params2str(params)
Guolin Ke's avatar
Guolin Ke committed
34
      handle <- 0.0
35
      # Check if training dataset is not null
Guolin Ke's avatar
Guolin Ke committed
36
      if (!is.null(train_set)) {
37
38
        
        # Check if training dataset is lgb.Dataset or not
Guolin Ke's avatar
Guolin Ke committed
39
        if (!lgb.check.r6.class(train_set, "lgb.Dataset")) {
40
          stop("lgb.Booster: Can only use lgb.Dataset as training data")
Guolin Ke's avatar
Guolin Ke committed
41
        }
Guolin Ke's avatar
Guolin Ke committed
42

43
44
        # Store booster handle
        handle <- lgb.call("LGBM_BoosterCreate_R", ret = handle, train_set$.__enclos_env__$private$get_handle(), params_str)
Guolin Ke's avatar
Guolin Ke committed
45

46
47
48
        # Create private booster information
        private$train_set <- train_set
        private$num_dataset <- 1
Guolin Ke's avatar
Guolin Ke committed
49
        private$init_predictor <- train_set$.__enclos_env__$private$predictor
50
51
        
        # Check if predictor is existing
Guolin Ke's avatar
Guolin Ke committed
52
        if (!is.null(private$init_predictor)) {
53
54
55
56
57
58
59
          
          # Merge booster
          lgb.call("LGBM_BoosterMerge_R",
                   ret = NULL,
                   handle,
                   private$init_predictor$.__enclos_env__$private$handle)
          
Guolin Ke's avatar
Guolin Ke committed
60
        }
61
62
        
        # Check current iteration
63
        private$is_predicted_cur_iter <- c(private$is_predicted_cur_iter, FALSE)
64
        
Guolin Ke's avatar
Guolin Ke committed
65
      } else if (!is.null(modelfile)) {
66
67
        
        # Do we have a model file as character?
Guolin Ke's avatar
Guolin Ke committed
68
        if (!is.character(modelfile)) {
69
          stop("lgb.Booster: Can only use a string as model file path")
Guolin Ke's avatar
Guolin Ke committed
70
        }
71
72
73
74
75
76
        
        # Create booster from model
        handle <- lgb.call("LGBM_BoosterCreateFromModelfile_R",
                           ret = handle,
                           lgb.c_str(modelfile))
        
77
78
79
80
81
82
83
84
85
86
87
88
      } else if (!is.null(model_str)) {
        
        # Do we have a model_str as character?
          if (!is.character(model_str)) {
            stop("lgb.Booster: Can only use a string as model_str")
          }
          
          # Create booster from model
          handle <- lgb.call("LGBM_BoosterLoadModelFromString_R",
                             ret = handle,
                             lgb.c_str(model_str))
        
Guolin Ke's avatar
Guolin Ke committed
89
      } else {
90
91
        
        # Booster non existent
92
        stop("lgb.Booster: Need at least either training dataset, model file, or model_str to create booster instance")
93
        
Guolin Ke's avatar
Guolin Ke committed
94
      }
Guolin Ke's avatar
Guolin Ke committed
95
96
97
98
99
100
101
102
103
104
105
      if (lgb.is.null.handle(handle)) {
        stop("lgb.Booster: cannot create Booster handle")
      } else {
        # Create class
        class(handle) <- "lgb.Booster.handle"
        private$handle <- handle
        private$num_class <- 1L
        private$num_class <- lgb.call("LGBM_BoosterGetNumClasses_R",
                                      ret = private$num_class,
                                      private$handle)
      }
106
      
Guolin Ke's avatar
Guolin Ke committed
107
    },
108
109
    
    # Set training data name
Guolin Ke's avatar
Guolin Ke committed
110
    set_train_data_name = function(name) {
111
112
      
      # Set name
Guolin Ke's avatar
Guolin Ke committed
113
      private$name_train_set <- name
114
      return(invisible(self))
115
      
Guolin Ke's avatar
Guolin Ke committed
116
    },
117
118
    
    # Add validation data
Guolin Ke's avatar
Guolin Ke committed
119
    add_valid = function(data, name) {
120
121
      
      # Check if data is lgb.Dataset
Guolin Ke's avatar
Guolin Ke committed
122
      if (!lgb.check.r6.class(data, "lgb.Dataset")) {
123
        stop("lgb.Booster.add_valid: Can only use lgb.Dataset as validation data")
Guolin Ke's avatar
Guolin Ke committed
124
      }
125
126
      
      # Check if predictors are identical
Guolin Ke's avatar
Guolin Ke committed
127
      if (!identical(data$.__enclos_env__$private$predictor, private$init_predictor)) {
128
        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
129
      }
130
131
      
      # Check if names are character
132
133
      if (!is.character(name)) {
        stop("lgb.Booster.add_valid: Can only use characters as data name")
Guolin Ke's avatar
Guolin Ke committed
134
      }
135
136
137
138
139
140
141
142
143
144
145
146
147
148
      
      # Add validation data to booster
      lgb.call("LGBM_BoosterAddValidData_R",
               ret = NULL,
               private$handle,
               data$.__enclos_env__$private$get_handle())
      
      # Store private information
      private$valid_sets <- c(private$valid_sets, data)
      private$name_valid_sets <- c(private$name_valid_sets, name)
      private$num_dataset <- private$num_dataset + 1
      private$is_predicted_cur_iter <- c(private$is_predicted_cur_iter, FALSE)
      
      # Return self
149
      return(invisible(self))
150
      
Guolin Ke's avatar
Guolin Ke committed
151
    },
152
153
    
    # Reset parameters of booster
Guolin Ke's avatar
Guolin Ke committed
154
    reset_parameter = function(params, ...) {
155
156
157
      
      # Append parameters
      params <- append(params, list(...))
Guolin Ke's avatar
Guolin Ke committed
158
      params_str <- algb.params2str(params)
159
160
161
162
163
164
165
166
      
      # Reset parameters
      lgb.call("LGBM_BoosterResetParameter_R",
               ret = NULL,
               private$handle,
               params_str)
      
      # Return self
167
      return(invisible(self))
168
      
Guolin Ke's avatar
Guolin Ke committed
169
    },
170
171
    
    # Perform boosting update iteration
Guolin Ke's avatar
Guolin Ke committed
172
    update = function(train_set = NULL, fobj = NULL) {
173
174
      
      # Check if training set is not null
Guolin Ke's avatar
Guolin Ke committed
175
      if (!is.null(train_set)) {
176
177
        
        # Check if training set is lgb.Dataset
Guolin Ke's avatar
Guolin Ke committed
178
179
180
        if (!lgb.check.r6.class(train_set, "lgb.Dataset")) {
          stop("lgb.Booster.update: Only can use lgb.Dataset as training data")
        }
181
182
        
        # Check if predictors are identical
Guolin Ke's avatar
Guolin Ke committed
183
        if (!identical(train_set$predictor, private$init_predictor)) {
184
          stop("lgb.Booster.update: Change train_set failed, you should use the same predictor for these data")
Guolin Ke's avatar
Guolin Ke committed
185
        }
186
187
188
189
190
191
192
193
        
        # Reset training data on booster
        lgb.call("LGBM_BoosterResetTrainingData_R",
                 ret = NULL,
                 private$handle,
                 train_set$.__enclos_env__$private$get_handle())
        
        # Store private train set
Guolin Ke's avatar
Guolin Ke committed
194
        private$train_set = train_set
195
        
Guolin Ke's avatar
Guolin Ke committed
196
      }
197
198
      
      # Check if objective is empty
Guolin Ke's avatar
Guolin Ke committed
199
      if (is.null(fobj)) {
200
201
        
        # Boost iteration from known objective
202
        ret <- lgb.call("LGBM_BoosterUpdateOneIter_R", ret = NULL, private$handle)
203
        
Guolin Ke's avatar
Guolin Ke committed
204
      } else {
205
206
207
208
209
210
211
        
        # Check if objective is function
        if (!is.function(fobj)) {
          stop("lgb.Booster.update: fobj should be a function")
        }
        
        # Perform objective calculation
Guolin Ke's avatar
Guolin Ke committed
212
        gpair <- fobj(private$inner_predict(1), private$train_set)
213
214
        
        # Check for gradient and hessian as list
215
216
217
218
        if(is.null(gpair$grad) | is.null(gpair$hess)){
          stop("lgb.Booster.update: custom objective should 
            return a list with attributes (hess, grad)")
        }
219
220
221
222
223
224
225
226
227
        
        # Return custom boosting gradient/hessian
        ret <- lgb.call("LGBM_BoosterUpdateOneIterCustom_R",
                        ret = NULL,
                        private$handle,
                        gpair$grad,
                        gpair$hess,
                        length(gpair$grad))
        
Guolin Ke's avatar
Guolin Ke committed
228
      }
229
230
      
      # Loop through each iteration
231
      for (i in seq_along(private$is_predicted_cur_iter)) {
Guolin Ke's avatar
Guolin Ke committed
232
233
        private$is_predicted_cur_iter[[i]] <- FALSE
      }
234
235
236
      
      return(ret)
      
Guolin Ke's avatar
Guolin Ke committed
237
    },
238
239
    
    # Return one iteration behind
Guolin Ke's avatar
Guolin Ke committed
240
    rollback_one_iter = function() {
241
242
243
244
245
246
247
      
      # Return one iteration behind
      lgb.call("LGBM_BoosterRollbackOneIter_R",
               ret = NULL,
               private$handle)
      
      # Loop through each iteration
248
      for (i in seq_along(private$is_predicted_cur_iter)) {
Guolin Ke's avatar
Guolin Ke committed
249
250
        private$is_predicted_cur_iter[[i]] <- FALSE
      }
251
252
      
      # Return self
253
      return(invisible(self))
254
      
Guolin Ke's avatar
Guolin Ke committed
255
    },
256
257
    
    # Get current iteration
Guolin Ke's avatar
Guolin Ke committed
258
    current_iter = function() {
259
      
260
      cur_iter <- 0L
261
262
263
264
      lgb.call("LGBM_BoosterGetCurrentIteration_R",
               ret = cur_iter,
               private$handle)
      
Guolin Ke's avatar
Guolin Ke committed
265
    },
266
267
    
    # Evaluate data on metrics
Guolin Ke's avatar
Guolin Ke committed
268
    eval = function(data, name, feval = NULL) {
269
270
      
      # Check if dataset is lgb.Dataset
Guolin Ke's avatar
Guolin Ke committed
271
      if (!lgb.check.r6.class(data, "lgb.Dataset")) {
272
        stop("lgb.Booster.eval: Can only use lgb.Dataset to eval")
Guolin Ke's avatar
Guolin Ke committed
273
      }
274
275
      
      # Check for identical data
Guolin Ke's avatar
Guolin Ke committed
276
      data_idx <- 0
277
278
279
280
281
      if (identical(data, private$train_set)) {
        data_idx <- 1
      } else {
        
        # Check for validation data
282
        if (length(private$valid_sets) > 0) {
283
284
          
          # Loop through each validation set
285
          for (i in seq_along(private$valid_sets)) {
286
287
            
            # Check for identical validation data with training data
Guolin Ke's avatar
Guolin Ke committed
288
            if (identical(data, private$valid_sets[[i]])) {
289
290
              
              # Found identical data, skip
Guolin Ke's avatar
Guolin Ke committed
291
292
              data_idx <- i + 1
              break
293
              
Guolin Ke's avatar
Guolin Ke committed
294
            }
295
            
Guolin Ke's avatar
Guolin Ke committed
296
          }
297
          
Guolin Ke's avatar
Guolin Ke committed
298
        }
299
        
Guolin Ke's avatar
Guolin Ke committed
300
      }
301
302
      
      # Check if evaluation was not done
Guolin Ke's avatar
Guolin Ke committed
303
      if (data_idx == 0) {
304
305
        
        # Add validation data by name
Guolin Ke's avatar
Guolin Ke committed
306
307
        self$add_valid(data, name)
        data_idx <- private$num_dataset
308
        
Guolin Ke's avatar
Guolin Ke committed
309
      }
310
311
      
      # Evaluate data
312
      private$inner_eval(name, data_idx, feval)
313
      
Guolin Ke's avatar
Guolin Ke committed
314
    },
315
316
    
    # Evaluation training data
Guolin Ke's avatar
Guolin Ke committed
317
    eval_train = function(feval = NULL) {
318
      private$inner_eval(private$name_train_set, 1, feval)
Guolin Ke's avatar
Guolin Ke committed
319
    },
320
321
    
    # Evaluation validation data
Guolin Ke's avatar
Guolin Ke committed
322
    eval_valid = function(feval = NULL) {
323
324
      
      # Create ret list
Guolin Ke's avatar
Guolin Ke committed
325
      ret = list()
326
327
328
329
330
331
332
      
      # Check if validation is empty
      if (length(private$valid_sets) <= 0) {
        return(ret)
      }
      
      # Loop through each validation set
333
334
      for (i in seq_along(private$valid_sets)) {
        ret <- append(ret, private$inner_eval(private$name_valid_sets[[i]], i + 1, feval))
Guolin Ke's avatar
Guolin Ke committed
335
      }
336
337
338
339
      
      # Return ret
      return(ret)
      
Guolin Ke's avatar
Guolin Ke committed
340
    },
341
342
    
    # Save model
Guolin Ke's avatar
Guolin Ke committed
343
    save_model = function(filename, num_iteration = NULL) {
344
345
346
347
348
349
350
351
352
353
354
355
356
357
      
      # Check if number of iteration is non existent
      if (is.null(num_iteration)) {
        num_iteration <- self$best_iter
      }
      
      # Save booster model
      lgb.call("LGBM_BoosterSaveModel_R",
               ret = NULL,
               private$handle,
               as.integer(num_iteration),
               lgb.c_str(filename))
      
      # Return self
358
      return(invisible(self))
Guolin Ke's avatar
Guolin Ke committed
359
    },
360
    
361
362
363
364
365
366
367
368
369
370
    # Save model to string
    save_model_to_string = function(num_iteration = NULL) {
      
      # Check if number of iteration is non existent
      if (is.null(num_iteration)) {
        num_iteration <- self$best_iter
      }
      
      # Return model string
      return(lgb.call.return.str("LGBM_BoosterSaveModelToString_R",
371
372
                                 private$handle,
                                 as.integer(num_iteration)))
373
374
375
      
    },
    
376
    # Dump model in memory
Guolin Ke's avatar
Guolin Ke committed
377
    dump_model = function(num_iteration = NULL) {
378
379
380
381
382
383
384
385
386
387
388
      
      # Check if number of iteration is non existent
      if (is.null(num_iteration)) {
        num_iteration <- self$best_iter
      }
      
      # Return dumped model
      lgb.call.return.str("LGBM_BoosterDumpModel_R",
                          private$handle,
                          as.integer(num_iteration))
      
Guolin Ke's avatar
Guolin Ke committed
389
    },
390
391
    
    # Predict on new data
Guolin Ke's avatar
Guolin Ke committed
392
    predict = function(data,
393
394
395
396
                       num_iteration = NULL,
                       rawscore = FALSE,
                       predleaf = FALSE,
                       header = FALSE,
397
                       reshape = FALSE, ...) {
398
399
400
401
402
403
404
      
      # Check if number of iteration is  non existent
      if (is.null(num_iteration)) {
        num_iteration <- self$best_iter
      }
      
      # Predict on new data
405
      predictor <- Predictor$new(private$handle, ...)
406
      predictor$predict(data, num_iteration, rawscore, predleaf, header, reshape)
407
408
409
410
411
412
      
    },
    
    # Transform into predictor
    to_predictor = function() {
      Predictor$new(private$handle)
Guolin Ke's avatar
Guolin Ke committed
413
    },
414
415
    
    # Used for save
416
    raw = NA,
417
418
    
    # Save model to temporary file for in-memory saving
419
    save = function() {
420
421
      
      # Overwrite model in object
422
      self$raw <- self$save_model_to_string(NULL)
423
      
424
    }
425
    
Guolin Ke's avatar
Guolin Ke committed
426
427
  ),
  private = list(
428
429
430
431
432
433
434
435
436
437
438
    handle = NULL,
    train_set = NULL,
    name_train_set = "training",
    valid_sets = list(),
    name_valid_sets = list(),
    predict_buffer = list(),
    is_predicted_cur_iter = list(),
    num_class = 1,
    num_dataset = 0,
    init_predictor = NULL,
    eval_names = NULL,
Guolin Ke's avatar
Guolin Ke committed
439
    higher_better_inner_eval = NULL,
440
441
442
443
444
    
    # Predict data
    inner_predict = function(idx) {
      
      # Store data name
Guolin Ke's avatar
Guolin Ke committed
445
      data_name <- private$name_train_set
446
447
448
449
450
451
452
      
      # Check for id bigger than 1
      if (idx > 1) {
        data_name <- private$name_valid_sets[[idx - 1]]
      }
      
      # Check for unknown dataset (over the maximum provided range)
Guolin Ke's avatar
Guolin Ke committed
453
454
455
      if (idx > private$num_dataset) {
        stop("data_idx should not be greater than num_dataset")
      }
456
457
      
      # Check for prediction buffer
Guolin Ke's avatar
Guolin Ke committed
458
      if (is.null(private$predict_buffer[[data_name]])) {
459
460
        
        # Store predictions
461
        npred <- 0L
462
        npred <- lgb.call("LGBM_BoosterGetNumPredict_R",
463
464
465
466
467
                          ret = npred,
                          private$handle,
                          as.integer(idx - 1))
        private$predict_buffer[[data_name]] <- numeric(npred)
        
Guolin Ke's avatar
Guolin Ke committed
468
      }
469
470
      
      # Check if current iteration was already predicted
Guolin Ke's avatar
Guolin Ke committed
471
      if (!private$is_predicted_cur_iter[[idx]]) {
472
473
474
475
476
477
        
        # Use buffer
        private$predict_buffer[[data_name]] <- lgb.call("LGBM_BoosterGetPredict_R",
                                                        ret = private$predict_buffer[[data_name]],
                                                        private$handle,
                                                        as.integer(idx - 1))
Guolin Ke's avatar
Guolin Ke committed
478
479
        private$is_predicted_cur_iter[[idx]] <- TRUE
      }
480
481
482
      
      # Return prediction buffer
      return(private$predict_buffer[[data_name]])
Guolin Ke's avatar
Guolin Ke committed
483
    },
484
485
    
    # Get evaluation information
Guolin Ke's avatar
Guolin Ke committed
486
    get_eval_info = function() {
487
488
      
      # Check for evaluation names emptiness
Guolin Ke's avatar
Guolin Ke committed
489
      if (is.null(private$eval_names)) {
490
491
492
493
494
495
        
        # Get evaluation names
        names <- lgb.call.return.str("LGBM_BoosterGetEvalNames_R",
                                     private$handle)
        
        # Check names' length
496
        if (nchar(names) > 0) {
497
498
          
          # Parse and store privately names
Guolin Ke's avatar
Guolin Ke committed
499
500
          names <- strsplit(names, "\t")[[1]]
          private$eval_names <- names
501
          private$higher_better_inner_eval <- rep(FALSE, length(names))
502
503
          
          # Loop through each name to pick up evaluation (and parse ndcg manually)
504
          for (i in seq_along(names)) {
505
            
506
            if ((names[i] == "auc") | grepl("^ndcg", names[i])) {
Guolin Ke's avatar
Guolin Ke committed
507
508
              private$higher_better_inner_eval[i] <- TRUE
            }
509
            
Guolin Ke's avatar
Guolin Ke committed
510
          }
511
          
Guolin Ke's avatar
Guolin Ke committed
512
        }
513
        
Guolin Ke's avatar
Guolin Ke committed
514
      }
515
516
517
518
      
      # Return evaluation names
      return(private$eval_names)
      
Guolin Ke's avatar
Guolin Ke committed
519
    },
520
521
    
    # Perform inner evaluation
Guolin Ke's avatar
Guolin Ke committed
522
    inner_eval = function(data_name, data_idx, feval = NULL) {
523
524
      
      # Check for unknown dataset (over the maximum provided range)
Guolin Ke's avatar
Guolin Ke committed
525
526
527
      if (data_idx > private$num_dataset) {
        stop("data_idx should not be greater than num_dataset")
      }
528
529
      
      # Get evaluation information
Guolin Ke's avatar
Guolin Ke committed
530
      private$get_eval_info()
531
532
      
      # Prepare return
Guolin Ke's avatar
Guolin Ke committed
533
      ret <- list()
534
535
      
      # Check evaluation names existence
Guolin Ke's avatar
Guolin Ke committed
536
      if (length(private$eval_names) > 0) {
537
538
539
540
541
542
543
544
545
        
        # Create evaluation values
        tmp_vals <- numeric(length(private$eval_names))
        tmp_vals <- lgb.call("LGBM_BoosterGetEval_R",
                             ret = tmp_vals,
                             private$handle,
                             as.integer(data_idx - 1))
        
        # Loop through all evaluation names
546
        for (i in seq_along(private$eval_names)) {
547
548
549
550
551
552
          
          # 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
553
          res$higher_better <- private$higher_better_inner_eval[i]
554
555
          ret <- append(ret, list(res))
          
Guolin Ke's avatar
Guolin Ke committed
556
        }
557
        
Guolin Ke's avatar
Guolin Ke committed
558
      }
559
560
      
      # Check if there are evaluation metrics
Guolin Ke's avatar
Guolin Ke committed
561
      if (!is.null(feval)) {
562
563
        
        # Check if evaluation metric is a function
564
        if (!is.function(feval)) {
Guolin Ke's avatar
Guolin Ke committed
565
566
          stop("lgb.Booster.eval: feval should be a function")
        }
567
568
        
        # Prepare data
Guolin Ke's avatar
Guolin Ke committed
569
        data <- private$train_set
570
571
572
573
574
575
576
        
        # Check if data to assess is existing differently
        if (data_idx > 1) {
          data <- private$valid_sets[[data_idx - 1]]
        }
        
        # Perform function evaluation
577
        res <- feval(private$inner_predict(data_idx), data)
578
579
580
        
        # Check for name correctness
        if(is.null(res$name) | is.null(res$value) |  is.null(res$higher_better)) {
581
582
583
          stop("lgb.Booster.eval: custom eval function should return a 
            list with attribute (name, value, higher_better)");
        }
584
585
        
        # Append names and evaluation
Guolin Ke's avatar
Guolin Ke committed
586
        res$data_name <- data_name
587
        ret <- append(ret, list(res))
Guolin Ke's avatar
Guolin Ke committed
588
      }
589
590
591
592
      
      # Return ret
      return(ret)
      
Guolin Ke's avatar
Guolin Ke committed
593
    }
594
    
Guolin Ke's avatar
Guolin Ke committed
595
596
597
598
599
  )
)


#' Predict method for LightGBM model
600
#'
Guolin Ke's avatar
Guolin Ke committed
601
#' Predicted values based on class \code{lgb.Booster}
602
#'
Guolin Ke's avatar
Guolin Ke committed
603
604
605
#' @param object Object of class \code{lgb.Booster}
#' @param data a \code{matrix} object, a \code{dgCMatrix} object or a character representing a filename
#' @param num_iteration number of iteration want to predict with, NULL or <= 0 means use best iteration
606
607
#' @param rawscore whether the prediction should be returned in the for of original untransformed
#'        sum of predictions from boosting iterations' results. E.g., setting \code{rawscore=TRUE} for
Guolin Ke's avatar
Guolin Ke committed
608
#'        logistic regression would result in predictions for log-odds instead of probabilities.
609
#' @param predleaf whether predict leaf index instead.
Guolin Ke's avatar
Guolin Ke committed
610
#' @param header only used for prediction for text file. True if text file has header
611
612
#' @param reshape whether to reshape the vector of predictions to a matrix form when there are several
#'        prediction outputs per case.
Guolin Ke's avatar
Guolin Ke committed
613

614
#' @return
Guolin Ke's avatar
Guolin Ke committed
615
#' For regression or binary classification, it returns a vector of length \code{nrows(data)}.
616
617
#' For multiclass classification, either a \code{num_class * nrows(data)} vector or
#' a \code{(nrows(data), num_class)} dimension matrix is returned, depending on
Guolin Ke's avatar
Guolin Ke committed
618
#' the \code{reshape} value.
619
620
#'
#' When \code{predleaf = TRUE}, the output is a matrix object with the
Guolin Ke's avatar
Guolin Ke committed
621
#' number of columns corresponding to the number of trees.
622
#' 
Guolin Ke's avatar
Guolin Ke committed
623
#' @examples
624
#' \dontrun{
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
#' 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)
#' model <- lgb.train(params,
#'                    dtrain,
#'                    100,
#'                    valids,
#'                    min_data = 1,
#'                    learning_rate = 1,
#'                    early_stopping_rounds = 10)
#' preds <- predict(model, test$data)
642
#' }
643
#' 
Guolin Ke's avatar
Guolin Ke committed
644
645
#' @rdname predict.lgb.Booster
#' @export
646
predict.lgb.Booster <- function(object, data,
Guolin Ke's avatar
Guolin Ke committed
647
                        num_iteration = NULL,
648
649
650
                        rawscore = FALSE,
                        predleaf = FALSE,
                        header = FALSE,
651
                        reshape = FALSE, ...) {
652
653
  
  # Check booster existence
654
655
  if (!lgb.is.Booster(object)) {
    stop("predict.lgb.Booster: object should be an ", sQuote("lgb.Booster"))
Guolin Ke's avatar
Guolin Ke committed
656
  }
657
658
659
660
661
662
663
  
  # Return booster predictions
  object$predict(data,
                 num_iteration,
                 rawscore,
                 predleaf,
                 header,
664
                 reshape, ...)
Guolin Ke's avatar
Guolin Ke committed
665
666
667
}

#' Load LightGBM model
668
#'
669
670
671
#' Load LightGBM model from saved model file or string
#' Load LightGBM takes in either a file path or model string
#' If both are provided, Load will default to loading from file
672
#'
Guolin Ke's avatar
Guolin Ke committed
673
#' @param filename path of model file
674
#' @param model_str a str containing the model
675
#'
676
#' @return lgb.Booster
677
#' 
Guolin Ke's avatar
Guolin Ke committed
678
#' @examples
679
#' \dontrun{
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
#' 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)
#' model <- lgb.train(params,
#'                    dtrain,
#'                    100,
#'                    valids,
#'                    min_data = 1,
#'                    learning_rate = 1,
#'                    early_stopping_rounds = 10)
#' lgb.save(model, "model.txt")
697
698
699
#' load_booster <- lgb.load(filename = "model.txt")
#' model_string <- model$save_model_to_string(NULL) # saves best iteration
#' load_booster_from_str <- lgb.load(model_str = model_string)
700
#' }
701
#' 
702
#' @rdname lgb.load
Guolin Ke's avatar
Guolin Ke committed
703
#' @export
704
lgb.load <- function(filename = NULL, model_str = NULL){
705
  
706
707
708
709
710
711
  if (is.null(filename) && is.null(model_str)) {
    stop("lgb.load: either filename or model_str must be given")
  }
  
  # Load from filename
  if (!is.null(filename) && !is.character(filename)) {
712
713
714
715
    stop("lgb.load: filename should be character")
  }
  
  # Return new booster
716
  if (!is.null(filename) && !file.exists(filename)) stop("lgb.load: file does not exist for supplied filename")
717
  if (!is.null(filename)) return(invisible(Booster$new(modelfile = filename)))
718
719
720
721
722
723
  
  # Load from model_str
  if (!is.null(model_str) && !is.character(model_str)) {
    stop("lgb.load: model_str should be character")
  }    
  # Return new booster
724
  if (!is.null(model_str)) return(invisible(Booster$new(model_str = model_str)))
725
  
Guolin Ke's avatar
Guolin Ke committed
726
727
728
}

#' Save LightGBM model
729
#'
Guolin Ke's avatar
Guolin Ke committed
730
#' Save LightGBM model
731
#'
Guolin Ke's avatar
Guolin Ke committed
732
733
734
#' @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
735
#'
736
#' @return lgb.Booster
737
#' 
Guolin Ke's avatar
Guolin Ke committed
738
#' @examples
739
#' \dontrun{
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
#' 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)
#' model <- lgb.train(params,
#'                    dtrain,
#'                    100,
#'                    valids,
#'                    min_data = 1,
#'                    learning_rate = 1,
#'                    early_stopping_rounds = 10)
#' lgb.save(model, "model.txt")
757
#' }
758
#' 
759
#' @rdname lgb.save
Guolin Ke's avatar
Guolin Ke committed
760
#' @export
761
lgb.save <- function(booster, filename, num_iteration = NULL){
762
763
764
765
766
767
768
769
770
771
772
773
  
  # Check if booster is booster
  if (!lgb.is.Booster(booster)) {
    stop("lgb.save: booster should be an ", sQuote("lgb.Booster"))
  }
  
  # Check if file name is character
  if (!is.character(filename)) {
    stop("lgb.save: filename should be a character")
  }
  
  # Store booster
774
  invisible(booster$save_model(filename, num_iteration))
775
  
Guolin Ke's avatar
Guolin Ke committed
776
777
778
}

#' Dump LightGBM model to json
779
#'
Guolin Ke's avatar
Guolin Ke committed
780
#' Dump LightGBM model to json
781
#'
Guolin Ke's avatar
Guolin Ke committed
782
783
#' @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
784
#'
Guolin Ke's avatar
Guolin Ke committed
785
#' @return json format of model
786
#' 
Guolin Ke's avatar
Guolin Ke committed
787
#' @examples
788
#' \dontrun{
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
#' 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)
#' model <- lgb.train(params,
#'                   dtrain,
#'                    100,
#'                    valids,
#'                    min_data = 1,
#'                    learning_rate = 1,
#'                    early_stopping_rounds = 10)
#' json_model <- lgb.dump(model)
806
#' }
807
#' 
808
#' @rdname lgb.dump
Guolin Ke's avatar
Guolin Ke committed
809
#' @export
810
lgb.dump <- function(booster, num_iteration = NULL){
811
812
813
814
815
816
817
  
  # Check if booster is booster
  if (!lgb.is.Booster(booster)) {
    stop("lgb.save: booster should be an ", sQuote("lgb.Booster"))
  }
  
  # Return booster at requested iteration
Guolin Ke's avatar
Guolin Ke committed
818
  booster$dump_model(num_iteration)
819
  
Guolin Ke's avatar
Guolin Ke committed
820
821
822
}

#' Get record evaluation result from booster
823
#'
Guolin Ke's avatar
Guolin Ke committed
824
825
826
827
828
829
#' Get record evaluation result from booster
#' @param booster Object of class \code{lgb.Booster}
#' @param data_name name of dataset
#' @param eval_name name of evaluation
#' @param iters iterations, NULL will return all
#' @param is_err TRUE will return evaluation error instead
830
#' 
Guolin Ke's avatar
Guolin Ke committed
831
#' @return vector of evaluation result
832
#' 
Guolin Ke's avatar
Guolin Ke committed
833
834
#' @rdname lgb.get.eval.result
#' @export
835
lgb.get.eval.result <- function(booster, data_name, eval_name, iters = NULL, is_err = FALSE) {
836
837
  
  # Check if booster is booster
838
839
  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
840
  }
841
842
  
  # Check if data and evaluation name are characters or not
843
844
  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
845
  }
846
847
  
  # Check if recorded evaluation is existing
848
  if (is.null(booster$record_evals[[data_name]])) {
Guolin Ke's avatar
Guolin Ke committed
849
850
    stop("lgb.get.eval.result: wrong data name")
  }
851
852
  
  # Check if evaluation result is existing
853
  if (is.null(booster$record_evals[[data_name]][[eval_name]])) {
Guolin Ke's avatar
Guolin Ke committed
854
855
    stop("lgb.get.eval.result: wrong eval name")
  }
856
857
  
  # Create result
Guolin Ke's avatar
Guolin Ke committed
858
  result <- booster$record_evals[[data_name]][[eval_name]]$eval
859
860
  
  # Check if error is requested
861
  if (is_err) {
Guolin Ke's avatar
Guolin Ke committed
862
863
    result <- booster$record_evals[[data_name]][[eval_name]]$eval_err
  }
864
865
  
  # Check if iteration is non existant
866
  if (is.null(iters)) {
Guolin Ke's avatar
Guolin Ke committed
867
868
    return(as.numeric(result))
  }
869
870
  
  # Parse iteration and booster delta
Guolin Ke's avatar
Guolin Ke committed
871
872
873
  iters <- as.integer(iters)
  delta <- booster$record_evals$start_iter - 1
  iters <- iters - delta
874
875
  
  # Return requested result
876
  as.numeric(result[iters])
Guolin Ke's avatar
Guolin Ke committed
877
}