lgb.Booster.R 26.1 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
    # 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",
369
370
                                 private$handle,
                                 as.integer(num_iteration)))
371
372
373
      
    },
    
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
      
      # Overwrite model in object
420
      self$raw <- self$save_model_to_string(NULL)
421
      
422
    }
423
    
Guolin Ke's avatar
Guolin Ke committed
424
425
  ),
  private = list(
426
427
428
429
430
431
432
433
434
435
436
    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
437
    higher_better_inner_eval = NULL,
438
439
440
441
442
    
    # Predict data
    inner_predict = function(idx) {
      
      # Store data name
Guolin Ke's avatar
Guolin Ke committed
443
      data_name <- private$name_train_set
444
445
446
447
448
449
450
      
      # 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
451
452
453
      if (idx > private$num_dataset) {
        stop("data_idx should not be greater than num_dataset")
      }
454
455
      
      # Check for prediction buffer
Guolin Ke's avatar
Guolin Ke committed
456
      if (is.null(private$predict_buffer[[data_name]])) {
457
458
        
        # Store predictions
459
        npred <- 0L
460
        npred <- lgb.call("LGBM_BoosterGetNumPredict_R",
461
462
463
464
465
                          ret = npred,
                          private$handle,
                          as.integer(idx - 1))
        private$predict_buffer[[data_name]] <- numeric(npred)
        
Guolin Ke's avatar
Guolin Ke committed
466
      }
467
468
      
      # Check if current iteration was already predicted
Guolin Ke's avatar
Guolin Ke committed
469
      if (!private$is_predicted_cur_iter[[idx]]) {
470
471
472
473
474
475
        
        # 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
476
477
        private$is_predicted_cur_iter[[idx]] <- TRUE
      }
478
479
480
      
      # Return prediction buffer
      return(private$predict_buffer[[data_name]])
Guolin Ke's avatar
Guolin Ke committed
481
    },
482
483
    
    # Get evaluation information
Guolin Ke's avatar
Guolin Ke committed
484
    get_eval_info = function() {
485
486
      
      # Check for evaluation names emptiness
Guolin Ke's avatar
Guolin Ke committed
487
      if (is.null(private$eval_names)) {
488
489
490
491
492
493
        
        # Get evaluation names
        names <- lgb.call.return.str("LGBM_BoosterGetEvalNames_R",
                                     private$handle)
        
        # Check names' length
494
        if (nchar(names) > 0) {
495
496
          
          # Parse and store privately names
Guolin Ke's avatar
Guolin Ke committed
497
498
          names <- strsplit(names, "\t")[[1]]
          private$eval_names <- names
499
          private$higher_better_inner_eval <- rep(FALSE, length(names))
500
501
          
          # Loop through each name to pick up evaluation (and parse ndcg manually)
502
          for (i in seq_along(names)) {
503
            
504
            if ((names[i] == "auc") | grepl("^ndcg", names[i])) {
Guolin Ke's avatar
Guolin Ke committed
505
506
              private$higher_better_inner_eval[i] <- TRUE
            }
507
            
Guolin Ke's avatar
Guolin Ke committed
508
          }
509
          
Guolin Ke's avatar
Guolin Ke committed
510
        }
511
        
Guolin Ke's avatar
Guolin Ke committed
512
      }
513
514
515
516
      
      # Return evaluation names
      return(private$eval_names)
      
Guolin Ke's avatar
Guolin Ke committed
517
    },
518
519
    
    # Perform inner evaluation
Guolin Ke's avatar
Guolin Ke committed
520
    inner_eval = function(data_name, data_idx, feval = NULL) {
521
522
      
      # Check for unknown dataset (over the maximum provided range)
Guolin Ke's avatar
Guolin Ke committed
523
524
525
      if (data_idx > private$num_dataset) {
        stop("data_idx should not be greater than num_dataset")
      }
526
527
      
      # Get evaluation information
Guolin Ke's avatar
Guolin Ke committed
528
      private$get_eval_info()
529
530
      
      # Prepare return
Guolin Ke's avatar
Guolin Ke committed
531
      ret <- list()
532
533
      
      # Check evaluation names existence
Guolin Ke's avatar
Guolin Ke committed
534
      if (length(private$eval_names) > 0) {
535
536
537
538
539
540
541
542
543
        
        # 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
544
        for (i in seq_along(private$eval_names)) {
545
546
547
548
549
550
          
          # 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
551
          res$higher_better <- private$higher_better_inner_eval[i]
552
553
          ret <- append(ret, list(res))
          
Guolin Ke's avatar
Guolin Ke committed
554
        }
555
        
Guolin Ke's avatar
Guolin Ke committed
556
      }
557
558
      
      # Check if there are evaluation metrics
Guolin Ke's avatar
Guolin Ke committed
559
      if (!is.null(feval)) {
560
561
        
        # Check if evaluation metric is a function
562
        if (!is.function(feval)) {
Guolin Ke's avatar
Guolin Ke committed
563
564
          stop("lgb.Booster.eval: feval should be a function")
        }
565
566
        
        # Prepare data
Guolin Ke's avatar
Guolin Ke committed
567
        data <- private$train_set
568
569
570
571
572
573
574
        
        # Check if data to assess is existing differently
        if (data_idx > 1) {
          data <- private$valid_sets[[data_idx - 1]]
        }
        
        # Perform function evaluation
575
        res <- feval(private$inner_predict(data_idx), data)
576
577
578
        
        # Check for name correctness
        if(is.null(res$name) | is.null(res$value) |  is.null(res$higher_better)) {
579
580
581
          stop("lgb.Booster.eval: custom eval function should return a 
            list with attribute (name, value, higher_better)");
        }
582
583
        
        # Append names and evaluation
Guolin Ke's avatar
Guolin Ke committed
584
        res$data_name <- data_name
585
        ret <- append(ret, list(res))
Guolin Ke's avatar
Guolin Ke committed
586
      }
587
588
589
590
      
      # Return ret
      return(ret)
      
Guolin Ke's avatar
Guolin Ke committed
591
    }
592
    
Guolin Ke's avatar
Guolin Ke committed
593
594
595
596
597
  )
)


#' Predict method for LightGBM model
598
#'
Guolin Ke's avatar
Guolin Ke committed
599
#' Predicted values based on class \code{lgb.Booster}
600
#'
Guolin Ke's avatar
Guolin Ke committed
601
602
603
#' @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
604
605
#' @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
606
#'        logistic regression would result in predictions for log-odds instead of probabilities.
607
#' @param predleaf whether predict leaf index instead.
Guolin Ke's avatar
Guolin Ke committed
608
#' @param header only used for prediction for text file. True if text file has header
609
610
#' @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
611

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

#' Load LightGBM model
666
#'
667
668
669
#' 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
670
#'
Guolin Ke's avatar
Guolin Ke committed
671
#' @param filename path of model file
672
#' @param model_str a str containing the model
673
#'
674
#' @return lgb.Booster
675
#' 
Guolin Ke's avatar
Guolin Ke committed
676
#' @examples
677
#' \dontrun{
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
#' 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")
695
696
697
#' 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)
698
#' }
699
#' 
700
#' @rdname lgb.load
Guolin Ke's avatar
Guolin Ke committed
701
#' @export
702
lgb.load <- function(filename = NULL, model_str = NULL){
703
  
704
705
706
707
708
709
  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)) {
710
711
712
713
    stop("lgb.load: filename should be character")
  }
  
  # Return new booster
714
715
716
717
718
719
720
721
722
  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))
723
  
Guolin Ke's avatar
Guolin Ke committed
724
725
726
}

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

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

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