lgb.Dataset.R 30.6 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
383
384
385
      if (is.null(private$info[[name]])) {
        if (lgb.is.null.handle(private$handle)){
          stop("Cannot perform getinfo before construct Dataset.")
        }
386
        # Get field size of info
387
        info_len <- 0L
388
389
390
391
        info_len <- lgb.call("LGBM_DatasetGetFieldSize_R",
                             ret = info_len,
                             private$handle,
                             lgb.c_str(name))
392
393
        
        # Check if info is not empty
Guolin Ke's avatar
Guolin Ke committed
394
        if (info_len > 0) {
395
396
          
          # Get back fields
Guolin Ke's avatar
Guolin Ke committed
397
          ret <- NULL
398
399
400
401
402
403
          ret <- if (name == "group") {
            integer(info_len) # Integer
          } else {
            numeric(info_len) # Numeric
          }
          
404
405
406
407
          ret <- lgb.call("LGBM_DatasetGetField_R",
                          ret = ret,
                          private$handle,
                          lgb.c_str(name))
408
          
Guolin Ke's avatar
Guolin Ke committed
409
          private$info[[name]] <- ret
410
          
Guolin Ke's avatar
Guolin Ke committed
411
412
        }
      }
413
      
414
      private$info[[name]]
415
      
Guolin Ke's avatar
Guolin Ke committed
416
    },
417
418
    
    # Set information
Guolin Ke's avatar
Guolin Ke committed
419
    setinfo = function(name, info) {
420
421
      
      # Create known attributes list
422
      INFONAMES <- c("label", "weight", "init_score", "group")
423
424
425
426
427
428
429
430
431
432
433
434
435
436
      
      # 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
437
      private$info[[name]] <- info
438
      
439
      if (!lgb.is.null.handle(private$handle) && !is.null(info)) {
440
        
Guolin Ke's avatar
Guolin Ke committed
441
        if (length(info) > 0) {
442
443
444
445
446
447
448
449
          
          lgb.call("LGBM_DatasetSetField_R",
                   ret = NULL,
                   private$handle,
                   lgb.c_str(name),
                   info,
                   length(info))
          
Guolin Ke's avatar
Guolin Ke committed
450
        }
451
        
Guolin Ke's avatar
Guolin Ke committed
452
      }
453
454
      
      # Return self
455
      return(invisible(self))
456
      
Guolin Ke's avatar
Guolin Ke committed
457
    },
458
459
    
    # Slice dataset
Guolin Ke's avatar
Guolin Ke committed
460
    slice = function(idxset, ...) {
461
462
463
464
465
466
467
468
469
470
471
472
473
      
      # 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
474
    },
475
476
    
    # Update parameters
477
    update_params = function(params) {
478
479
      
      # Parameter updating
Guolin Ke's avatar
Guolin Ke committed
480
      private$params <- modifyList(private$params, params)
481
      return(invisible(self))
482
      
Guolin Ke's avatar
Guolin Ke committed
483
    },
484
485
    
    # Set categorical feature parameter
