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


#' Predict method for LightGBM model
607
#'
Guolin Ke's avatar
Guolin Ke committed
608
#' Predicted values based on class \code{lgb.Booster}
609
#'
Guolin Ke's avatar
Guolin Ke committed
610
611
612
#' @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
613
614
#' @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
615
#'        logistic regression would result in predictions for log-odds instead of probabilities.
616
#' @param predleaf whether predict leaf index instead.
Guolin Ke's avatar
Guolin Ke committed
617
#' @param header only used for prediction for text file. True if text file has header
618
619
#' @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
620

621
#' @return
Guolin Ke's avatar
Guolin Ke committed
622
#' For regression or binary classification, it returns a vector of length \code{nrows(data)}.
623
624
#' 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
625
#' the \code{reshape} value.
626
627
#'
#' When \code{predleaf = TRUE}, the output is a matrix object with the
Guolin Ke's avatar
Guolin Ke committed
628
#' number of columns corresponding to the number of trees.
629
#' 
Guolin Ke's avatar
Guolin Ke committed
630
#' @examples
631
#' \dontrun{
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
#' 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)
649
#' }
650
#' 
Guolin Ke's avatar
Guolin Ke committed
651
652
#' @rdname predict.lgb.Booster
#' @export
653
predict.lgb.Booster <- function(object, data,
Guolin Ke's avatar
Guolin Ke committed
654
                        num_iteration = NULL,
655
656
657
658
659
660
                        rawscore = FALSE,
                        predleaf = FALSE,
                        header = FALSE,
                        reshape = FALSE) {
  
  # Check booster existence
661
662
  if (!lgb.is.Booster(object)) {
    stop("predict.lgb.Booster: object should be an ", sQuote("lgb.Booster"))
Guolin Ke's avatar
Guolin Ke committed
663
  }
664
665
666
667
668
669
670
671
  
  # Return booster predictions
  object$predict(data,
                 num_iteration,
                 rawscore,
                 predleaf,
                 header,
                 reshape)
Guolin Ke's avatar
Guolin Ke committed
672
673
674
}

#' Load LightGBM model
675
#'
676
677
678
#' 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
679
#'
Guolin Ke's avatar
Guolin Ke committed
680
#' @param filename path of model file
681
#' @param model_str a str containing the model
682
#'
Guolin Ke's avatar
Guolin Ke committed
683
#' @return booster
684
#' 
Guolin Ke's avatar
Guolin Ke committed
685
#' @examples
686
#' \dontrun{
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
#' 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")
#' load_booster <- lgb.load("model.txt")
705
#' load_booster_from_str <- lgb.load(model$raw)
706
#' }
707
#' 
708
#' @rdname lgb.load
Guolin Ke's avatar
Guolin Ke committed
709
#' @export
710
lgb.load <- function(filename = NULL, model_str = NULL){
711
  
712
713
714
715
716
717
  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)) {
718
719
720
721
    stop("lgb.load: filename should be character")
  }
  
  # Return new booster
722
723
724
725
726
727
728
729
730
  if (!is.null(filename) && !file.exists(filename)) stop("lgb.load: file does not exist for supplied filename")
  if (!is.null(filename)) return(Booster$new(modelfile = filename))
  
  # Load from model_str
  if (!is.null(model_str) && !is.character(model_str)) {
    stop("lgb.load: model_str should be character")
  }    
  # Return new booster
  if (!is.null(model_str)) return(Booster$new(model_str = model_str))
731
  
Guolin Ke's avatar
Guolin Ke committed
732
733
734
}

#' Save LightGBM model
735
#'
Guolin Ke's avatar
Guolin Ke committed
736
#' Save LightGBM model
737
#'
Guolin Ke's avatar
Guolin Ke committed
738
739
740
#' @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
741
#'
Guolin Ke's avatar
Guolin Ke committed
742
#' @return booster
743
#' 
Guolin Ke's avatar
Guolin Ke committed
744
#' @examples
745
#' \dontrun{
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
#' 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")
763
#' }
764
#' 
765
#' @rdname lgb.save
Guolin Ke's avatar
Guolin Ke committed
766
#' @export
767
lgb.save <- function(booster, filename, num_iteration = NULL){
768
769
770
771
772
773
774
775
776
777
778
779
  
  # 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
Guolin Ke's avatar
Guolin Ke committed
780
  booster$save_model(filename, num_iteration)
781
  
Guolin Ke's avatar
Guolin Ke committed
782
783
784
}

#' Dump LightGBM model to json
785
#'
Guolin Ke's avatar
Guolin Ke committed
786
#' Dump LightGBM model to json
787
#'
Guolin Ke's avatar
Guolin Ke committed
788
789
#' @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
790
#'
Guolin Ke's avatar
Guolin Ke committed
791
#' @return json format of model
792
#' 
Guolin Ke's avatar
Guolin Ke committed
793
#' @examples
794
#' \dontrun{
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
#' 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)
812
#' }
813
#' 
814
#' @rdname lgb.dump
Guolin Ke's avatar
Guolin Ke committed
815
#' @export
816
lgb.dump <- function(booster, num_iteration = NULL){
817
818
819
820
821
822
823
  
  # 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
824
  booster$dump_model(num_iteration)
825
  
Guolin Ke's avatar
Guolin Ke committed
826
827
828
}

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