lgb.Dataset.R 30.5 KB
Newer Older
Guolin Ke's avatar
Guolin Ke committed
1
Dataset <- R6Class(
2
  classname = "lgb.Dataset",
3
  cloneable = FALSE,
Guolin Ke's avatar
Guolin Ke committed
4
  public = list(
5
6
    
    # Finalize will free up the handles
Guolin Ke's avatar
Guolin Ke committed
7
    finalize = function() {
8
9
      
      # Check the need for freeing handle
Guolin Ke's avatar
Guolin Ke committed
10
      if (!lgb.is.null.handle(private$handle)) {
11
12
        
        # Freeing up handle
Guolin Ke's avatar
Guolin Ke committed
13
14
        lgb.call("LGBM_DatasetFree_R", ret = NULL, private$handle)
        private$handle <- NULL
15
        
Guolin Ke's avatar
Guolin Ke committed
16
      }
17
      
Guolin Ke's avatar
Guolin Ke committed
18
    },
19
20
    
    # Initialize will create a starter dataset
Guolin Ke's avatar
Guolin Ke committed
21
    initialize = function(data,
22
23
24
                          params = list(),
                          reference = NULL,
                          colnames = NULL,
25
                          categorical_feature = NULL,
26
27
28
29
                          predictor = NULL,
                          free_raw_data = TRUE,
                          used_indices = NULL,
                          info = list(),
Guolin Ke's avatar
Guolin Ke committed
30
                          ...) {
31
32
      
      # Check for additional parameters
33
      additional_params <- list(...)
34
35
36
37
38
      
      # Create known attributes list
      INFO_KEYS <- c("label", "weight", "init_score", "group")
      
      # Check if attribute key is in the known attribute list
39
      for (key in names(additional_params)) {
40
41
        
        # Key existing
42
        if (key %in% INFO_KEYS) {
43
44
          
          # Store as info
45
          info[[key]] <- additional_params[[key]]
46
          
Guolin Ke's avatar
Guolin Ke committed
47
        } else {
48
49
          
          # Store as param
50
          params[[key]] <- additional_params[[key]]
51
          
Guolin Ke's avatar
Guolin Ke committed
52
        }
53
        
Guolin Ke's avatar
Guolin Ke committed
54
      }
55
56
      
      # Check for dataset reference
Guolin Ke's avatar
Guolin Ke committed
57
58
      if (!is.null(reference)) {
        if (!lgb.check.r6.class(reference, "lgb.Dataset")) {
59
          stop("lgb.Dataset: Can only use ", sQuote("lgb.Dataset"), " as reference")
Guolin Ke's avatar
Guolin Ke committed
60
61
        }
      }
62
63
      
      # Check for predictor reference
Guolin Ke's avatar
Guolin Ke committed
64
65
      if (!is.null(predictor)) {
        if (!lgb.check.r6.class(predictor, "lgb.Predictor")) {
66
          stop("lgb.Dataset: Only can use ", sQuote("lgb.Predictor"), " as predictor")
Guolin Ke's avatar
Guolin Ke committed
67
68
        }
      }
69
70
71
72
      
      # Setup private attributes
      private$raw_data <- data
      private$params <- params
Guolin Ke's avatar
Guolin Ke committed
73
      private$reference <- reference
74
      private$colnames <- colnames
75

76
      private$categorical_feature <- categorical_feature
77
78
79
80
81
      private$predictor <- predictor
      private$free_raw_data <- free_raw_data
      private$used_indices <- used_indices
      private$info <- info
      
Guolin Ke's avatar
Guolin Ke committed
82
    },
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
    
    create_valid = function(data,
                            info = list(),
                            ...) {
      
      # Create new dataset
      ret <- Dataset$new(data,
                         private$params,
                         self,
                         private$colnames,
                         private$categorical_feature,
                         private$predictor,
                         private$free_raw_data,
                         NULL,
                         info,
                         ...)
      
      # Return ret
101
      return(invisible(ret))
102
      
Guolin Ke's avatar
Guolin Ke committed
103
    },
104
105
    
    # Dataset constructor
Guolin Ke's avatar
Guolin Ke committed
106
    construct = function() {
107
108
      
      # Check for handle null
Guolin Ke's avatar
Guolin Ke committed
109
      if (!lgb.is.null.handle(private$handle)) {
110
        return(invisible(self))
Guolin Ke's avatar
Guolin Ke committed
111
      }
112
      
Guolin Ke's avatar
Guolin Ke committed
113
114
      # Get feature names
      cnames <- NULL
115
      if (is.matrix(private$raw_data) || is(private$raw_data, "dgCMatrix")) {
Guolin Ke's avatar
Guolin Ke committed
116
117
        cnames <- colnames(private$raw_data)
      }
118
      
Guolin Ke's avatar
Guolin Ke committed
119
      # set feature names if not exist
120
      if (is.null(private$colnames) && !is.null(cnames)) {
Guolin Ke's avatar
Guolin Ke committed
121
122
        private$colnames <- as.character(cnames)
      }
123
      
124
125
      # Get categorical feature index
      if (!is.null(private$categorical_feature)) {
126
127
        
        # Check for character name
128
        if (is.character(private$categorical_feature)) {
129
          
130
            cate_indices <- as.list(match(private$categorical_feature, private$colnames) - 1)
131
132
            
            # Provided indices, but some indices are not existing?
133
134
135
            if (sum(is.na(cate_indices)) > 0) {
              stop("lgb.self.get.handle: supplied an unknown feature in categorical_feature: ", sQuote(private$categorical_feature[is.na(cate_indices)]))
            }
136
            
137
          } else {
138
139
            
            # Check if more categorical features were output over the feature space
140
141
142
            if (max(private$categorical_feature) > length(private$colnames)) {
              stop("lgb.self.get.handle: supplied a too large value in categorical_feature: ", max(private$categorical_feature), " but only ", length(private$colnames), " features")
            }
143
144
            
            # Store indices as [0, n-1] indexed instead of [1, n] indexed
145
            cate_indices <- as.list(private$categorical_feature - 1)
146
            
147
          }
148
149
        
        # Store indices for categorical features
150
        private$params$categorical_feature <- cate_indices
151
        
152
      }
153
      
Guolin Ke's avatar
Guolin Ke committed
154
155
      # Check has header or not
      has_header <- FALSE
156
157
      if (!is.null(private$params$has_header) || !is.null(private$params$header)) {
        if (tolower(as.character(private$params$has_header)) == "true" || tolower(as.character(private$params$header)) == "true") {
Guolin Ke's avatar
Guolin Ke committed
158
159
160
          has_header <- TRUE
        }
      }
161
      
Guolin Ke's avatar
Guolin Ke committed
162
163
      # Generate parameter str
      params_str <- lgb.params2str(private$params)
164
165
      
      # Get handle of reference dataset
Guolin Ke's avatar
Guolin Ke committed
166
167
168
169
      ref_handle <- NULL
      if (!is.null(private$reference)) {
        ref_handle <- private$reference$.__enclos_env__$private$get_handle()
      }
Guolin Ke's avatar
Guolin Ke committed
170
      handle <- 0.0
171
172
      
      # Not subsetting
Guolin Ke's avatar
Guolin Ke committed
173
      if (is.null(private$used_indices)) {
174
175
        
        # Are we using a data file?
176
        if (is.character(private$raw_data)) {
177
178
179
180
181
182
183
          
          handle <- lgb.call("LGBM_DatasetCreateFromFile_R",
                             ret = handle,
                             lgb.c_str(private$raw_data),
                             params_str,
                             ref_handle)
          
Guolin Ke's avatar
Guolin Ke committed
184
        } else if (is.matrix(private$raw_data)) {
185
186
187
188
189
190
191
192
193
194
          
          # Are we using a matrix?
          handle <- lgb.call("LGBM_DatasetCreateFromMat_R",
                             ret = handle,
                             private$raw_data,
                             nrow(private$raw_data),
                             ncol(private$raw_data),
                             params_str,
                             ref_handle)
          
195
        } else if (is(private$raw_data, "dgCMatrix")) {
196
197
198
          if (length(private$raw_data@p) > 2147483647) {
            stop("Cannot support large CSC matrix")
          }
199
200
201
202
203
204
205
206
207
208
209
210
          # Are we using a dgCMatrix (sparsed matrix column compressed)
          handle <- lgb.call("LGBM_DatasetCreateFromCSC_R",
                             ret = handle,
                             private$raw_data@p,
                             private$raw_data@i,
                             private$raw_data@x,
                             length(private$raw_data@p),
                             length(private$raw_data@x),
                             nrow(private$raw_data),
                             params_str,
                             ref_handle)
          
Guolin Ke's avatar
Guolin Ke committed
211
        } else {
212
213
214
215
          
          # Unknown data type
          stop("lgb.Dataset.construct: does not support constructing from ", sQuote(class(private$raw_data)))
          
Guolin Ke's avatar
Guolin Ke committed
216
        }
217
        
Guolin Ke's avatar
Guolin Ke committed
218
      } else {
219
220
        
        # Reference is empty
Guolin Ke's avatar
Guolin Ke committed
221
        if (is.null(private$reference)) {
222
          stop("lgb.Dataset.construct: reference cannot be NULL for constructing data subset")
Guolin Ke's avatar
Guolin Ke committed
223
        }
224
225
226
227
228
229
230
231
232
        
        # Construct subset
        handle <- lgb.call("LGBM_DatasetGetSubset_R",
                           ret = handle,
                           ref_handle,
                           private$used_indices,
                           length(private$used_indices),
                           params_str)
        
Guolin Ke's avatar
Guolin Ke committed
233
      }
Guolin Ke's avatar
Guolin Ke committed
234
235
236
      if (lgb.is.null.handle(handle)) {
        stop("lgb.Dataset.construct: cannot create Dataset handle")
      }
237
      # Setup class and private type
Guolin Ke's avatar
Guolin Ke committed
238
239
      class(handle) <- "lgb.Dataset.handle"
      private$handle <- handle
240
241
242
243
244
      
      # Set feature names
      if (!is.null(private$colnames)) {
        self$set_colnames(private$colnames)
      }
245

246
247
248
249
      # Load init score if requested
      if (!is.null(private$predictor) && is.null(private$used_indices)) {
        
        # Setup initial scores
250
        init_score <- private$predictor$predict(private$raw_data, rawscore = TRUE, reshape = TRUE)
251
252
        
        # Not needed to transpose, for is col_marjor
Guolin Ke's avatar
Guolin Ke committed
253
254
        init_score <- as.vector(init_score)
        private$info$init_score <- init_score
255
256
257
258
259
260
        
      }
      
      # Should we free raw data?
      if (isTRUE(private$free_raw_data)) {
        private$raw_data <- NULL
Guolin Ke's avatar
Guolin Ke committed
261
      }
262
263
      
      # Get private information
Guolin Ke's avatar
Guolin Ke committed
264
      if (length(private$info) > 0) {
265
266
        
        # Set infos
267
        for (i in seq_along(private$info)) {
268
          
Guolin Ke's avatar
Guolin Ke committed
269
270
          p <- private$info[i]
          self$setinfo(names(p), p[[1]])
271
          
Guolin Ke's avatar
Guolin Ke committed
272
        }
273
        
Guolin Ke's avatar
Guolin Ke committed
274
      }
275
276
      
      # Get label information existence
Guolin Ke's avatar
Guolin Ke committed
277
278
279
      if (is.null(self$getinfo("label"))) {
        stop("lgb.Dataset.construct: label should be set")
      }
280
      
281
282
      # Return self
      return(invisible(self))
283
      
Guolin Ke's avatar
Guolin Ke committed
284
    },
285
286
    
    # Dimension function
Guolin Ke's avatar
Guolin Ke committed
287
    dim = function() {
288
289
      
      # Check for handle
Guolin Ke's avatar
Guolin Ke committed
290
      if (!lgb.is.null.handle(private$handle)) {
291
        
292
293
        num_row <- 0L
        num_col <- 0L
294
295
296
297
298
        
        # Get numeric data and numeric features
        c(lgb.call("LGBM_DatasetGetNumData_R", ret = num_row, private$handle),
          lgb.call("LGBM_DatasetGetNumFeature_R", ret = num_col, private$handle))
        
299
      } else if (is.matrix(private$raw_data) || is(private$raw_data, "dgCMatrix")) {
300
301
        
        # Check if dgCMatrix (sparse matrix column compressed)
302
        dim(private$raw_data)
303
        
Guolin Ke's avatar
Guolin Ke committed
304
      } else {
305
306
307
308
        
        # Trying to work with unknown dimensions is not possible
        stop("dim: cannot get dimensions before dataset has been constructed, please call lgb.Dataset.construct explicitly")
        
Guolin Ke's avatar
Guolin Ke committed
309
      }
310
      
Guolin Ke's avatar
Guolin Ke committed
311
    },
312
313
    
    # Get column names
Guolin Ke's avatar
Guolin Ke committed
314
    get_colnames = function() {
315
316
      
      # Check for handle
Guolin Ke's avatar
Guolin Ke committed
317
      if (!lgb.is.null.handle(private$handle)) {
318
319
        
        # Get feature names and write them
320
321
322
        cnames <- lgb.call.return.str("LGBM_DatasetGetFeatureNames_R", private$handle)
        private$colnames <- as.character(base::strsplit(cnames, "\t")[[1]])
        private$colnames
323
        
324
      } else if (is.matrix(private$raw_data) || is(private$raw_data, "dgCMatrix")) {
325
326
        
        # Check if dgCMatrix (sparse matrix column compressed)
327
        colnames(private$raw_data)
328
        
Guolin Ke's avatar
Guolin Ke committed
329
      } else {
330
331
332
333
        
        # Trying to work with unknown dimensions is not possible
        stop("dim: cannot get dimensions before dataset has been constructed, please call lgb.Dataset.construct explicitly")
        
Guolin Ke's avatar
Guolin Ke committed
334
      }
335
      
Guolin Ke's avatar
Guolin Ke committed
336
    },
337
338
    
    # Set column names
Guolin Ke's avatar
Guolin Ke committed
339
    set_colnames = function(colnames) {
340
341
342
      
      # Check column names non-existence
      if (is.null(colnames)) {
343
        return(invisible(self))
344
345
346
      }
      
      # Check empty column names
Guolin Ke's avatar
Guolin Ke committed
347
      colnames <- as.character(colnames)
348
      if (length(colnames) == 0) {
349
        return(invisible(self))
350
351
352
      }
      
      # Write column names
Guolin Ke's avatar
Guolin Ke committed
353
354
      private$colnames <- colnames
      if (!lgb.is.null.handle(private$handle)) {
355
356
        
        # Merge names with tab separation
Guolin Ke's avatar
Guolin Ke committed
357
358
359
360
361
        merged_name <- paste0(as.list(private$colnames), collapse = "\t")
        lgb.call("LGBM_DatasetSetFeatureNames_R",
                 ret = NULL,
                 private$handle,
                 lgb.c_str(merged_name))
362
        
Guolin Ke's avatar
Guolin Ke committed
363
      }
364
365
      
      # Return self
366
      return(invisible(self))
367
      
Guolin Ke's avatar
Guolin Ke committed
368
    },
369
370
    
    # Get information
Guolin Ke's avatar
Guolin Ke committed
371
    getinfo = function(name) {
372
373
      
      # Create known attributes list
374
      INFONAMES <- c("label", "weight", "init_score", "group")
375
376
377
378
      
      # Check if attribute key is in the known attribute list
      if (!is.character(name) || length(name) != 1 || !name %in% INFONAMES) {
        stop("getinfo: name must one of the following: ", paste0(sQuote(INFONAMES), collapse = ", "))
Guolin Ke's avatar
Guolin Ke committed
379
      }
380
381
      
      # Check for info name and handle
382
      if (is.null(private$info[[name]]) && !lgb.is.null.handle(private$handle)) {
383
384
        
        # Get field size of info
385
        info_len <- 0L
386
387
388
389
        info_len <- lgb.call("LGBM_DatasetGetFieldSize_R",
                             ret = info_len,
                             private$handle,
                             lgb.c_str(name))
390
391
        
        # Check if info is not empty
Guolin Ke's avatar
Guolin Ke committed
392
        if (info_len > 0) {
393
394
          
          # Get back fields
Guolin Ke's avatar
Guolin Ke committed
395
          ret <- NULL
396
397
398
399
400
401
          ret <- if (name == "group") {
            integer(info_len) # Integer
          } else {
            numeric(info_len) # Numeric
          }
          
402
403
404
405
          ret <- lgb.call("LGBM_DatasetGetField_R",
                          ret = ret,
                          private$handle,
                          lgb.c_str(name))
406
          
Guolin Ke's avatar
Guolin Ke committed
407
          private$info[[name]] <- ret
408
          
Guolin Ke's avatar
Guolin Ke committed
409
410
        }
      }
411
      
412
      private$info[[name]]
413
      
Guolin Ke's avatar
Guolin Ke committed
414
    },
415
416
    
    # Set information
Guolin Ke's avatar
Guolin Ke committed
417
    setinfo = function(name, info) {
418
419
      
      # Create known attributes list
420
      INFONAMES <- c("label", "weight", "init_score", "group")
421
422
423
424
425
426
427
428
429
430
431
432
433
434
      
      # Check if attribute key is in the known attribute list
      if (!is.character(name) || length(name) != 1 || !name %in% INFONAMES) {
        stop("setinfo: name must one of the following: ", paste0(sQuote(INFONAMES), collapse = ", "))
      }
      
      # Check for type of information
      info <- if (name == "group") {
        as.integer(info) # Integer
      } else {
        as.numeric(info) # Numeric
      }
      
      # Store information privately
Guolin Ke's avatar
Guolin Ke committed
435
      private$info[[name]] <- info
436
      
437
      if (!lgb.is.null.handle(private$handle) && !is.null(info)) {
438
        
Guolin Ke's avatar
Guolin Ke committed
439
        if (length(info) > 0) {
440
441
442
443
444
445
446
447
          
          lgb.call("LGBM_DatasetSetField_R",
                   ret = NULL,
                   private$handle,
                   lgb.c_str(name),
                   info,
                   length(info))
          
Guolin Ke's avatar
Guolin Ke committed
448
        }
449
        
Guolin Ke's avatar
Guolin Ke committed
450
      }
451
452
      
      # Return self
453
      return(invisible(self))
454
      
Guolin Ke's avatar
Guolin Ke committed
455
    },
456
457
    
    # Slice dataset
Guolin Ke's avatar
Guolin Ke committed
458
    slice = function(idxset, ...) {
459
460
461
462
463
464
465
466
467
468
469
470
471
      
      # Perform slicing
      Dataset$new(NULL,
                  private$params,
                  self,
                  private$colnames,
                  private$categorical_feature,
                  private$predictor,
                  private$free_raw_data,
                  idxset,
                  NULL,
                  ...)
      
Guolin Ke's avatar
Guolin Ke committed
472
    },
473
474
    
    # Update parameters
475
    update_params = function(params) {
476
477
      
      # Parameter updating
Guolin Ke's avatar
Guolin Ke committed
478
      private$params <- modifyList(private$params, params)
479
      return(invisible(self))
480
      
Guolin Ke's avatar
Guolin Ke committed
481
    },
482
483
    
    # Set categorical feature parameter
484
    set_categorical_feature = function(categorical_feature) {
485
486
487
      
      # Check for identical input
      if (identical(private$categorical_feature, categorical_feature)) {
488
        return(invisible(self))
489
490
491
      }
      
      # Check for empty data
492
      if (is.null(private$raw_data)) {
493
494
        stop("set_categorical_feature: cannot set categorical feature after freeing raw data,
          please set ", sQuote("free_raw_data = FALSE"), " when you construct lgb.Dataset")
495
      }
496
497
      
      # Overwrite categorical features
498
      private$categorical_feature <- categorical_feature
499
500
      
      # Finalize and return self
501
      self$finalize()
502
      return(invisible(self))
503
      
504
    },
505
506
    
    # Set reference
Guolin Ke's avatar
Guolin Ke committed
507
    set_reference = function(reference) {
508
509
      
      # Set known references
510
      self$set_categorical_feature(reference$.__enclos_env__$private$categorical_feature)
Guolin Ke's avatar
Guolin Ke committed
511
512
      self$set_colnames(reference$get_colnames())
      private$set_predictor(reference$.__enclos_env__$private$predictor)
513
514
515
      
      # Check for identical references
      if (identical(private$reference, reference)) {
516
        return(invisible(self))
517
518
519
      }
      
      # Check for empty data
Guolin Ke's avatar
Guolin Ke committed
520
      if (is.null(private$raw_data)) {
521
522
523
524
        
        stop("set_reference: cannot set reference after freeing raw data,
          please set ", sQuote("free_raw_data = FALSE"), " when you construct lgb.Dataset")
        
Guolin Ke's avatar
Guolin Ke committed
525
      }
526
527
      
      # Check for non-existing reference
Guolin Ke's avatar
Guolin Ke committed
528
      if (!is.null(reference)) {
529
530
        
        # Reference is unknown
Guolin Ke's avatar
Guolin Ke committed
531
        if (!lgb.check.r6.class(reference, "lgb.Dataset")) {
532
          stop("set_reference: Can only use lgb.Dataset as a reference")
Guolin Ke's avatar
Guolin Ke committed
533
        }
534
        
Guolin Ke's avatar
Guolin Ke committed
535
      }
536
537
      
      # Store reference
Guolin Ke's avatar
Guolin Ke committed
538
      private$reference <- reference
539
540
      
      # Finalize and return self
Guolin Ke's avatar
Guolin Ke committed
541
      self$finalize()
542
      return(invisible(self))
543
      
Guolin Ke's avatar
Guolin Ke committed
544
    },
545
546
    
    # Save binary model
Guolin Ke's avatar
Guolin Ke committed
547
    save_binary = function(fname) {
548
549
      
      # Store binary data
Guolin Ke's avatar
Guolin Ke committed
550
551
552
553
554
      self$construct()
      lgb.call("LGBM_DatasetSaveBinary_R",
               ret = NULL,
               private$handle,
               lgb.c_str(fname))
555
      return(invisible(self))
Guolin Ke's avatar
Guolin Ke committed
556
    }
557
    
Guolin Ke's avatar
Guolin Ke committed
558
559
  ),
  private = list(
560
561
562
563
564
    handle = NULL,
    raw_data = NULL,
    params = list(),
    reference = NULL,
    colnames = NULL,
565
    categorical_feature = NULL,
566
567
568
569
570
571
572
573
574
575
576
577
    predictor = NULL,
    free_raw_data = TRUE,
    used_indices = NULL,
    info = NULL,
    
    # Get handle
    get_handle = function() {
      
      # Get handle and construct if needed
      if (lgb.is.null.handle(private$handle)) {
        self$construct()
      }
578
      private$handle
579
      
Guolin Ke's avatar
Guolin Ke committed
580
    },
581
582
    
    # Set predictor
Guolin Ke's avatar
Guolin Ke committed
583
    set_predictor = function(predictor) {
584
585
586
      
      # Return self is identical predictor
      if (identical(private$predictor, predictor)) {
587
        return(invisible(self))
588
589
590
      }
      
      # Check for empty data
Guolin Ke's avatar
Guolin Ke committed
591
      if (is.null(private$raw_data)) {
592
593
        stop("set_predictor: cannot set predictor after free raw data,
          please set ", sQuote("free_raw_data = FALSE"), " when you construct lgb.Dataset")
Guolin Ke's avatar
Guolin Ke committed
594
      }
595
596
      
      # Check for empty predictor
Guolin Ke's avatar
Guolin Ke committed
597
      if (!is.null(predictor)) {
598
599
        
        # Predictor is unknown
Guolin Ke's avatar
Guolin Ke committed
600
        if (!lgb.check.r6.class(predictor, "lgb.Predictor")) {
601
          stop("set_predictor: Can only use lgb.Predictor as predictor")
Guolin Ke's avatar
Guolin Ke committed
602
        }
603
        
Guolin Ke's avatar
Guolin Ke committed
604
      }
605
606
      
      # Store predictor
Guolin Ke's avatar
Guolin Ke committed
607
      private$predictor <- predictor
608
609
      
      # Finalize and return self
Guolin Ke's avatar
Guolin Ke committed
610
      self$finalize()
611
      return(invisible(self))
612
      
Guolin Ke's avatar
Guolin Ke committed
613
    }
614
    
Guolin Ke's avatar
Guolin Ke committed
615
616
617
  )
)

wxchan's avatar
wxchan committed
618
#' Construct lgb.Dataset object
Guolin Ke's avatar
Guolin Ke committed
619
#'
wxchan's avatar
wxchan committed
620
#' Construct lgb.Dataset object from dense matrix, sparse matrix
Guolin Ke's avatar
Guolin Ke committed
621
622
623
624
625
626
#' or local file (that was created previously by saving an \code{lgb.Dataset}).
#'
#' @param data a \code{matrix} object, a \code{dgCMatrix} object or a character representing a filename
#' @param params a list of parameters
#' @param reference reference dataset
#' @param colnames names of columns
627
#' @param categorical_feature categorical features
Guolin Ke's avatar
Guolin Ke committed
628
629
630
#' @param free_raw_data TRUE for need to free raw data after construct
#' @param info a list of information of the lgb.Dataset object
#' @param ... other information to pass to \code{info} or parameters pass to \code{params}
631
#' 
Guolin Ke's avatar
Guolin Ke committed
632
#' @return constructed dataset
633
#' 
Guolin Ke's avatar
Guolin Ke committed
634
#' @examples
635
#' \dontrun{
636
637
638
639
640
641
642
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.save(dtrain, "lgb.Dataset.data")
#' dtrain <- lgb.Dataset("lgb.Dataset.data")
#' lgb.Dataset.construct(dtrain)
643
#' }
644
#' 
Guolin Ke's avatar
Guolin Ke committed
645
646
#' @export
lgb.Dataset <- function(data,
647
648
649
                        params = list(),
                        reference = NULL,
                        colnames = NULL,
650
                        categorical_feature = NULL,
651
652
                        free_raw_data = TRUE,
                        info = list(),
Guolin Ke's avatar
Guolin Ke committed
653
                        ...) {
654
655
  
  # Create new dataset
656
  invisible(Dataset$new(data,
657
658
659
660
661
662
663
664
              params,
              reference,
              colnames,
              categorical_feature,
              NULL,
              free_raw_data,
              NULL,
              info,
665
              ...))
666
  
Guolin Ke's avatar
Guolin Ke committed
667
668
}

wxchan's avatar
wxchan committed
669
#' Construct validation data
670
#' 
wxchan's avatar
wxchan committed
671
#' Construct validation data according to training data
672
#' 
Guolin Ke's avatar
Guolin Ke committed
673
674
675
676
#' @param dataset \code{lgb.Dataset} object, training data
#' @param data a \code{matrix} object, a \code{dgCMatrix} object or a character representing a filename
#' @param info a list of information of the lgb.Dataset object
#' @param ... other information to pass to \code{info}.
677
#' 
Guolin Ke's avatar
Guolin Ke committed
678
#' @return constructed dataset
679
#' 
Guolin Ke's avatar
Guolin Ke committed
680
#' @examples
681
#' \dontrun{
682
683
684
685
686
687
688
#' 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)
689
#' }
690
#' 
Guolin Ke's avatar
Guolin Ke committed
691
#' @export
692
693
694
lgb.Dataset.create.valid <- function(dataset, data, info = list(), ...) {
  
  # Check if dataset is not a dataset
695
696
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.create.valid: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
697
  }
698
699
  
  # Create validation dataset
700
  invisible(dataset$create_valid(data, info, ...))
701
  
702
}
Guolin Ke's avatar
Guolin Ke committed
703

704
#' Construct Dataset explicitly
705
#' 
Guolin Ke's avatar
Guolin Ke committed
706
#' @param dataset Object of class \code{lgb.Dataset}
707
#' 
Guolin Ke's avatar
Guolin Ke committed
708
#' @examples
709
#' \dontrun{
710
711
712
713
714
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
715
#' }
716
#' 
Guolin Ke's avatar
Guolin Ke committed
717
718
#' @export
lgb.Dataset.construct <- function(dataset) {
719
720
  
  # Check if dataset is not a dataset
721
722
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.construct: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
723
  }
724
725
  
  # Construct the dataset
726
  invisible(dataset$construct())
727
  
Guolin Ke's avatar
Guolin Ke committed
728
729
}

730
#' Dimensions of an lgb.Dataset
731
#' 
Guolin Ke's avatar
Guolin Ke committed
732
733
734
#' Returns a vector of numbers of rows and of columns in an \code{lgb.Dataset}.
#' @param x Object of class \code{lgb.Dataset}
#' @param ... other parameters
735
#' 
Guolin Ke's avatar
Guolin Ke committed
736
#' @return a vector of numbers of rows and of columns
737
#' 
Guolin Ke's avatar
Guolin Ke committed
738
739
740
#' @details
#' Note: since \code{nrow} and \code{ncol} internally use \code{dim}, they can also
#' be directly used with an \code{lgb.Dataset} object.
741
#' 
Guolin Ke's avatar
Guolin Ke committed
742
#' @examples
743
744
745
746
747
748
749
750
751
#' \dontrun{
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' 
#' stopifnot(nrow(dtrain) == nrow(train$data))
#' stopifnot(ncol(dtrain) == ncol(train$data))
#' stopifnot(all(dim(dtrain) == dim(train$data)))
752
#' }
753
#' 
Guolin Ke's avatar
Guolin Ke committed
754
755
756
#' @rdname dim
#' @export
dim.lgb.Dataset <- function(x, ...) {
757
758
  
  # Check if dataset is not a dataset
759
760
  if (!lgb.is.Dataset(x)) {
    stop("dim.lgb.Dataset: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
761
  }
762
763
  
  # Return dimensions
764
  x$dim()
765
  
Guolin Ke's avatar
Guolin Ke committed
766
767
768
769
770
}

#' Handling of column names of \code{lgb.Dataset}
#'
#' Only column names are supported for \code{lgb.Dataset}, thus setting of
771
#' row names would have no effect and returned row names would be NULL.
Guolin Ke's avatar
Guolin Ke committed
772
773
774
775
776
777
778
779
780
781
#'
#' @param x object of class \code{lgb.Dataset}
#' @param value a list of two elements: the first one is ignored
#'        and the second one is column names
#'
#' @details
#' Generic \code{dimnames} methods are used by \code{colnames}.
#' Since row names are irrelevant, it is recommended to use \code{colnames} directly.
#'
#' @examples
782
783
784
785
786
787
788
789
790
791
#' \dontrun{
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
#' dimnames(dtrain)
#' colnames(dtrain)
#' colnames(dtrain) <- make.names(1:ncol(train$data))
#' print(dtrain, verbose = TRUE)
792
#' }
793
#' 
Guolin Ke's avatar
Guolin Ke committed
794
795
796
#' @rdname dimnames.lgb.Dataset
#' @export
dimnames.lgb.Dataset <- function(x) {
797
798
  
  # Check if dataset is not a dataset
799
800
  if (!lgb.is.Dataset(x)) {
    stop("dimnames.lgb.Dataset: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
801
  }
802
803
  
  # Return dimension names
804
  list(NULL, x$get_colnames())
805
  
Guolin Ke's avatar
Guolin Ke committed
806
807
808
809
810
}

#' @rdname dimnames.lgb.Dataset
#' @export
`dimnames<-.lgb.Dataset` <- function(x, value) {
811
812
813
  
  # Check if invalid element list
  if (!is.list(value) || length(value) != 2L) {
814
    stop("invalid ", sQuote("value"), " given: must be a list of two elements")
815
816
817
818
819
820
821
822
  }
  
  # Check for unknown row names
  if (!is.null(value[[1L]])) {
    stop("lgb.Dataset does not have rownames")
  }
  
  # Check for second value missing
Guolin Ke's avatar
Guolin Ke committed
823
  if (is.null(value[[2]])) {
824
825
    
    # No column names
Guolin Ke's avatar
Guolin Ke committed
826
827
    x$set_colnames(NULL)
    return(x)
828
829
830
831
832
833
    
  }
  
  # Check for unmatching column size
  if (ncol(x) != length(value[[2]])) {
    stop("can't assign ", sQuote(length(value[[2]])), " colnames to an lgb.Dataset with ", sQuote(ncol(x)), " columns")
Guolin Ke's avatar
Guolin Ke committed
834
  }
835
836
  
  # Set column names properly, and return
Guolin Ke's avatar
Guolin Ke committed
837
  x$set_colnames(value[[2]])
838
  x
839
  
Guolin Ke's avatar
Guolin Ke committed
840
841
}

842
#' Slice a dataset
843
#' 
844
#' Get a new \code{lgb.Dataset} containing the specified rows of
Guolin Ke's avatar
Guolin Ke committed
845
#' orginal lgb.Dataset object
846
#' 
Guolin Ke's avatar
Guolin Ke committed
847
848
849
850
#' @param dataset Object of class "lgb.Dataset"
#' @param idxset a integer vector of indices of rows needed
#' @param ... other parameters (currently not used)
#' @return constructed sub dataset
851
#' 
Guolin Ke's avatar
Guolin Ke committed
852
#' @examples
853
#' \dontrun{
854
855
856
857
858
859
860
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' 
#' dsub <- lightgbm::slice(dtrain, 1:42)
#' labels <- lightgbm::getinfo(dsub, "label")
861
#' }
862
#' 
Guolin Ke's avatar
Guolin Ke committed
863
#' @export
864
865
866
slice <- function(dataset, ...) {
  UseMethod("slice")
}
Guolin Ke's avatar
Guolin Ke committed
867
868
869
870

#' @rdname slice
#' @export
slice.lgb.Dataset <- function(dataset, idxset, ...) {
871
872
  
  # Check if dataset is not a dataset
873
874
  if (!lgb.is.Dataset(dataset)) {
    stop("slice.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
875
  }
876
877
  
  # Return sliced set
878
  invisible(dataset$slice(idxset, ...))
879
  
Guolin Ke's avatar
Guolin Ke committed
880
881
882
}

#' Get information of an lgb.Dataset object
883
#' 
Guolin Ke's avatar
Guolin Ke committed
884
885
886
887
#' @param dataset Object of class \code{lgb.Dataset}
#' @param name the name of the information field to get (see details)
#' @param ... other parameters
#' @return info data
888
#' 
Guolin Ke's avatar
Guolin Ke committed
889
890
#' @details
#' The \code{name} field can be one of the following:
891
#' 
Guolin Ke's avatar
Guolin Ke committed
892
893
894
895
896
897
#' \itemize{
#'     \item \code{label}: label lightgbm learn from ;
#'     \item \code{weight}: to do a weight rescale ;
#'     \item \code{group}: group size
#'     \item \code{init_score}: initial score is the base prediction lightgbm will boost from ;
#' }
898
#' 
Guolin Ke's avatar
Guolin Ke committed
899
#' @examples
900
#' \dontrun{
901
902
903
904
905
906
907
908
909
910
911
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
#' 
#' labels <- lightgbm::getinfo(dtrain, "label")
#' lightgbm::setinfo(dtrain, "label", 1 - labels)
#' 
#' labels2 <- lightgbm::getinfo(dtrain, "label")
#' stopifnot(all(labels2 == 1 - labels))
912
#' }
913
#' 
Guolin Ke's avatar
Guolin Ke committed
914
#' @export
915
916
917
getinfo <- function(dataset, ...) {
  UseMethod("getinfo")
}
Guolin Ke's avatar
Guolin Ke committed
918
919
920
921

#' @rdname getinfo
#' @export
getinfo.lgb.Dataset <- function(dataset, name, ...) {
922
923
  
  # Check if dataset is not a dataset
924
925
  if (!lgb.is.Dataset(dataset)) {
    stop("getinfo.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
926
  }
927
928
  
  # Return information
929
  dataset$getinfo(name)
930
  
Guolin Ke's avatar
Guolin Ke committed
931
932
933
}

#' Set information of an lgb.Dataset object
934
#' 
Guolin Ke's avatar
Guolin Ke committed
935
936
937
938
939
#' @param dataset Object of class "lgb.Dataset"
#' @param name the name of the field to get
#' @param info the specific field of information to set
#' @param ... other parameters
#' @return passed object
940
#' 
Guolin Ke's avatar
Guolin Ke committed
941
942
#' @details
#' The \code{name} field can be one of the following:
943
#' 
Guolin Ke's avatar
Guolin Ke committed
944
945
946
947
948
949
#' \itemize{
#'     \item \code{label}: label lightgbm learn from ;
#'     \item \code{weight}: to do a weight rescale ;
#'     \item \code{init_score}: initial score is the base prediction lightgbm will boost from ;
#'     \item \code{group}.
#' }
950
#' 
Guolin Ke's avatar
Guolin Ke committed
951
#' @examples
952
#' \dontrun{
953
954
955
956
957
958
959
960
961
962
963
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
#' 
#' labels <- lightgbm::getinfo(dtrain, "label")
#' lightgbm::setinfo(dtrain, "label", 1 - labels)
#' 
#' labels2 <- lightgbm::getinfo(dtrain, "label")
#' stopifnot(all.equal(labels2, 1 - labels))
964
#' }
965
#' 
Guolin Ke's avatar
Guolin Ke committed
966
#' @export
967
968
969
setinfo <- function(dataset, ...) {
  UseMethod("setinfo")
}
Guolin Ke's avatar
Guolin Ke committed
970
971
972
973

#' @rdname setinfo
#' @export
setinfo.lgb.Dataset <- function(dataset, name, info, ...) {
974
975
  
  # Check if dataset is not a dataset
976
977
  if (!lgb.is.Dataset(dataset)) {
    stop("setinfo.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
978
  }
979
980
  
  # Set information
981
  invisible(dataset$setinfo(name, info))
Guolin Ke's avatar
Guolin Ke committed
982
983
}

984
#' Set categorical feature of \code{lgb.Dataset}
985
#' 
986
987
#' @param dataset object of class \code{lgb.Dataset}
#' @param categorical_feature categorical features
988
#' 
989
#' @return passed dataset
990
#' 
991
992
#' @examples
#' \dontrun{
993
994
995
996
997
998
999
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.save(dtrain, "lgb.Dataset.data")
#' dtrain <- lgb.Dataset("lgb.Dataset.data")
#' lgb.Dataset.set.categorical(dtrain, 1:2)
1000
#' }
1001
#' 
1002
1003
1004
#' @rdname lgb.Dataset.set.categorical
#' @export
lgb.Dataset.set.categorical <- function(dataset, categorical_feature) {
1005
1006
  
  # Check if dataset is not a dataset
1007
1008
1009
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.set.categorical: input dataset should be an lgb.Dataset object")
  }
1010
1011
  
  # Set categoricals
1012
  invisible(dataset$set_categorical_feature(categorical_feature))
1013
  
1014
1015
}

1016
#' Set reference of \code{lgb.Dataset}
1017
#' 
1018
#' If you want to use validation data, you should set reference to training data
1019
#' 
Guolin Ke's avatar
Guolin Ke committed
1020
1021
#' @param dataset object of class \code{lgb.Dataset}
#' @param reference object of class \code{lgb.Dataset}
1022
#' 
Guolin Ke's avatar
Guolin Ke committed
1023
#' @return passed dataset
1024
#' 
Guolin Ke's avatar
Guolin Ke committed
1025
#' @examples
1026
#' \dontrun{
1027
1028
1029
1030
1031
1032
1033
1034
#' 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(test$data, test = train$label)
#' lgb.Dataset.set.reference(dtest, dtrain)
1035
#' }
1036
#' 
Guolin Ke's avatar
Guolin Ke committed
1037
1038
1039
#' @rdname lgb.Dataset.set.reference
#' @export
lgb.Dataset.set.reference <- function(dataset, reference) {
1040
1041
  
  # Check if dataset is not a dataset
1042
1043
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.set.reference: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1044
  }
1045
1046
  
  # Set reference
1047
  invisible(dataset$set_reference(reference))
Guolin Ke's avatar
Guolin Ke committed
1048
1049
}

1050
#' Save \code{lgb.Dataset} to a binary file
1051
#' 
Guolin Ke's avatar
Guolin Ke committed
1052
1053
#' @param dataset object of class \code{lgb.Dataset}
#' @param fname object filename of output file
1054
#' 
Guolin Ke's avatar
Guolin Ke committed
1055
#' @return passed dataset
1056
#' 
Guolin Ke's avatar
Guolin Ke committed
1057
#' @examples
1058
#' 
1059
#' \dontrun{
1060
1061
1062
1063
1064
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.save(dtrain, "data.bin")
1065
#' }
1066
#' 
Guolin Ke's avatar
Guolin Ke committed
1067
1068
1069
#' @rdname lgb.Dataset.save
#' @export
lgb.Dataset.save <- function(dataset, fname) {
1070
1071
  
  # Check if dataset is not a dataset
1072
1073
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.set: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1074
  }
1075
1076
  
  # File-type is not matching
1077
1078
  if (!is.character(fname)) {
    stop("lgb.Dataset.set: fname should be a character or a file connection")
Guolin Ke's avatar
Guolin Ke committed
1079
  }
1080
1081
  
  # Store binary
1082
  invisible(dataset$save_binary(fname))
Guolin Ke's avatar
Guolin Ke committed
1083
}