486
    set_categorical_feature = function(categorical_feature) {
487
488
489
      
      # Check for identical input
      if (identical(private$categorical_feature, categorical_feature)) {
490
        return(invisible(self))
491
492
493
      }
      
      # Check for empty data
494
      if (is.null(private$raw_data)) {
495
496
        stop("set_categorical_feature: cannot set categorical feature after freeing raw data,
          please set ", sQuote("free_raw_data = FALSE"), " when you construct lgb.Dataset")
497
      }
498
499
      
      # Overwrite categorical features
500
      private$categorical_feature <- categorical_feature
501
502
      
      # Finalize and return self
503
      self$finalize()
504
      return(invisible(self))
505
      
506
    },
507
508
    
    # Set reference
Guolin Ke's avatar
Guolin Ke committed
509
    set_reference = function(reference) {
510
511
      
      # Set known references
512
      self$set_categorical_feature(reference$.__enclos_env__$private$categorical_feature)
Guolin Ke's avatar
Guolin Ke committed
513
514
      self$set_colnames(reference$get_colnames())
      private$set_predictor(reference$.__enclos_env__$private$predictor)
515
516
517
      
      # Check for identical references
      if (identical(private$reference, reference)) {
518
        return(invisible(self))
519
520
521
      }
      
      # Check for empty data
Guolin Ke's avatar
Guolin Ke committed
522
      if (is.null(private$raw_data)) {
523
524
525
526
        
        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
527
      }
528
529
      
      # Check for non-existing reference
Guolin Ke's avatar
Guolin Ke committed
530
      if (!is.null(reference)) {
531
532
        
        # Reference is unknown
Guolin Ke's avatar
Guolin Ke committed
533
        if (!lgb.check.r6.class(reference, "lgb.Dataset")) {
534
          stop("set_reference: Can only use lgb.Dataset as a reference")
Guolin Ke's avatar
Guolin Ke committed
535
        }
536
        
Guolin Ke's avatar
Guolin Ke committed
537
      }
538
539
      
      # Store reference
Guolin Ke's avatar
Guolin Ke committed
540
      private$reference <- reference
541
542
      
      # Finalize and return self
Guolin Ke's avatar
Guolin Ke committed
543
      self$finalize()
544
      return(invisible(self))
545
      
Guolin Ke's avatar
Guolin Ke committed
546
    },
547
548
    
    # Save binary model
Guolin Ke's avatar
Guolin Ke committed
549
    save_binary = function(fname) {
550
551
      
      # Store binary data
Guolin Ke's avatar
Guolin Ke committed
552
553
554
555
556
      self$construct()
      lgb.call("LGBM_DatasetSaveBinary_R",
               ret = NULL,
               private$handle,
               lgb.c_str(fname))
557
      return(invisible(self))
Guolin Ke's avatar
Guolin Ke committed
558
    }
559
    
Guolin Ke's avatar
Guolin Ke committed
560
561
  ),
  private = list(
562
563
564
565
566
    handle = NULL,
    raw_data = NULL,
    params = list(),
    reference = NULL,
    colnames = NULL,
567
    categorical_feature = NULL,
568
569
570
571
572
573
574
575
576
577
578
579
    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()
      }
580
      private$handle
581
      
Guolin Ke's avatar
Guolin Ke committed
582
    },
583
584
    
    # Set predictor
Guolin Ke's avatar
Guolin Ke committed
585
    set_predictor = function(predictor) {
586
587
588
      
      # Return self is identical predictor
      if (identical(private$predictor, predictor)) {
589
        return(invisible(self))
590
591
592
      }
      
      # Check for empty data
Guolin Ke's avatar
Guolin Ke committed
593
      if (is.null(private$raw_data)) {
594
595
        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
596
      }
597
598
      
      # Check for empty predictor
Guolin Ke's avatar
Guolin Ke committed
599
      if (!is.null(predictor)) {
600
601
        
        # Predictor is unknown
Guolin Ke's avatar
Guolin Ke committed
602
        if (!lgb.check.r6.class(predictor, "lgb.Predictor")) {
603
          stop("set_predictor: Can only use lgb.Predictor as predictor")
Guolin Ke's avatar
Guolin Ke committed
604
        }
605
        
Guolin Ke's avatar
Guolin Ke committed
606
      }
607
608
      
      # Store predictor
Guolin Ke's avatar
Guolin Ke committed
609
      private$predictor <- predictor
610
611
      
      # Finalize and return self
Guolin Ke's avatar
Guolin Ke committed
612
      self$finalize()
613
      return(invisible(self))
614
      
Guolin Ke's avatar
Guolin Ke committed
615
    }
616
    
Guolin Ke's avatar
Guolin Ke committed
617
618
619
  )
)

