lgb.Dataset.R 35.6 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}).
713
714
715
#' @param data a \code{matrix} object, a \code{dgCMatrix} object,
#'             a character representing a path to a text file (CSV, TSV, or LibSVM),
#'             or a character representing a path to a binary \code{lgb.Dataset} file
716
717
718
719
720
721
722
#' @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
723
#' @param colnames names of columns
724
725
726
727
728
729
730
731
#' @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
732
#' @param info a list of information of the \code{lgb.Dataset} object
Guolin Ke's avatar
Guolin Ke committed
733
#' @param ... other information to pass to \code{info} or parameters pass to \code{params}
James Lamb's avatar
James Lamb committed
734
#'
Guolin Ke's avatar
Guolin Ke committed
735
#' @return constructed dataset
James Lamb's avatar
James Lamb committed
736
#'
Guolin Ke's avatar
Guolin Ke committed
737
#' @examples
738
#' \donttest{
739
740
741
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
742
743
744
#' data_file <- tempfile(fileext = ".data")
#' lgb.Dataset.save(dtrain, data_file)
#' dtrain <- lgb.Dataset(data_file)
745
#' lgb.Dataset.construct(dtrain)
746
#' }
Guolin Ke's avatar
Guolin Ke committed
747
748
#' @export
lgb.Dataset <- function(data,
749
750
751
                        params = list(),
                        reference = NULL,
                        colnames = NULL,
752
                        categorical_feature = NULL,
753
754
                        free_raw_data = TRUE,
                        info = list(),
Guolin Ke's avatar
Guolin Ke committed
755
                        ...) {
James Lamb's avatar
James Lamb committed
756

757
  # Create new dataset
758
759
760
761
762
763
764
765
766
767
768
769
770
771
  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
772

Guolin Ke's avatar
Guolin Ke committed
773
774
}

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

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

804
  # Create validation dataset
805
  return(invisible(dataset$create_valid(data = data, info = info, ...)))
James Lamb's avatar
James Lamb committed
806

807
}
Guolin Ke's avatar
Guolin Ke committed
808

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

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

830
  # Construct the dataset
831
  return(invisible(dataset$construct()))
James Lamb's avatar
James Lamb committed
832

Guolin Ke's avatar
Guolin Ke committed
833
834
}

