lgb.Dataset.R 30.4 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 (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
      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
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
      }
Guolin Ke's avatar
Guolin Ke committed
232
233
234
      if (lgb.is.null.handle(handle)) {
        stop("lgb.Dataset.construct: cannot create Dataset handle")
      }
235
      # Setup class and private type
Guolin Ke's avatar
Guolin Ke committed
236
237
      class(handle) <- "lgb.Dataset.handle"
      private$handle <- handle
238
239
240
241
242
      
      # Set feature names
      if (!is.null(private$colnames)) {
        self$set_colnames(private$colnames)
      }
243

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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