wxchan's avatar
wxchan committed
620
#' Construct lgb.Dataset object
Guolin Ke's avatar
Guolin Ke committed
621
#'
wxchan's avatar
wxchan committed
622
#' Construct lgb.Dataset object from dense matrix, sparse matrix
Guolin Ke's avatar
Guolin Ke committed
623
624
625
626
627
628
#' 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
629
#' @param categorical_feature categorical features
Guolin Ke's avatar
Guolin Ke committed
630
631
632
#' @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}
633
#' 
Guolin Ke's avatar
Guolin Ke committed
634
#' @return constructed dataset
635
#' 
Guolin Ke's avatar
Guolin Ke committed
636
#' @examples
637
#' \dontrun{
638
639
640
641
642
643
644
#' 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)
645
#' }
646
#' 
Guolin Ke's avatar
Guolin Ke committed
647
648
#' @export
lgb.Dataset <- function(data,
649
650
651
                        params = list(),
                        reference = NULL,
                        colnames = NULL,
652
                        categorical_feature = NULL,
653
654
                        free_raw_data = TRUE,
                        info = list(),
Guolin Ke's avatar
Guolin Ke committed
655
                        ...) {
656
657
  
  # Create new dataset
658
  invisible(Dataset$new(data,
659
660
661
662
663
664
665
666
              params,
              reference,
              colnames,
              categorical_feature,
              NULL,
              free_raw_data,
              NULL,
              info,
667
              ...))
668
  
Guolin Ke's avatar
Guolin Ke committed
669
670
}

wxchan's avatar
wxchan committed
671
#' Construct validation data
672
#' 
wxchan's avatar
wxchan committed
673
#' Construct validation data according to training data
674
#' 
Guolin Ke's avatar
Guolin Ke committed
675
676
677
678
#' @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}.
679
#' 
Guolin Ke's avatar
Guolin Ke committed
680
#' @return constructed dataset
681
#' 
Guolin Ke's avatar
Guolin Ke committed
682
#' @examples
683
#' \dontrun{
684
685
686
687
688
689
690
#' 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)
691
#' }
692
#' 
Guolin Ke's avatar
Guolin Ke committed
693
#' @export
694
695
696
lgb.Dataset.create.valid <- function(dataset, data, info = list(), ...) {
  
  # Check if dataset is not a dataset
697
698
  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
699
  }
700
701
  
  # Create validation dataset
702
  invisible(dataset$create_valid(data, info, ...))
703
  
704
}
Guolin Ke's avatar
Guolin Ke committed
705

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