835
836
#' @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
837
#' @param x Object of class \code{lgb.Dataset}
838
#' @param ... other parameters (ignored)
James Lamb's avatar
James Lamb committed
839
#'
Guolin Ke's avatar
Guolin Ke committed
840
#' @return a vector of numbers of rows and of columns
James Lamb's avatar
James Lamb committed
841
#'
Guolin Ke's avatar
Guolin Ke committed
842
843
844
#' @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
845
#'
Guolin Ke's avatar
Guolin Ke committed
846
#' @examples
847
#' \donttest{
848
849
850
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
James Lamb's avatar
James Lamb committed
851
#'
852
853
854
#' stopifnot(nrow(dtrain) == nrow(train$data))
#' stopifnot(ncol(dtrain) == ncol(train$data))
#' stopifnot(all(dim(dtrain) == dim(train$data)))
855
#' }
Guolin Ke's avatar
Guolin Ke committed
856
857
858
#' @rdname dim
#' @export
dim.lgb.Dataset <- function(x, ...) {
James Lamb's avatar
James Lamb committed
859

860
861
862
863
864
865
866
867
868
869
  additional_args <- list(...)
  if (length(additional_args) > 0L) {
    warning(paste0(
      "dim.lgb.Dataset: Found the following passed through '...': "
      , paste(names(additional_args), collapse = ", ")
      , ". These are ignored. In future releases of lightgbm, this warning will become an error. "
      , "See ?dim.lgb.Dataset for documentation on how to call this function."
    ))
  }

870
  # Check if dataset is not a dataset
871
  if (!lgb.is.Dataset(x = x)) {
872
    stop("dim.lgb.Dataset: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
873
  }
James Lamb's avatar
James Lamb committed
874

875
  return(x$dim())
James Lamb's avatar
James Lamb committed
876

Guolin Ke's avatar
Guolin Ke committed
877
878
}

879
880
881
#' @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
882
883
#' @param x object of class \code{lgb.Dataset}
#' @param value a list of two elements: the first one is ignored
884
#'              and the second one is column names
Guolin Ke's avatar
Guolin Ke committed
885
886
887
888
889
890
#'
#' @details
#' Generic \code{dimnames} methods are used by \code{colnames}.
#' Since row names are irrelevant, it is recommended to use \code{colnames} directly.
#'
#' @examples
891
#' \donttest{
892
893
894
895
896
897
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
#' dimnames(dtrain)
#' colnames(dtrain)
898
#' colnames(dtrain) <- make.names(seq_len(ncol(train$data)))
899
#' print(dtrain, verbose = TRUE)
900
#' }
Guolin Ke's avatar
Guolin Ke committed
901
#' @rdname dimnames.lgb.Dataset
902
#' @return A list with the dimension names of the dataset
Guolin Ke's avatar
Guolin Ke committed
903
904
#' @export
dimnames.lgb.Dataset <- function(x) {
James Lamb's avatar
James Lamb committed
905

906
  # Check if dataset is not a dataset
907
  if (!lgb.is.Dataset(x = x)) {
908
    stop("dimnames.lgb.Dataset: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
909
  }
James Lamb's avatar
James Lamb committed
910

911
  # Return dimension names
912
  return(list(NULL, x$get_colnames()))
James Lamb's avatar
James Lamb committed
913

Guolin Ke's avatar
Guolin Ke committed
914
915
916
917
918
}

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

920
  # Check if invalid element list
921
  if (!identical(class(value), "list") || length(value) != 2L) {
922
    stop("invalid ", sQuote("value"), " given: must be a list of two elements")
923
  }
James Lamb's avatar
James Lamb committed
924

925
926
927
928
  # Check for unknown row names
  if (!is.null(value[[1L]])) {
    stop("lgb.Dataset does not have rownames")
  }
James Lamb's avatar
James Lamb committed
929

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

932
    x$set_colnames(colnames = NULL)
Guolin Ke's avatar
Guolin Ke committed
933
    return(x)
James Lamb's avatar
James Lamb committed
934

935
  }
James Lamb's avatar
James Lamb committed
936

937
  # Check for unmatching column size
938
  if (ncol(x) != length(value[[2L]])) {
939
940
    stop(
      "can't assign "
941
      , sQuote(length(value[[2L]]))
942
943
944
945
      , " colnames to an lgb.Dataset with "
      , sQuote(ncol(x))
      , " columns"
    )
Guolin Ke's avatar
Guolin Ke committed
946
  }
James Lamb's avatar
James Lamb committed
947

948
  # Set column names properly, and return
949
  x$set_colnames(colnames = value[[2L]])
950
  return(x)
James Lamb's avatar
James Lamb committed
951

Guolin Ke's avatar
Guolin Ke committed
952
953
}

954
955
956
#' @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
957
#' @param dataset Object of class \code{lgb.Dataset}
958
#' @param idxset an integer vector of indices of rows needed
Guolin Ke's avatar
Guolin Ke committed
959
960
#' @param ... other parameters (currently not used)
#' @return constructed sub dataset
James Lamb's avatar
James Lamb committed
961
#'
Guolin Ke's avatar
Guolin Ke committed
962
#' @examples
963
#' \donttest{
964
965
966
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
James Lamb's avatar
James Lamb committed
967
#'
968
#' dsub <- lightgbm::slice(dtrain, seq_len(42L))
969
#' lgb.Dataset.construct(dsub)
970
#' labels <- lightgbm::getinfo(dsub, "label")
971
#' }
Guolin Ke's avatar
Guolin Ke committed
972
#' @export
973
974
975
slice <- function(dataset, ...) {
  UseMethod("slice")
}
Guolin Ke's avatar
Guolin Ke committed
976
977
978
979

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

981
  # Check if dataset is not a dataset
982
  if (!lgb.is.Dataset(x = dataset)) {
983
    stop("slice.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
984
  }
James Lamb's avatar
James Lamb committed
985

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

Guolin Ke's avatar
Guolin Ke committed
988
989
}

