lgb.Dataset.R 34.1 KB
Newer Older
1
2
3
4
5
6
7
8
# [description] List of valid keys for "info" arguments in lgb.Dataset.
#               Wrapped in a function to take advantage of lazy evaluation
#               (so it doesn't matter what order R sources files during installation).
# [return] A character vector of names.
.INFO_KEYS <- function() {
  return(c("label", "weight", "init_score", "group"))
}

James Lamb's avatar
James Lamb committed
9
#' @importFrom methods is
James Lamb's avatar
James Lamb committed
10
11
12
#' @importFrom R6 R6Class
Dataset <- R6::R6Class(

13
  classname = "lgb.Dataset",
14
  cloneable = FALSE,
Guolin Ke's avatar
Guolin Ke committed
15
  public = list(
James Lamb's avatar
James Lamb committed
16

17
    # Finalize will free up the handles
Guolin Ke's avatar
Guolin Ke committed
18
    finalize = function() {
19
20
21
22
23
      .Call(
        LGBM_DatasetFree_R
        , private$handle
      )
      private$handle <- NULL
24
      return(invisible(NULL))
Guolin Ke's avatar
Guolin Ke committed
25
    },
James Lamb's avatar
James Lamb committed
26

27
    # Initialize will create a starter dataset
Guolin Ke's avatar
Guolin Ke committed
28
    initialize = function(data,
29
30
31
                          params = list(),
                          reference = NULL,
                          colnames = NULL,
32
                          categorical_feature = NULL,
33
34
35
36
                          predictor = NULL,
                          free_raw_data = TRUE,
                          used_indices = NULL,
                          info = list(),
Guolin Ke's avatar
Guolin Ke committed
37
                          ...) {
James Lamb's avatar
James Lamb committed
38

39
      # validate inputs early to avoid unnecessary computation
40
      if (!(is.null(reference) || lgb.is.Dataset(reference))) {
41
42
          stop("lgb.Dataset: If provided, reference must be a ", sQuote("lgb.Dataset"))
      }
43
      if (!(is.null(predictor) || lgb.is.Predictor(predictor))) {
44
45
46
          stop("lgb.Dataset: If provided, predictor must be a ", sQuote("lgb.Predictor"))
      }

47
      # Check for additional parameters
48
      additional_params <- list(...)
James Lamb's avatar
James Lamb committed
49

50
      # Check if attribute key is in the known attribute list
51
      for (key in names(additional_params)) {
James Lamb's avatar
James Lamb committed
52

53
        # Key existing
54
        if (key %in% .INFO_KEYS()) {
James Lamb's avatar
James Lamb committed
55

56
          # Store as info
57
          info[[key]] <- additional_params[[key]]
James Lamb's avatar
James Lamb committed
58

Guolin Ke's avatar
Guolin Ke committed
59
        } else {
James Lamb's avatar
James Lamb committed
60

61
          # Store as param
62
          params[[key]] <- additional_params[[key]]
James Lamb's avatar
James Lamb committed
63

Guolin Ke's avatar
Guolin Ke committed
64
        }
James Lamb's avatar
James Lamb committed
65

Guolin Ke's avatar
Guolin Ke committed
66
      }
James Lamb's avatar
James Lamb committed
67

68
69
70
71
72
73
74
      # Check for matrix format
      if (is.matrix(data)) {
        # Check whether matrix is the correct type first ("double")
        if (storage.mode(data) != "double") {
          storage.mode(data) <- "double"
        }
      }
James Lamb's avatar
James Lamb committed
75

76
77
78
      # Setup private attributes
      private$raw_data <- data
      private$params <- params
Guolin Ke's avatar
Guolin Ke committed
79
      private$reference <- reference
80
      private$colnames <- colnames
81

82
      private$categorical_feature <- categorical_feature
83
84
      private$predictor <- predictor
      private$free_raw_data <- free_raw_data
85
      private$used_indices <- sort(used_indices, decreasing = FALSE)
86
      private$info <- info
87
      private$version <- 0L
James Lamb's avatar
James Lamb committed
88

89
90
      return(invisible(NULL))

Guolin Ke's avatar
Guolin Ke committed
91
    },
James Lamb's avatar
James Lamb committed
92

93
94
95
    create_valid = function(data,
                            info = list(),
                            ...) {
James Lamb's avatar
James Lamb committed
96

97
      # Create new dataset
98
99
100
101
102
103
104
105
106
107
108
109
      ret <- Dataset$new(
        data = data
        , params = private$params
        , reference = self
        , colnames = private$colnames
        , categorical_feature = private$categorical_feature
        , predictor = private$predictor
        , free_raw_data = private$free_raw_data
        , used_indices = NULL
        , info = info
        , ...
      )
James Lamb's avatar
James Lamb committed
110

111
      return(invisible(ret))
James Lamb's avatar
James Lamb committed
112

Guolin Ke's avatar
Guolin Ke committed
113
    },
James Lamb's avatar
James Lamb committed
114

115
    # Dataset constructor
Guolin Ke's avatar
Guolin Ke committed
116
    construct = function() {
James Lamb's avatar
James Lamb committed
117

118
      # Check for handle null
119
      if (!lgb.is.null.handle(x = private$handle)) {
120
        return(invisible(self))
Guolin Ke's avatar
Guolin Ke committed
121
      }
James Lamb's avatar
James Lamb committed
122

Guolin Ke's avatar
Guolin Ke committed
123
124
      # Get feature names
      cnames <- NULL
James Lamb's avatar
James Lamb committed
125
      if (is.matrix(private$raw_data) || methods::is(private$raw_data, "dgCMatrix")) {
Guolin Ke's avatar
Guolin Ke committed
126
127
        cnames <- colnames(private$raw_data)
      }
James Lamb's avatar
James Lamb committed
128

129
      # set feature names if they do not exist
130
      if (is.null(private$colnames) && !is.null(cnames)) {
Guolin Ke's avatar
Guolin Ke committed
131
132
        private$colnames <- as.character(cnames)
      }
James Lamb's avatar
James Lamb committed
133

134
135
      # Get categorical feature index
      if (!is.null(private$categorical_feature)) {
James Lamb's avatar
James Lamb committed
136

137
        # Check for character name
138
        if (is.character(private$categorical_feature)) {
James Lamb's avatar
James Lamb committed
139

140
            cate_indices <- as.list(match(private$categorical_feature, private$colnames) - 1L)
James Lamb's avatar
James Lamb committed
141

142
            # Provided indices, but some indices are missing?
143
            if (sum(is.na(cate_indices)) > 0L) {
144
145
146
147
              stop(
                "lgb.self.get.handle: supplied an unknown feature in categorical_feature: "
                , sQuote(private$categorical_feature[is.na(cate_indices)])
              )
148
            }
James Lamb's avatar
James Lamb committed
149

150
          } else {
James Lamb's avatar
James Lamb committed
151

152
            # Check if more categorical features were output over the feature space
153
            if (max(private$categorical_feature) > length(private$colnames)) {
154
155
156
157
158
159
160
              stop(
                "lgb.self.get.handle: supplied a too large value in categorical_feature: "
                , max(private$categorical_feature)
                , " but only "
                , length(private$colnames)
                , " features"
              )
161
            }
James Lamb's avatar
James Lamb committed
162

163
            # Store indices as [0, n-1] indexed instead of [1, n] indexed
164
            cate_indices <- as.list(private$categorical_feature - 1L)
James Lamb's avatar
James Lamb committed
165

166
          }
James Lamb's avatar
James Lamb committed
167

168
        # Store indices for categorical features
169
        private$params$categorical_feature <- cate_indices
James Lamb's avatar
James Lamb committed
170

171
      }
James Lamb's avatar
James Lamb committed
172

Guolin Ke's avatar
Guolin Ke committed
173
174
      # Check has header or not
      has_header <- FALSE
175
      if (!is.null(private$params$has_header) || !is.null(private$params$header)) {
176
177
178
        params_has_header <- tolower(as.character(private$params$has_header)) == "true"
        params_header <- tolower(as.character(private$params$header)) == "true"
        if (params_has_header || params_header) {
Guolin Ke's avatar
Guolin Ke committed
179
180
181
          has_header <- TRUE
        }
      }
James Lamb's avatar
James Lamb committed
182

Guolin Ke's avatar
Guolin Ke committed
183
      # Generate parameter str
184
      params_str <- lgb.params2str(params = private$params)
James Lamb's avatar
James Lamb committed
185

186
      # Get handle of reference dataset
Guolin Ke's avatar
Guolin Ke committed
187
188
189
190
      ref_handle <- NULL
      if (!is.null(private$reference)) {
        ref_handle <- private$reference$.__enclos_env__$private$get_handle()
      }
James Lamb's avatar
James Lamb committed
191

192
      # Not subsetting
Guolin Ke's avatar
Guolin Ke committed
193
      if (is.null(private$used_indices)) {
James Lamb's avatar
James Lamb committed
194

195
        # Are we using a data file?
196
        if (is.character(private$raw_data)) {
James Lamb's avatar
James Lamb committed
197

198
          handle <- .Call(
199
            LGBM_DatasetCreateFromFile_R
200
            , private$raw_data
201
202
203
            , params_str
            , ref_handle
          )
James Lamb's avatar
James Lamb committed
204

Guolin Ke's avatar
Guolin Ke committed
205
        } else if (is.matrix(private$raw_data)) {
James Lamb's avatar
James Lamb committed
206

207
          # Are we using a matrix?
208
          handle <- .Call(
209
            LGBM_DatasetCreateFromMat_R
210
211
212
213
214
215
            , private$raw_data
            , nrow(private$raw_data)
            , ncol(private$raw_data)
            , params_str
            , ref_handle
          )
James Lamb's avatar
James Lamb committed
216
217

        } else if (methods::is(private$raw_data, "dgCMatrix")) {
218
          if (length(private$raw_data@p) > 2147483647L) {
219
220
            stop("Cannot support large CSC matrix")
          }
221
          # Are we using a dgCMatrix (sparsed matrix column compressed)
222
          handle <- .Call(
223
            LGBM_DatasetCreateFromCSC_R
224
225
226
227
228
229
230
231
232
            , 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
          )
James Lamb's avatar
James Lamb committed
233

Guolin Ke's avatar
Guolin Ke committed
234
        } else {
James Lamb's avatar
James Lamb committed
235

236
          # Unknown data type
237
238
239
240
          stop(
            "lgb.Dataset.construct: does not support constructing from "
            , sQuote(class(private$raw_data))
          )
James Lamb's avatar
James Lamb committed
241

Guolin Ke's avatar
Guolin Ke committed
242
        }
James Lamb's avatar
James Lamb committed
243

Guolin Ke's avatar
Guolin Ke committed
244
      } else {
James Lamb's avatar
James Lamb committed
245

246
        # Reference is empty
Guolin Ke's avatar
Guolin Ke committed
247
        if (is.null(private$reference)) {
248
          stop("lgb.Dataset.construct: reference cannot be NULL for constructing data subset")
Guolin Ke's avatar
Guolin Ke committed
249
        }
James Lamb's avatar
James Lamb committed
250

251
        # Construct subset
252
        handle <- .Call(
253
          LGBM_DatasetGetSubset_R
254
255
256
257
258
          , ref_handle
          , c(private$used_indices) # Adding c() fixes issue in R v3.5
          , length(private$used_indices)
          , params_str
        )
James Lamb's avatar
James Lamb committed
259

Guolin Ke's avatar
Guolin Ke committed
260
      }
261
      if (lgb.is.null.handle(x = handle)) {
Guolin Ke's avatar
Guolin Ke committed
262
263
        stop("lgb.Dataset.construct: cannot create Dataset handle")
      }
264
      # Setup class and private type
Guolin Ke's avatar
Guolin Ke committed
265
266
      class(handle) <- "lgb.Dataset.handle"
      private$handle <- handle
James Lamb's avatar
James Lamb committed
267

268
269
      # Set feature names
      if (!is.null(private$colnames)) {
270
        self$set_colnames(colnames = private$colnames)
271
      }
272

273
274
      # Load init score if requested
      if (!is.null(private$predictor) && is.null(private$used_indices)) {
James Lamb's avatar
James Lamb committed
275

276
        # Setup initial scores
277
        init_score <- private$predictor$predict(
278
          data = private$raw_data
279
280
281
          , rawscore = TRUE
          , reshape = TRUE
        )
James Lamb's avatar
James Lamb committed
282

283
        # Not needed to transpose, for is col_marjor
Guolin Ke's avatar
Guolin Ke committed
284
285
        init_score <- as.vector(init_score)
        private$info$init_score <- init_score
James Lamb's avatar
James Lamb committed
286

287
      }
James Lamb's avatar
James Lamb committed
288

289
290
291
      # Should we free raw data?
      if (isTRUE(private$free_raw_data)) {
        private$raw_data <- NULL
Guolin Ke's avatar
Guolin Ke committed
292
      }
James Lamb's avatar
James Lamb committed
293

294
      # Get private information
295
      if (length(private$info) > 0L) {
James Lamb's avatar
James Lamb committed
296

297
        # Set infos
298
        for (i in seq_along(private$info)) {
James Lamb's avatar
James Lamb committed
299

Guolin Ke's avatar
Guolin Ke committed
300
          p <- private$info[i]
301
          self$setinfo(name = names(p), info = p[[1L]])
James Lamb's avatar
James Lamb committed
302

Guolin Ke's avatar
Guolin Ke committed
303
        }
James Lamb's avatar
James Lamb committed
304

Guolin Ke's avatar
Guolin Ke committed
305
      }
James Lamb's avatar
James Lamb committed
306

307
      # Get label information existence
308
      if (is.null(self$getinfo(name = "label"))) {
Guolin Ke's avatar
Guolin Ke committed
309
310
        stop("lgb.Dataset.construct: label should be set")
      }
James Lamb's avatar
James Lamb committed
311

312
      return(invisible(self))
James Lamb's avatar
James Lamb committed
313

Guolin Ke's avatar
Guolin Ke committed
314
    },
James Lamb's avatar
James Lamb committed
315

316
    # Dimension function
Guolin Ke's avatar
Guolin Ke committed
317
    dim = function() {
James Lamb's avatar
James Lamb committed
318

319
      # Check for handle
320
      if (!lgb.is.null.handle(x = private$handle)) {
James Lamb's avatar
James Lamb committed
321

322
323
        num_row <- 0L
        num_col <- 0L
James Lamb's avatar
James Lamb committed
324

325
        # Get numeric data and numeric features
326
327
328
329
330
331
332
333
334
335
        .Call(
          LGBM_DatasetGetNumData_R
          , private$handle
          , num_row
        )
        .Call(
          LGBM_DatasetGetNumFeature_R
          , private$handle
          , num_col
        )
336
        return(
337
          c(num_row, num_col)
338
        )
James Lamb's avatar
James Lamb committed
339
340
341

      } else if (is.matrix(private$raw_data) || methods::is(private$raw_data, "dgCMatrix")) {

342
        # Check if dgCMatrix (sparse matrix column compressed)
343
        # NOTE: requires Matrix package
344
        return(dim(private$raw_data))
James Lamb's avatar
James Lamb committed
345

Guolin Ke's avatar
Guolin Ke committed
346
      } else {
James Lamb's avatar
James Lamb committed
347

348
        # Trying to work with unknown dimensions is not possible
349
350
351
352
        stop(
          "dim: cannot get dimensions before dataset has been constructed, "
          , "please call lgb.Dataset.construct explicitly"
        )
James Lamb's avatar
James Lamb committed
353

Guolin Ke's avatar
Guolin Ke committed
354
      }
James Lamb's avatar
James Lamb committed
355

Guolin Ke's avatar
Guolin Ke committed
356
    },
James Lamb's avatar
James Lamb committed
357

358
    # Get column names
Guolin Ke's avatar
Guolin Ke committed
359
    get_colnames = function() {
James Lamb's avatar
James Lamb committed
360

361
      # Check for handle
362
      if (!lgb.is.null.handle(x = private$handle)) {
363
        private$colnames <- .Call(
364
365
          LGBM_DatasetGetFeatureNames_R
          , private$handle
366
        )
367
        return(private$colnames)
James Lamb's avatar
James Lamb committed
368
369
370

      } else if (is.matrix(private$raw_data) || methods::is(private$raw_data, "dgCMatrix")) {

371
        # Check if dgCMatrix (sparse matrix column compressed)
372
        return(colnames(private$raw_data))
James Lamb's avatar
James Lamb committed
373

Guolin Ke's avatar
Guolin Ke committed
374
      } else {
James Lamb's avatar
James Lamb committed
375

376
        # Trying to work with unknown dimensions is not possible
377
378
379
380
        stop(
          "dim: cannot get dimensions before dataset has been constructed, please call "
          , "lgb.Dataset.construct explicitly"
        )
James Lamb's avatar
James Lamb committed
381

Guolin Ke's avatar
Guolin Ke committed
382
      }
James Lamb's avatar
James Lamb committed
383

Guolin Ke's avatar
Guolin Ke committed
384
    },
James Lamb's avatar
James Lamb committed
385

386
    # Set column names
Guolin Ke's avatar
Guolin Ke committed
387
    set_colnames = function(colnames) {
James Lamb's avatar
James Lamb committed
388

389
390
      # Check column names non-existence
      if (is.null(colnames)) {
391
        return(invisible(self))
392
      }
James Lamb's avatar
James Lamb committed
393

394
      # Check empty column names
Guolin Ke's avatar
Guolin Ke committed
395
      colnames <- as.character(colnames)
396
      if (length(colnames) == 0L) {
397
        return(invisible(self))
398
      }
James Lamb's avatar
James Lamb committed
399

400
      # Write column names
Guolin Ke's avatar
Guolin Ke committed
401
      private$colnames <- colnames
402
      if (!lgb.is.null.handle(x = private$handle)) {
James Lamb's avatar
James Lamb committed
403

404
        # Merge names with tab separation
Guolin Ke's avatar
Guolin Ke committed
405
        merged_name <- paste0(as.list(private$colnames), collapse = "\t")
406
407
        .Call(
          LGBM_DatasetSetFeatureNames_R
408
          , private$handle
409
          , merged_name
410
        )
James Lamb's avatar
James Lamb committed
411

Guolin Ke's avatar
Guolin Ke committed
412
      }
James Lamb's avatar
James Lamb committed
413

414
      return(invisible(self))
James Lamb's avatar
James Lamb committed
415

Guolin Ke's avatar
Guolin Ke committed
416
    },
James Lamb's avatar
James Lamb committed
417

418
    # Get information
Guolin Ke's avatar
Guolin Ke committed
419
    getinfo = function(name) {
James Lamb's avatar
James Lamb committed
420

421
      # Check if attribute key is in the known attribute list
422
423
      if (!is.character(name) || length(name) != 1L || !name %in% .INFO_KEYS()) {
        stop("getinfo: name must one of the following: ", paste0(sQuote(.INFO_KEYS()), collapse = ", "))
Guolin Ke's avatar
Guolin Ke committed
424
      }
James Lamb's avatar
James Lamb committed
425

426
      # Check for info name and handle
427
      if (is.null(private$info[[name]])) {
428

429
        if (lgb.is.null.handle(x = private$handle)) {
430
          stop("Cannot perform getinfo before constructing Dataset.")
431
        }
432

433
        # Get field size of info
434
        info_len <- 0L
435
436
        .Call(
          LGBM_DatasetGetFieldSize_R
437
          , private$handle
438
          , name
439
          , info_len
440
        )
James Lamb's avatar
James Lamb committed
441

442
        # Check if info is not empty
443
        if (info_len > 0L) {
James Lamb's avatar
James Lamb committed
444

445
          # Get back fields
Guolin Ke's avatar
Guolin Ke committed
446
          ret <- NULL
447
448
449
450
451
          ret <- if (name == "group") {
            integer(info_len) # Integer
          } else {
            numeric(info_len) # Numeric
          }
James Lamb's avatar
James Lamb committed
452

453
454
          .Call(
            LGBM_DatasetGetField_R
455
            , private$handle
456
            , name
457
            , ret
458
          )
James Lamb's avatar
James Lamb committed
459

Guolin Ke's avatar
Guolin Ke committed
460
          private$info[[name]] <- ret
James Lamb's avatar
James Lamb committed
461

Guolin Ke's avatar
Guolin Ke committed
462
463
        }
      }
James Lamb's avatar
James Lamb committed
464

465
      return(private$info[[name]])
James Lamb's avatar
James Lamb committed
466

Guolin Ke's avatar
Guolin Ke committed
467
    },
James Lamb's avatar
James Lamb committed
468

469
    # Set information
Guolin Ke's avatar
Guolin Ke committed
470
    setinfo = function(name, info) {
James Lamb's avatar
James Lamb committed
471

472
      # Check if attribute key is in the known attribute list
473
474
      if (!is.character(name) || length(name) != 1L || !name %in% .INFO_KEYS()) {
        stop("setinfo: name must one of the following: ", paste0(sQuote(.INFO_KEYS()), collapse = ", "))
475
      }
James Lamb's avatar
James Lamb committed
476

477
478
479
480
481
482
      # Check for type of information
      info <- if (name == "group") {
        as.integer(info) # Integer
      } else {
        as.numeric(info) # Numeric
      }
James Lamb's avatar
James Lamb committed
483

484
      # Store information privately
Guolin Ke's avatar
Guolin Ke committed
485
      private$info[[name]] <- info
James Lamb's avatar
James Lamb committed
486

487
      if (!lgb.is.null.handle(x = private$handle) && !is.null(info)) {
James Lamb's avatar
James Lamb committed
488

489
        if (length(info) > 0L) {
James Lamb's avatar
James Lamb committed
490

491
492
          .Call(
            LGBM_DatasetSetField_R
493
            , private$handle
494
            , name
495
496
497
            , info
            , length(info)
          )
James Lamb's avatar
James Lamb committed
498

499
500
          private$version <- private$version + 1L

Guolin Ke's avatar
Guolin Ke committed
501
        }
James Lamb's avatar
James Lamb committed
502

Guolin Ke's avatar
Guolin Ke committed
503
      }
James Lamb's avatar
James Lamb committed
504

505
      return(invisible(self))
James Lamb's avatar
James Lamb committed
506

Guolin Ke's avatar
Guolin Ke committed
507
    },
James Lamb's avatar
James Lamb committed
508

509
    # Slice dataset
Guolin Ke's avatar
Guolin Ke committed
510
    slice = function(idxset, ...) {
James Lamb's avatar
James Lamb committed
511

512
      # Perform slicing
513
514
515
516
517
518
519
520
521
522
523
524
525
      return(
        Dataset$new(
          data = NULL
          , params = private$params
          , reference = self
          , colnames = private$colnames
          , categorical_feature = private$categorical_feature
          , predictor = private$predictor
          , free_raw_data = private$free_raw_data
          , used_indices = sort(idxset, decreasing = FALSE)
          , info = NULL
          , ...
        )
526
      )
James Lamb's avatar
James Lamb committed
527

Guolin Ke's avatar
Guolin Ke committed
528
    },
James Lamb's avatar
James Lamb committed
529

530
531
532
    # [description] Update Dataset parameters. If it has not been constructed yet,
    #               this operation just happens on the R side (updating private$params).
    #               If it has been constructed, parameters will be updated on the C++ side.
533
    update_params = function(params) {
534
535
536
      if (length(params) == 0L) {
        return(invisible(self))
      }
537
      if (lgb.is.null.handle(x = private$handle)) {
538
539
        private$params <- modifyList(private$params, params)
      } else {
540
541
        tryCatch({
          .Call(
542
            LGBM_DatasetUpdateParamChecking_R
543
544
545
546
547
548
            , lgb.params2str(params = private$params)
            , lgb.params2str(params = params)
          )
        }, error = function(e) {
          # If updating failed but raw data is not available, raise an error because
          # achieving what the user asked for is not possible
549
          if (is.null(private$raw_data)) {
550
            stop(e)
551
552
          }

553
554
          # If updating failed but raw data is available, modify the params
          # on the R side and re-set ("deconstruct") the Dataset
555
556
          private$params <- modifyList(private$params, params)
          self$finalize()
557
        })
558
      }
559
      return(invisible(self))
James Lamb's avatar
James Lamb committed
560

Guolin Ke's avatar
Guolin Ke committed
561
    },
James Lamb's avatar
James Lamb committed
562

563
564
565
566
567
568
569
570
571
572
573
    get_params = function() {
      dataset_params <- unname(unlist(.DATASET_PARAMETERS()))
      ret <- list()
      for (param_key in names(private$params)) {
        if (param_key %in% dataset_params) {
          ret[[param_key]] <- private$params[[param_key]]
        }
      }
      return(ret)
    },

574
    # Set categorical feature parameter
575
    set_categorical_feature = function(categorical_feature) {
James Lamb's avatar
James Lamb committed
576

577
578
      # Check for identical input
      if (identical(private$categorical_feature, categorical_feature)) {
579
        return(invisible(self))
580
      }
James Lamb's avatar
James Lamb committed
581

582
      # Check for empty data
583
      if (is.null(private$raw_data)) {
584
585
        stop("set_categorical_feature: cannot set categorical feature after freeing raw data,
          please set ", sQuote("free_raw_data = FALSE"), " when you construct lgb.Dataset")
586
      }
James Lamb's avatar
James Lamb committed
587

588
      # Overwrite categorical features
589
      private$categorical_feature <- categorical_feature
James Lamb's avatar
James Lamb committed
590

591
      # Finalize and return self
592
      self$finalize()
593
      return(invisible(self))
James Lamb's avatar
James Lamb committed
594

595
    },
James Lamb's avatar
James Lamb committed
596

597
    # Set reference
Guolin Ke's avatar
Guolin Ke committed
598
    set_reference = function(reference) {
James Lamb's avatar
James Lamb committed
599

600
      # Set known references
601
602
603
      self$set_categorical_feature(categorical_feature = reference$.__enclos_env__$private$categorical_feature)
      self$set_colnames(colnames = reference$get_colnames())
      private$set_predictor(predictor = reference$.__enclos_env__$private$predictor)
James Lamb's avatar
James Lamb committed
604

605
606
      # Check for identical references
      if (identical(private$reference, reference)) {
607
        return(invisible(self))
608
      }
James Lamb's avatar
James Lamb committed
609

610
      # Check for empty data
Guolin Ke's avatar
Guolin Ke committed
611
      if (is.null(private$raw_data)) {
James Lamb's avatar
James Lamb committed
612

613
614
        stop("set_reference: cannot set reference after freeing raw data,
          please set ", sQuote("free_raw_data = FALSE"), " when you construct lgb.Dataset")
James Lamb's avatar
James Lamb committed
615

Guolin Ke's avatar
Guolin Ke committed
616
      }
James Lamb's avatar
James Lamb committed
617

618
      # Check for non-existing reference
Guolin Ke's avatar
Guolin Ke committed
619
      if (!is.null(reference)) {
James Lamb's avatar
James Lamb committed
620

621
        # Reference is unknown
622
        if (!lgb.is.Dataset(reference)) {
623
          stop("set_reference: Can only use lgb.Dataset as a reference")
Guolin Ke's avatar
Guolin Ke committed
624
        }
James Lamb's avatar
James Lamb committed
625

Guolin Ke's avatar
Guolin Ke committed
626
      }
James Lamb's avatar
James Lamb committed
627

628
      # Store reference
Guolin Ke's avatar
Guolin Ke committed
629
      private$reference <- reference
James Lamb's avatar
James Lamb committed
630

631
      # Finalize and return self
Guolin Ke's avatar
Guolin Ke committed
632
      self$finalize()
633
      return(invisible(self))
James Lamb's avatar
James Lamb committed
634

Guolin Ke's avatar
Guolin Ke committed
635
    },
James Lamb's avatar
James Lamb committed
636

637
    # Save binary model
Guolin Ke's avatar
Guolin Ke committed
638
    save_binary = function(fname) {
James Lamb's avatar
James Lamb committed
639

640
      # Store binary data
Guolin Ke's avatar
Guolin Ke committed
641
      self$construct()
642
643
      .Call(
        LGBM_DatasetSaveBinary_R
644
        , private$handle
645
        , fname
646
      )
647
      return(invisible(self))
Guolin Ke's avatar
Guolin Ke committed
648
    }
James Lamb's avatar
James Lamb committed
649

Guolin Ke's avatar
Guolin Ke committed
650
651
  ),
  private = list(
652
653
654
655
656
    handle = NULL,
    raw_data = NULL,
    params = list(),
    reference = NULL,
    colnames = NULL,
657
    categorical_feature = NULL,
658
659
660
661
    predictor = NULL,
    free_raw_data = TRUE,
    used_indices = NULL,
    info = NULL,
662
    version = 0L,
James Lamb's avatar
James Lamb committed
663

664
665
    # Get handle
    get_handle = function() {
James Lamb's avatar
James Lamb committed
666

667
      # Get handle and construct if needed
668
      if (lgb.is.null.handle(x = private$handle)) {
669
670
        self$construct()
      }
671
      return(private$handle)
James Lamb's avatar
James Lamb committed
672

Guolin Ke's avatar
Guolin Ke committed
673
    },
James Lamb's avatar
James Lamb committed
674

675
    # Set predictor
Guolin Ke's avatar
Guolin Ke committed
676
    set_predictor = function(predictor) {
James Lamb's avatar
James Lamb committed
677

678
      if (identical(private$predictor, predictor)) {
679
        return(invisible(self))
680
      }
James Lamb's avatar
James Lamb committed
681

682
      # Check for empty data
Guolin Ke's avatar
Guolin Ke committed
683
      if (is.null(private$raw_data)) {
684
685
        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
686
      }
James Lamb's avatar
James Lamb committed
687

688
      # Check for empty predictor
Guolin Ke's avatar
Guolin Ke committed
689
      if (!is.null(predictor)) {
James Lamb's avatar
James Lamb committed
690

691
        # Predictor is unknown
692
        if (!lgb.is.Predictor(predictor)) {
693
          stop("set_predictor: Can only use lgb.Predictor as predictor")
Guolin Ke's avatar
Guolin Ke committed
694
        }
James Lamb's avatar
James Lamb committed
695

Guolin Ke's avatar
Guolin Ke committed
696
      }
James Lamb's avatar
James Lamb committed
697

698
      # Store predictor
Guolin Ke's avatar
Guolin Ke committed
699
      private$predictor <- predictor
James Lamb's avatar
James Lamb committed
700

701
      # Finalize and return self
Guolin Ke's avatar
Guolin Ke committed
702
      self$finalize()
703
      return(invisible(self))
James Lamb's avatar
James Lamb committed
704

Guolin Ke's avatar
Guolin Ke committed
705
    }
James Lamb's avatar
James Lamb committed
706

Guolin Ke's avatar
Guolin Ke committed
707
708
709
  )
)

710
711
712
#' @title Construct \code{lgb.Dataset} object
#' @description Construct \code{lgb.Dataset} object from dense matrix, sparse matrix
#'              or local file (that was created previously by saving an \code{lgb.Dataset}).
Guolin Ke's avatar
Guolin Ke committed
713
#' @param data a \code{matrix} object, a \code{dgCMatrix} object or a character representing a filename
714
715
716
717
718
719
720
#' @param params a list of parameters. See
#'               \href{https://lightgbm.readthedocs.io/en/latest/Parameters.html#dataset-parameters}{
#'               The "Dataset Parameters" section of the documentation} for a list of parameters
#'               and valid values.
#' @param reference reference dataset. When LightGBM creates a Dataset, it does some preprocessing like binning
#'                  continuous features into histograms. If you want to apply the same bin boundaries from an existing
#'                  dataset to new \code{data}, pass that existing Dataset to this argument.
Guolin Ke's avatar
Guolin Ke committed
721
#' @param colnames names of columns
722
723
724
725
726
727
728
729
#' @param categorical_feature categorical features. This can either be a character vector of feature
#'                            names or an integer vector with the indices of the features (e.g.
#'                            \code{c(1L, 10L)} to say "the first and tenth columns").
#' @param free_raw_data LightGBM constructs its data format, called a "Dataset", from tabular data.
#'                      By default, that Dataset object on the R side does not keep a copy of the raw data.
#'                      This reduces LightGBM's memory consumption, but it means that the Dataset object
#'                      cannot be changed after it has been constructed. If you'd prefer to be able to
#'                      change the Dataset object after construction, set \code{free_raw_data = FALSE}.
Nikita Titov's avatar
Nikita Titov committed
730
#' @param info a list of information of the \code{lgb.Dataset} object
Guolin Ke's avatar
Guolin Ke committed
731
#' @param ... other information to pass to \code{info} or parameters pass to \code{params}
James Lamb's avatar
James Lamb committed
732
#'
Guolin Ke's avatar
Guolin Ke committed
733
#' @return constructed dataset
James Lamb's avatar
James Lamb committed
734
#'
Guolin Ke's avatar
Guolin Ke committed
735
#' @examples
736
#' \donttest{
737
738
739
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
740
741
742
#' data_file <- tempfile(fileext = ".data")
#' lgb.Dataset.save(dtrain, data_file)
#' dtrain <- lgb.Dataset(data_file)
743
#' lgb.Dataset.construct(dtrain)
744
#' }
Guolin Ke's avatar
Guolin Ke committed
745
746
#' @export
lgb.Dataset <- function(data,
747
748
749
                        params = list(),
                        reference = NULL,
                        colnames = NULL,
750
                        categorical_feature = NULL,
751
752
                        free_raw_data = TRUE,
                        info = list(),
Guolin Ke's avatar
Guolin Ke committed
753
                        ...) {
James Lamb's avatar
James Lamb committed
754

755
  # Create new dataset
756
757
758
759
760
761
762
763
764
765
766
767
768
769
  return(
    invisible(Dataset$new(
      data = data
      , params = params
      , reference = reference
      , colnames = colnames
      , categorical_feature = categorical_feature
      , predictor = NULL
      , free_raw_data = free_raw_data
      , used_indices = NULL
      , info = info
      , ...
    ))
  )
James Lamb's avatar
James Lamb committed
770

Guolin Ke's avatar
Guolin Ke committed
771
772
}

773
774
775
#' @name lgb.Dataset.create.valid
#' @title Construct validation data
#' @description Construct validation data according to training data
Guolin Ke's avatar
Guolin Ke committed
776
777
#' @param dataset \code{lgb.Dataset} object, training data
#' @param data a \code{matrix} object, a \code{dgCMatrix} object or a character representing a filename
Nikita Titov's avatar
Nikita Titov committed
778
#' @param info a list of information of the \code{lgb.Dataset} object
Guolin Ke's avatar
Guolin Ke committed
779
#' @param ... other information to pass to \code{info}.
James Lamb's avatar
James Lamb committed
780
#'
Guolin Ke's avatar
Guolin Ke committed
781
#' @return constructed dataset
James Lamb's avatar
James Lamb committed
782
#'
Guolin Ke's avatar
Guolin Ke committed
783
#' @examples
784
#' \donttest{
785
786
787
788
789
790
#' 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)
791
#' }
Guolin Ke's avatar
Guolin Ke committed
792
#' @export
793
lgb.Dataset.create.valid <- function(dataset, data, info = list(), ...) {
James Lamb's avatar
James Lamb committed
794

795
  # Check if dataset is not a dataset
796
  if (!lgb.is.Dataset(x = dataset)) {
797
    stop("lgb.Dataset.create.valid: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
798
  }
James Lamb's avatar
James Lamb committed
799

800
  # Create validation dataset
801
  return(invisible(dataset$create_valid(data = data, info = info, ...)))
James Lamb's avatar
James Lamb committed
802

803
}
Guolin Ke's avatar
Guolin Ke committed
804

805
806
807
#' @name lgb.Dataset.construct
#' @title Construct Dataset explicitly
#' @description Construct Dataset explicitly
Guolin Ke's avatar
Guolin Ke committed
808
#' @param dataset Object of class \code{lgb.Dataset}
James Lamb's avatar
James Lamb committed
809
#'
Guolin Ke's avatar
Guolin Ke committed
810
#' @examples
811
#' \donttest{
812
813
814
815
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
816
#' }
817
#' @return constructed dataset
Guolin Ke's avatar
Guolin Ke committed
818
819
#' @export
lgb.Dataset.construct <- function(dataset) {
James Lamb's avatar
James Lamb committed
820

821
  # Check if dataset is not a dataset
822
  if (!lgb.is.Dataset(x = dataset)) {
823
    stop("lgb.Dataset.construct: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
824
  }
James Lamb's avatar
James Lamb committed
825

826
  # Construct the dataset
827
  return(invisible(dataset$construct()))
James Lamb's avatar
James Lamb committed
828

Guolin Ke's avatar
Guolin Ke committed
829
830
}

831
832
#' @title Dimensions of an \code{lgb.Dataset}
#' @description Returns a vector of numbers of rows and of columns in an \code{lgb.Dataset}.
Guolin Ke's avatar
Guolin Ke committed
833
834
#' @param x Object of class \code{lgb.Dataset}
#' @param ... other parameters
James Lamb's avatar
James Lamb committed
835
#'
Guolin Ke's avatar
Guolin Ke committed
836
#' @return a vector of numbers of rows and of columns
James Lamb's avatar
James Lamb committed
837
#'
Guolin Ke's avatar
Guolin Ke committed
838
839
840
#' @details
#' Note: since \code{nrow} and \code{ncol} internally use \code{dim}, they can also
#' be directly used with an \code{lgb.Dataset} object.
James Lamb's avatar
James Lamb committed
841
#'
Guolin Ke's avatar
Guolin Ke committed
842
#' @examples
843
#' \donttest{
844
845
846
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
James Lamb's avatar
James Lamb committed
847
#'
848
849
850
#' stopifnot(nrow(dtrain) == nrow(train$data))
#' stopifnot(ncol(dtrain) == ncol(train$data))
#' stopifnot(all(dim(dtrain) == dim(train$data)))
851
#' }
Guolin Ke's avatar
Guolin Ke committed
852
853
854
#' @rdname dim
#' @export
dim.lgb.Dataset <- function(x, ...) {
James Lamb's avatar
James Lamb committed
855

856
  # Check if dataset is not a dataset
857
  if (!lgb.is.Dataset(x = x)) {
858
    stop("dim.lgb.Dataset: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
859
  }
James Lamb's avatar
James Lamb committed
860

861
  return(x$dim())
James Lamb's avatar
James Lamb committed
862

Guolin Ke's avatar
Guolin Ke committed
863
864
}

865
866
867
#' @title Handling of column names of \code{lgb.Dataset}
#' @description Only column names are supported for \code{lgb.Dataset}, thus setting of
#'              row names would have no effect and returned row names would be NULL.
Guolin Ke's avatar
Guolin Ke committed
868
869
#' @param x object of class \code{lgb.Dataset}
#' @param value a list of two elements: the first one is ignored
870
#'              and the second one is column names
Guolin Ke's avatar
Guolin Ke committed
871
872
873
874
875
876
#'
#' @details
#' Generic \code{dimnames} methods are used by \code{colnames}.
#' Since row names are irrelevant, it is recommended to use \code{colnames} directly.
#'
#' @examples
877
#' \donttest{
878
879
880
881
882
883
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
#' dimnames(dtrain)
#' colnames(dtrain)
884
#' colnames(dtrain) <- make.names(seq_len(ncol(train$data)))
885
#' print(dtrain, verbose = TRUE)
886
#' }
Guolin Ke's avatar
Guolin Ke committed
887
#' @rdname dimnames.lgb.Dataset
888
#' @return A list with the dimension names of the dataset
Guolin Ke's avatar
Guolin Ke committed
889
890
#' @export
dimnames.lgb.Dataset <- function(x) {
James Lamb's avatar
James Lamb committed
891

892
  # Check if dataset is not a dataset
893
  if (!lgb.is.Dataset(x = x)) {
894
    stop("dimnames.lgb.Dataset: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
895
  }
James Lamb's avatar
James Lamb committed
896

897
  # Return dimension names
898
  return(list(NULL, x$get_colnames()))
James Lamb's avatar
James Lamb committed
899

Guolin Ke's avatar
Guolin Ke committed
900
901
902
903
904
}

#' @rdname dimnames.lgb.Dataset
#' @export
`dimnames<-.lgb.Dataset` <- function(x, value) {
James Lamb's avatar
James Lamb committed
905

906
  # Check if invalid element list
907
  if (!identical(class(value), "list") || length(value) != 2L) {
908
    stop("invalid ", sQuote("value"), " given: must be a list of two elements")
909
  }
James Lamb's avatar
James Lamb committed
910

911
912
913
914
  # Check for unknown row names
  if (!is.null(value[[1L]])) {
    stop("lgb.Dataset does not have rownames")
  }
James Lamb's avatar
James Lamb committed
915

916
  if (is.null(value[[2L]])) {
James Lamb's avatar
James Lamb committed
917

918
    x$set_colnames(colnames = NULL)
Guolin Ke's avatar
Guolin Ke committed
919
    return(x)
James Lamb's avatar
James Lamb committed
920

921
  }
James Lamb's avatar
James Lamb committed
922

923
  # Check for unmatching column size
924
  if (ncol(x) != length(value[[2L]])) {
925
926
    stop(
      "can't assign "
927
      , sQuote(length(value[[2L]]))
928
929
930
931
      , " colnames to an lgb.Dataset with "
      , sQuote(ncol(x))
      , " columns"
    )
Guolin Ke's avatar
Guolin Ke committed
932
  }
James Lamb's avatar
James Lamb committed
933

934
  # Set column names properly, and return
935
  x$set_colnames(colnames = value[[2L]])
936
  return(x)
James Lamb's avatar
James Lamb committed
937

Guolin Ke's avatar
Guolin Ke committed
938
939
}

940
941
942
#' @title Slice a dataset
#' @description Get a new \code{lgb.Dataset} containing the specified rows of
#'              original \code{lgb.Dataset} object
Nikita Titov's avatar
Nikita Titov committed
943
#' @param dataset Object of class \code{lgb.Dataset}
944
#' @param idxset an integer vector of indices of rows needed
Guolin Ke's avatar
Guolin Ke committed
945
946
#' @param ... other parameters (currently not used)
#' @return constructed sub dataset
James Lamb's avatar
James Lamb committed
947
#'
Guolin Ke's avatar
Guolin Ke committed
948
#' @examples
949
#' \donttest{
950
951
952
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
James Lamb's avatar
James Lamb committed
953
#'
954
#' dsub <- lightgbm::slice(dtrain, seq_len(42L))
955
#' lgb.Dataset.construct(dsub)
956
#' labels <- lightgbm::getinfo(dsub, "label")
957
#' }
Guolin Ke's avatar
Guolin Ke committed
958
#' @export
959
960
961
slice <- function(dataset, ...) {
  UseMethod("slice")
}
Guolin Ke's avatar
Guolin Ke committed
962
963
964
965

#' @rdname slice
#' @export
slice.lgb.Dataset <- function(dataset, idxset, ...) {
James Lamb's avatar
James Lamb committed
966

967
  # Check if dataset is not a dataset
968
  if (!lgb.is.Dataset(x = dataset)) {
969
    stop("slice.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
970
  }
James Lamb's avatar
James Lamb committed
971

972
  return(invisible(dataset$slice(idxset = idxset, ...)))
James Lamb's avatar
James Lamb committed
973

Guolin Ke's avatar
Guolin Ke committed
974
975
}

976
977
978
#' @name getinfo
#' @title Get information of an \code{lgb.Dataset} object
#' @description Get one attribute of a \code{lgb.Dataset}
Guolin Ke's avatar
Guolin Ke committed
979
980
981
982
#' @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
James Lamb's avatar
James Lamb committed
983
#'
Guolin Ke's avatar
Guolin Ke committed
984
985
#' @details
#' The \code{name} field can be one of the following:
James Lamb's avatar
James Lamb committed
986
#'
Guolin Ke's avatar
Guolin Ke committed
987
988
989
#' \itemize{
#'     \item \code{label}: label lightgbm learn from ;
#'     \item \code{weight}: to do a weight rescale ;
990
991
992
993
994
#'     \item{\code{group}: used for learning-to-rank tasks. An integer vector describing how to
#'         group rows together as ordered results from the same set of candidate results to be ranked.
#'         For example, if you have a 100-document dataset with \code{group = c(10, 20, 40, 10, 10, 10)},
#'         that means that you have 6 groups, where the first 10 records are in the first group,
#'         records 11-30 are in the second group, etc.}
Nikita Titov's avatar
Nikita Titov committed
995
#'     \item \code{init_score}: initial score is the base prediction lightgbm will boost from.
Guolin Ke's avatar
Guolin Ke committed
996
#' }
James Lamb's avatar
James Lamb committed
997
#'
Guolin Ke's avatar
Guolin Ke committed
998
#' @examples
999
#' \donttest{
1000
1001
1002
1003
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
James Lamb's avatar
James Lamb committed
1004
#'
1005
1006
#' labels <- lightgbm::getinfo(dtrain, "label")
#' lightgbm::setinfo(dtrain, "label", 1 - labels)
James Lamb's avatar
James Lamb committed
1007
#'
1008
1009
#' labels2 <- lightgbm::getinfo(dtrain, "label")
#' stopifnot(all(labels2 == 1 - labels))
1010
#' }
Guolin Ke's avatar
Guolin Ke committed
1011
#' @export
1012
1013
1014
getinfo <- function(dataset, ...) {
  UseMethod("getinfo")
}
Guolin Ke's avatar
Guolin Ke committed
1015
1016
1017
1018

#' @rdname getinfo
#' @export
getinfo.lgb.Dataset <- function(dataset, name, ...) {
James Lamb's avatar
James Lamb committed
1019

1020
  # Check if dataset is not a dataset
1021
  if (!lgb.is.Dataset(x = dataset)) {
1022
    stop("getinfo.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1023
  }
James Lamb's avatar
James Lamb committed
1024

1025
  return(dataset$getinfo(name = name))
James Lamb's avatar
James Lamb committed
1026

Guolin Ke's avatar
Guolin Ke committed
1027
1028
}

1029
1030
1031
#' @name setinfo
#' @title Set information of an \code{lgb.Dataset} object
#' @description Set one attribute of a \code{lgb.Dataset}
Nikita Titov's avatar
Nikita Titov committed
1032
#' @param dataset Object of class \code{lgb.Dataset}
Guolin Ke's avatar
Guolin Ke committed
1033
1034
1035
#' @param name the name of the field to get
#' @param info the specific field of information to set
#' @param ... other parameters
1036
#' @return the dataset you passed in
James Lamb's avatar
James Lamb committed
1037
#'
Guolin Ke's avatar
Guolin Ke committed
1038
1039
#' @details
#' The \code{name} field can be one of the following:
James Lamb's avatar
James Lamb committed
1040
#'
Guolin Ke's avatar
Guolin Ke committed
1041
#' \itemize{
1042
1043
1044
1045
1046
#'     \item{\code{label}: vector of labels to use as the target variable}
#'     \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}: used for learning-to-rank tasks. An integer vector describing how to
#'         group rows together as ordered results from the same set of candidate results to be ranked.
1047
1048
1049
#'         For example, if you have a 100-document dataset with \code{group = c(10, 20, 40, 10, 10, 10)},
#'         that means that you have 6 groups, where the first 10 records are in the first group,
#'         records 11-30 are in the second group, etc.}
Guolin Ke's avatar
Guolin Ke committed
1050
#' }
James Lamb's avatar
James Lamb committed
1051
#'
Guolin Ke's avatar
Guolin Ke committed
1052
#' @examples
1053
#' \donttest{
1054
1055
1056
1057
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
James Lamb's avatar
James Lamb committed
1058
#'
1059
1060
#' labels <- lightgbm::getinfo(dtrain, "label")
#' lightgbm::setinfo(dtrain, "label", 1 - labels)
James Lamb's avatar
James Lamb committed
1061
#'
1062
1063
#' labels2 <- lightgbm::getinfo(dtrain, "label")
#' stopifnot(all.equal(labels2, 1 - labels))
1064
#' }
Guolin Ke's avatar
Guolin Ke committed
1065
#' @export
1066
1067
1068
setinfo <- function(dataset, ...) {
  UseMethod("setinfo")
}
Guolin Ke's avatar
Guolin Ke committed
1069
1070
1071
1072

#' @rdname setinfo
#' @export
setinfo.lgb.Dataset <- function(dataset, name, info, ...) {
James Lamb's avatar
James Lamb committed
1073

1074
  if (!lgb.is.Dataset(x = dataset)) {
1075
    stop("setinfo.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1076
  }
James Lamb's avatar
James Lamb committed
1077

1078
  return(invisible(dataset$setinfo(name = name, info = info)))
Guolin Ke's avatar
Guolin Ke committed
1079
1080
}

1081
1082
1083
1084
#' @name lgb.Dataset.set.categorical
#' @title Set categorical feature of \code{lgb.Dataset}
#' @description Set the categorical features of an \code{lgb.Dataset} object. Use this function
#'              to tell LightGBM which features should be treated as categorical.
1085
#' @param dataset object of class \code{lgb.Dataset}
1086
1087
1088
#' @param categorical_feature categorical features. This can either be a character vector of feature
#'                            names or an integer vector with the indices of the features (e.g.
#'                            \code{c(1L, 10L)} to say "the first and tenth columns").
1089
#' @return the dataset you passed in
James Lamb's avatar
James Lamb committed
1090
#'
1091
#' @examples
1092
#' \donttest{
1093
1094
1095
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
1096
1097
1098
#' data_file <- tempfile(fileext = ".data")
#' lgb.Dataset.save(dtrain, data_file)
#' dtrain <- lgb.Dataset(data_file)
1099
#' lgb.Dataset.set.categorical(dtrain, 1L:2L)
1100
#' }
1101
1102
1103
#' @rdname lgb.Dataset.set.categorical
#' @export
lgb.Dataset.set.categorical <- function(dataset, categorical_feature) {
James Lamb's avatar
James Lamb committed
1104

1105
  if (!lgb.is.Dataset(x = dataset)) {
1106
1107
    stop("lgb.Dataset.set.categorical: input dataset should be an lgb.Dataset object")
  }
James Lamb's avatar
James Lamb committed
1108

1109
  return(invisible(dataset$set_categorical_feature(categorical_feature = categorical_feature)))
James Lamb's avatar
James Lamb committed
1110

1111
1112
}

1113
1114
1115
#' @name lgb.Dataset.set.reference
#' @title Set reference of \code{lgb.Dataset}
#' @description If you want to use validation data, you should set reference to training data
Guolin Ke's avatar
Guolin Ke committed
1116
1117
#' @param dataset object of class \code{lgb.Dataset}
#' @param reference object of class \code{lgb.Dataset}
James Lamb's avatar
James Lamb committed
1118
#'
1119
#' @return the dataset you passed in
James Lamb's avatar
James Lamb committed
1120
#'
Guolin Ke's avatar
Guolin Ke committed
1121
#' @examples
1122
#' \donttest{
1123
1124
1125
1126
1127
1128
1129
#' 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)
1130
#' }
Guolin Ke's avatar
Guolin Ke committed
1131
1132
1133
#' @rdname lgb.Dataset.set.reference
#' @export
lgb.Dataset.set.reference <- function(dataset, reference) {
James Lamb's avatar
James Lamb committed
1134

1135
  if (!lgb.is.Dataset(x = dataset)) {
1136
    stop("lgb.Dataset.set.reference: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1137
  }
James Lamb's avatar
James Lamb committed
1138

1139
  return(invisible(dataset$set_reference(reference = reference)))
Guolin Ke's avatar
Guolin Ke committed
1140
1141
}

1142
1143
1144
1145
#' @name lgb.Dataset.save
#' @title Save \code{lgb.Dataset} to a binary file
#' @description Please note that \code{init_score} is not saved in binary file.
#'              If you need it, please set it again after loading Dataset.
Guolin Ke's avatar
Guolin Ke committed
1146
1147
#' @param dataset object of class \code{lgb.Dataset}
#' @param fname object filename of output file
James Lamb's avatar
James Lamb committed
1148
#'
1149
#' @return the dataset you passed in
James Lamb's avatar
James Lamb committed
1150
#'
Guolin Ke's avatar
Guolin Ke committed
1151
#' @examples
1152
#' \donttest{
1153
1154
1155
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
1156
#' lgb.Dataset.save(dtrain, tempfile(fileext = ".bin"))
1157
#' }
Guolin Ke's avatar
Guolin Ke committed
1158
1159
#' @export
lgb.Dataset.save <- function(dataset, fname) {
James Lamb's avatar
James Lamb committed
1160

1161
  if (!lgb.is.Dataset(x = dataset)) {
1162
    stop("lgb.Dataset.set: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1163
  }
James Lamb's avatar
James Lamb committed
1164

1165
1166
  if (!is.character(fname)) {
    stop("lgb.Dataset.set: fname should be a character or a file connection")
Guolin Ke's avatar
Guolin Ke committed
1167
  }
James Lamb's avatar
James Lamb committed
1168

1169
  return(invisible(dataset$save_binary(fname = fname)))
Guolin Ke's avatar
Guolin Ke committed
1170
}