lgb.Dataset.R 30.1 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
101
102
    
    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
      return(ret)
      
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
110
111
      if (!lgb.is.null.handle(private$handle)) {
        return(self)
      }
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 (typeof(private$categorical_feature) == "character") {
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
170
      ref_handle <- NULL
      if (!is.null(private$reference)) {
        ref_handle <- private$reference$.__enclos_env__$private$get_handle()
      }
      handle <- lgb.new.handle()
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
199
200
201
202
203
204
205
206
207
208
          
          # 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
209
        } else {
210
211
212
213
          
          # Unknown data type
          stop("lgb.Dataset.construct: does not support constructing from ", sQuote(class(private$raw_data)))
          
Guolin Ke's avatar
Guolin Ke committed
214
        }
215
        
Guolin Ke's avatar
Guolin Ke committed
216
      } else {
217
218
        
        # Reference is empty
Guolin Ke's avatar
Guolin Ke committed
219
        if (is.null(private$reference)) {
220
          stop("lgb.Dataset.construct: reference cannot be NULL for constructing data subset")
Guolin Ke's avatar
Guolin Ke committed
221
        }
222
223
224
225
226
227
228
229
230
        
        # 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
231
      }
232
233
      
      # Setup class and private type
Guolin Ke's avatar
Guolin Ke committed
234
235
      class(handle) <- "lgb.Dataset.handle"
      private$handle <- handle
236
237
238
239
240
      
      # Set feature names
      if (!is.null(private$colnames)) {
        self$set_colnames(private$colnames)
      }
241

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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