990
991
992
#' @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
993
994
#' @param dataset Object of class \code{lgb.Dataset}
#' @param name the name of the information field to get (see details)
995
#' @param ... other parameters (ignored)
Guolin Ke's avatar
Guolin Ke committed
996
#' @return info data
James Lamb's avatar
James Lamb committed
997
#'
Guolin Ke's avatar
Guolin Ke committed
998
999
#' @details
#' The \code{name} field can be one of the following:
James Lamb's avatar
James Lamb committed
1000
#'
Guolin Ke's avatar
Guolin Ke committed
1001
1002
1003
#' \itemize{
#'     \item \code{label}: label lightgbm learn from ;
#'     \item \code{weight}: to do a weight rescale ;
1004
1005
1006
1007
1008
#'     \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
1009
#'     \item \code{init_score}: initial score is the base prediction lightgbm will boost from.
Guolin Ke's avatar
Guolin Ke committed
1010
#' }
James Lamb's avatar
James Lamb committed
1011
#'
Guolin Ke's avatar
Guolin Ke committed
1012
#' @examples
1013
#' \donttest{
1014
1015
1016
1017
#' 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
1018
#'
1019
1020
#' labels <- lightgbm::getinfo(dtrain, "label")
#' lightgbm::setinfo(dtrain, "label", 1 - labels)
James Lamb's avatar
James Lamb committed
1021
#'
1022
1023
#' labels2 <- lightgbm::getinfo(dtrain, "label")
#' stopifnot(all(labels2 == 1 - labels))
1024
#' }
Guolin Ke's avatar
Guolin Ke committed
1025
#' @export
1026
1027
1028
getinfo <- function(dataset, ...) {
  UseMethod("getinfo")
}
Guolin Ke's avatar
Guolin Ke committed
1029
1030
1031
1032

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

1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
  additional_args <- list(...)
  if (length(additional_args) > 0L) {
    warning(paste0(
      "getinfo.lgb.Dataset: Found the following passed through '...': "
      , paste(names(additional_args), collapse = ", ")
      , ". These are ignored. In future releases of lightgbm, this warning will become an error. "
      , "See ?getinfo.lgb.Dataset for documentation on how to call this function."
    ))
  }

1044
  # Check if dataset is not a dataset
1045
  if (!lgb.is.Dataset(x = dataset)) {
1046
    stop("getinfo.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1047
  }
James Lamb's avatar
James Lamb committed
1048

1049
  return(dataset$getinfo(name = name))
James Lamb's avatar
James Lamb committed
1050

Guolin Ke's avatar
Guolin Ke committed
1051
1052
}

1053
1054
1055
#' @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
1056
#' @param dataset Object of class \code{lgb.Dataset}
Guolin Ke's avatar
Guolin Ke committed
1057
1058
#' @param name the name of the field to get
#' @param info the specific field of information to set
1059
#' @param ... other parameters (ignored)
1060
#' @return the dataset you passed in
James Lamb's avatar
James Lamb committed
1061
#'
Guolin Ke's avatar
Guolin Ke committed
1062
1063
#' @details
#' The \code{name} field can be one of the following:
James Lamb's avatar
James Lamb committed
1064
#'
Guolin Ke's avatar
Guolin Ke committed
1065
#' \itemize{
1066
1067
1068
1069
1070
#'     \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.
1071
1072
1073
#'         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
1074
#' }
James Lamb's avatar
James Lamb committed
1075
#'
Guolin Ke's avatar
Guolin Ke committed
1076
#' @examples
1077
#' \donttest{
1078
1079
1080
1081
#' 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
1082
#'
1083
1084
#' labels <- lightgbm::getinfo(dtrain, "label")
#' lightgbm::setinfo(dtrain, "label", 1 - labels)
James Lamb's avatar
James Lamb committed
1085
#'
1086
1087
#' labels2 <- lightgbm::getinfo(dtrain, "label")
#' stopifnot(all.equal(labels2, 1 - labels))
1088
#' }
Guolin Ke's avatar
Guolin Ke committed
1089
#' @export
1090
1091
1092
setinfo <- function(dataset, ...) {
  UseMethod("setinfo")
}
Guolin Ke's avatar
Guolin Ke committed
1093
1094
1095
1096

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