732
#' Dimensions of an lgb.Dataset
733
#' 
Guolin Ke's avatar
Guolin Ke committed
734
735
736
#' 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
737
#' 
Guolin Ke's avatar
Guolin Ke committed
738
#' @return a vector of numbers of rows and of columns
739
#' 
Guolin Ke's avatar
Guolin Ke committed
740
741
742
#' @details
#' Note: since \code{nrow} and \code{ncol} internally use \code{dim}, they can also
#' be directly used with an \code{lgb.Dataset} object.
743
#' 
Guolin Ke's avatar
Guolin Ke committed
744
#' @examples
745
746
747
748
749
750
751
752
753
#' \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)))
754
#' }
755
#' 
Guolin Ke's avatar
Guolin Ke committed
756
757
758
#' @rdname dim
#' @export
dim.lgb.Dataset <- function(x, ...) {
759
760
  
  # Check if dataset is not a dataset
761
762
  if (!lgb.is.Dataset(x)) {
    stop("dim.lgb.Dataset: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
763
  }
764
765
  
  # Return dimensions
766
  x$dim()
767
  
Guolin Ke's avatar
Guolin Ke committed
768
769
770
771
772
}

#' Handling of column names of \code{lgb.Dataset}
#'
#' Only column names are supported for \code{lgb.Dataset}, thus setting of
773
#' row names would have no effect and returned row names would be NULL.
Guolin Ke's avatar
Guolin Ke committed
774
775
776
777
778
779
780
781
782
783
#'
#' @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
784
785
786
787
788
789
790
791
792
793
#' \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)
794
#' }
795
#' 
Guolin Ke's avatar
Guolin Ke committed
796
797
798
#' @rdname dimnames.lgb.Dataset
#' @export
dimnames.lgb.Dataset <- function(x) {
799
800
  
  # Check if dataset is not a dataset
801
802
  if (!lgb.is.Dataset(x)) {
    stop("dimnames.lgb.Dataset: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
803
  }
804
805
  
  # Return dimension names
806
  list(NULL, x$get_colnames())
807
  
Guolin Ke's avatar
Guolin Ke committed
808
809
810
811
812
}

#' @rdname dimnames.lgb.Dataset
#' @export
`dimnames<-.lgb.Dataset` <- function(x, value) {
813
814
815
  
  # Check if invalid element list
  if (!is.list(value) || length(value) != 2L) {
816
    stop("invalid ", sQuote("value"), " given: must be a list of two elements")
817
818
819
820
821
822
823
824
  }
  
  # 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
825
  if (is.null(value[[2]])) {
826
827
    
    # No column names
Guolin Ke's avatar
Guolin Ke committed
828
829
    x$set_colnames(NULL)
    return(x)
830
831
832
833
834
835
    
  }
  
  # 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
836
  }
837
838
  
  # Set column names properly, and return
Guolin Ke's avatar
Guolin Ke committed
839
  x$set_colnames(value[[2]])
840
  x
841
  
Guolin Ke's avatar
Guolin Ke committed
842
843
}

844
#' Slice a dataset
845
#' 
846
#' Get a new \code{lgb.Dataset} containing the specified rows of
Guolin Ke's avatar
Guolin Ke committed
847
#' orginal lgb.Dataset object
848
#' 
Guolin Ke's avatar
Guolin Ke committed
849
850
851
852
#' @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
853
#' 
Guolin Ke's avatar
Guolin Ke committed
854
#' @examples
855
#' \dontrun{
856
857
858
859
860
861
862
#' 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")
863
#' }
864
#' 
Guolin Ke's avatar
Guolin Ke committed
865
#' @export
866
867
868
slice <- function(dataset, ...) {
  UseMethod("slice")
}
Guolin Ke's avatar
Guolin Ke committed
869
870
871
872

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

#' Get information of an lgb.Dataset object
885
#' 
Guolin Ke's avatar
Guolin Ke committed
886
887
888
889
#' @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
890
#' 
Guolin Ke's avatar
Guolin Ke committed
891
892
#' @details
#' The \code{name} field can be one of the following:
893
#' 
Guolin Ke's avatar
Guolin Ke committed
894
895
896
897
898
899
#' \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 ;
#' }
900
#' 
Guolin Ke's avatar
Guolin Ke committed
901
#' @examples
902
#' \dontrun{
903
904
905
906
907
908
909
910
911
912
913
#' 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))
914
#' }
915
#' 
Guolin Ke's avatar
Guolin Ke committed
916
#' @export
917
918
919
getinfo <- function(dataset, ...) {
  UseMethod("getinfo")
}
Guolin Ke's avatar
Guolin Ke committed
920
921
922
923

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

#' Set information of an lgb.Dataset object
936
#' 
Guolin Ke's avatar
Guolin Ke committed
937
938
939
940
941
#' @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
942
#' 
Guolin Ke's avatar
Guolin Ke committed
943
944
#' @details
#' The \code{name} field can be one of the following:
945
#' 
Guolin Ke's avatar
Guolin Ke committed
946
947
948
949
950
951
#' \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}.
#' }
952
#' 
Guolin Ke's avatar
Guolin Ke committed
953
#' @examples
954
#' \dontrun{
955
956
957
958
959
960
961
962
963
964
965
#' 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))
966
#' }
967
#' 
Guolin Ke's avatar
Guolin Ke committed
968
#' @export
969
970
971
setinfo <- function(dataset, ...) {
  UseMethod("setinfo")
}
Guolin Ke's avatar
Guolin Ke committed
972
973
974
975

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

986
#' Set categorical feature of \code{lgb.Dataset}
987
#' 
988
989
#' @param dataset object of class \code{lgb.Dataset}
#' @param categorical_feature categorical features
990
#' 
991
#' @return passed dataset
992
#' 
993
994
#' @examples
#' \dontrun{
995
996
997
998
999
1000
1001
#' 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)
1002
#' }
1003
#' 
1004
1005
1006
#' @rdname lgb.Dataset.set.categorical
#' @export
lgb.Dataset.set.categorical <- function(dataset, categorical_feature) {
1007
1008
  
  # Check if dataset is not a dataset
1009
1010
1011
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.set.categorical: input dataset should be an lgb.Dataset object")
  }
1012
1013
  
  # Set categoricals
1014
  invisible(dataset$set_categorical_feature(categorical_feature))
1015
  
1016
1017
}

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

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