1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
  additional_args <- list(...)
  if (length(additional_args) > 0L) {
    warning(paste0(
      "setinfo.lgb.Dataset: Found the following passed through '...': "
      , paste(names(additional_args), collapse = ", ")
      , ". These are ignored. In future releases of lightgbm, this warning will become an error. "
      , "See ?setinfo.lgb.Dataset for documentation on how to call this function."
    ))
  }

1108
  if (!lgb.is.Dataset(x = dataset)) {
1109
    stop("setinfo.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1110
  }
James Lamb's avatar
James Lamb committed
1111

1112
  return(invisible(dataset$setinfo(name = name, info = info)))
Guolin Ke's avatar
Guolin Ke committed
1113
1114
}

1115
1116
1117
1118
#' @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.
1119
#' @param dataset object of class \code{lgb.Dataset}
1120
1121
1122
#' @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").
1123
#' @return the dataset you passed in
James Lamb's avatar
James Lamb committed
1124
#'
1125
#' @examples
1126
#' \donttest{
1127
1128
1129
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
1130
1131
1132
#' data_file <- tempfile(fileext = ".data")
#' lgb.Dataset.save(dtrain, data_file)
#' dtrain <- lgb.Dataset(data_file)
1133
#' lgb.Dataset.set.categorical(dtrain, 1L:2L)
1134
#' }
1135
1136
1137
#' @rdname lgb.Dataset.set.categorical
#' @export
lgb.Dataset.set.categorical <- function(dataset, categorical_feature) {
James Lamb's avatar
James Lamb committed
1138

1139
  if (!lgb.is.Dataset(x = dataset)) {
1140
1141
    stop("lgb.Dataset.set.categorical: input dataset should be an lgb.Dataset object")
  }
James Lamb's avatar
James Lamb committed
1142

1143
  return(invisible(dataset$set_categorical_feature(categorical_feature = categorical_feature)))
James Lamb's avatar
James Lamb committed
1144

1145
1146
}

1147
1148
1149
#' @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
1150
1151
#' @param dataset object of class \code{lgb.Dataset}
#' @param reference object of class \code{lgb.Dataset}
James Lamb's avatar
James Lamb committed
1152
#'
1153
#' @return the dataset you passed in
James Lamb's avatar
James Lamb committed
1154
#'
Guolin Ke's avatar
Guolin Ke committed
1155
#' @examples
1156
#' \donttest{
1157
1158
1159
1160
1161
1162
1163
#' 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)
1164
#' }
Guolin Ke's avatar
Guolin Ke committed
1165
1166
1167
#' @rdname lgb.Dataset.set.reference
#' @export
lgb.Dataset.set.reference <- function(dataset, reference) {
James Lamb's avatar
James Lamb committed
1168

1169
  if (!lgb.is.Dataset(x = dataset)) {
1170
    stop("lgb.Dataset.set.reference: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1171
  }
James Lamb's avatar
James Lamb committed
1172

1173
  return(invisible(dataset$set_reference(reference = reference)))
Guolin Ke's avatar
Guolin Ke committed
1174
1175
}

1176
1177
1178
1179
#' @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
1180
1181
#' @param dataset object of class \code{lgb.Dataset}
#' @param fname object filename of output file
James Lamb's avatar
James Lamb committed
1182
#'
1183
#' @return the dataset you passed in
James Lamb's avatar
James Lamb committed
1184
#'
Guolin Ke's avatar
Guolin Ke committed
1185
#' @examples
1186
#' \donttest{
1187
1188
1189
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
1190
#' lgb.Dataset.save(dtrain, tempfile(fileext = ".bin"))
1191
#' }
Guolin Ke's avatar
Guolin Ke committed
1192
1193
#' @export
lgb.Dataset.save <- function(dataset, fname) {
James Lamb's avatar
James Lamb committed
1194

1195
  if (!lgb.is.Dataset(x = dataset)) {
1196
    stop("lgb.Dataset.set: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1197
  }
James Lamb's avatar
James Lamb committed
1198

1199
1200
  if (!is.character(fname)) {
    stop("lgb.Dataset.set: fname should be a character or a file connection")
Guolin Ke's avatar
Guolin Ke committed
1201
  }
James Lamb's avatar
James Lamb committed
1202

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