lgb.Dataset.R 35.7 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
#' @importFrom R6 R6Class
11
#' @importFrom utils modifyList
James Lamb's avatar
James Lamb committed
12
13
Dataset <- R6::R6Class(

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

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

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

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

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

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

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

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

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

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

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

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

69
70
71
72
73
74
75
      # 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
76

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

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

90
91
      return(invisible(NULL))

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

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

98
      # Create new dataset
99
100
101
102
103
104
105
106
107
108
109
110
      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
111

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

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

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

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

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

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

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

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

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

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

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

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

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

167
          }
James Lamb's avatar
James Lamb committed
168

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

172
      }
James Lamb's avatar
James Lamb committed
173

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

177
      # Get handle of reference dataset
Guolin Ke's avatar
Guolin Ke committed
178
179
180
181
      ref_handle <- NULL
      if (!is.null(private$reference)) {
        ref_handle <- private$reference$.__enclos_env__$private$get_handle()
      }
James Lamb's avatar
James Lamb committed
182

183
      # Not subsetting
Guolin Ke's avatar
Guolin Ke committed
184
      if (is.null(private$used_indices)) {
James Lamb's avatar
James Lamb committed
185

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

189
          handle <- .Call(
190
            LGBM_DatasetCreateFromFile_R
191
            , private$raw_data
192
193
194
            , params_str
            , ref_handle
          )
James Lamb's avatar
James Lamb committed
195

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

198
          # Are we using a matrix?
199
          handle <- .Call(
200
            LGBM_DatasetCreateFromMat_R
201
202
203
204
205
206
            , private$raw_data
            , nrow(private$raw_data)
            , ncol(private$raw_data)
            , params_str
            , ref_handle
          )
James Lamb's avatar
James Lamb committed
207
208

        } else if (methods::is(private$raw_data, "dgCMatrix")) {
209
          if (length(private$raw_data@p) > 2147483647L) {
210
211
            stop("Cannot support large CSC matrix")
          }
212
          # Are we using a dgCMatrix (sparsed matrix column compressed)
213
          handle <- .Call(
214
            LGBM_DatasetCreateFromCSC_R
215
216
217
218
219
220
221
222
223
            , 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
224

Guolin Ke's avatar
Guolin Ke committed
225
        } else {
James Lamb's avatar
James Lamb committed
226

227
          # Unknown data type
228
229
230
231
          stop(
            "lgb.Dataset.construct: does not support constructing from "
            , sQuote(class(private$raw_data))
          )
James Lamb's avatar
James Lamb committed
232

Guolin Ke's avatar
Guolin Ke committed
233
        }
James Lamb's avatar
James Lamb committed
234

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

237
        # Reference is empty
Guolin Ke's avatar
Guolin Ke committed
238
        if (is.null(private$reference)) {
239
          stop("lgb.Dataset.construct: reference cannot be NULL for constructing data subset")
Guolin Ke's avatar
Guolin Ke committed
240
        }
James Lamb's avatar
James Lamb committed
241

242
        # Construct subset
243
        handle <- .Call(
244
          LGBM_DatasetGetSubset_R
245
246
247
248
249
          , 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
250

Guolin Ke's avatar
Guolin Ke committed
251
      }
252
      if (lgb.is.null.handle(x = handle)) {
Guolin Ke's avatar
Guolin Ke committed
253
254
        stop("lgb.Dataset.construct: cannot create Dataset handle")
      }
255
      # Setup class and private type
Guolin Ke's avatar
Guolin Ke committed
256
257
      class(handle) <- "lgb.Dataset.handle"
      private$handle <- handle
James Lamb's avatar
James Lamb committed
258

259
260
      # Set feature names
      if (!is.null(private$colnames)) {
261
        self$set_colnames(colnames = private$colnames)
262
      }
263

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

267
        # Setup initial scores
268
        init_score <- private$predictor$predict(
269
          data = private$raw_data
270
271
272
          , rawscore = TRUE
          , reshape = TRUE
        )
James Lamb's avatar
James Lamb committed
273

274
        # Not needed to transpose, for is col_marjor
Guolin Ke's avatar
Guolin Ke committed
275
276
        init_score <- as.vector(init_score)
        private$info$init_score <- init_score
James Lamb's avatar
James Lamb committed
277

278
      }
James Lamb's avatar
James Lamb committed
279

280
281
282
      # Should we free raw data?
      if (isTRUE(private$free_raw_data)) {
        private$raw_data <- NULL
Guolin Ke's avatar
Guolin Ke committed
283
      }
James Lamb's avatar
James Lamb committed
284

285
      # Get private information
286
      if (length(private$info) > 0L) {
James Lamb's avatar
James Lamb committed
287

288
        # Set infos
289
        for (i in seq_along(private$info)) {
James Lamb's avatar
James Lamb committed
290

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

Guolin Ke's avatar
Guolin Ke committed
294
        }
James Lamb's avatar
James Lamb committed
295

Guolin Ke's avatar
Guolin Ke committed
296
      }
James Lamb's avatar
James Lamb committed
297

298
      # Get label information existence
299
      if (is.null(self$getinfo(name = "label"))) {
Guolin Ke's avatar
Guolin Ke committed
300
301
        stop("lgb.Dataset.construct: label should be set")
      }
James Lamb's avatar
James Lamb committed
302

303
      return(invisible(self))
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
    # Dimension function
Guolin Ke's avatar
Guolin Ke committed
308
    dim = function() {
James Lamb's avatar
James Lamb committed
309

310
      # Check for handle
311
      if (!lgb.is.null.handle(x = private$handle)) {
James Lamb's avatar
James Lamb committed
312

313
314
        num_row <- 0L
        num_col <- 0L
James Lamb's avatar
James Lamb committed
315

316
        # Get numeric data and numeric features
317
318
319
320
321
322
323
324
325
326
        .Call(
          LGBM_DatasetGetNumData_R
          , private$handle
          , num_row
        )
        .Call(
          LGBM_DatasetGetNumFeature_R
          , private$handle
          , num_col
        )
327
        return(
328
          c(num_row, num_col)
329
        )
James Lamb's avatar
James Lamb committed
330
331
332

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

333
        # Check if dgCMatrix (sparse matrix column compressed)
334
        # NOTE: requires Matrix package
335
        return(dim(private$raw_data))
James Lamb's avatar
James Lamb committed
336

Guolin Ke's avatar
Guolin Ke committed
337
      } else {
James Lamb's avatar
James Lamb committed
338

339
        # Trying to work with unknown dimensions is not possible
340
341
342
343
        stop(
          "dim: cannot get dimensions before dataset has been constructed, "
          , "please call lgb.Dataset.construct explicitly"
        )
James Lamb's avatar
James Lamb committed
344

Guolin Ke's avatar
Guolin Ke committed
345
      }
James Lamb's avatar
James Lamb committed
346

Guolin Ke's avatar
Guolin Ke committed
347
    },
James Lamb's avatar
James Lamb committed
348

349
    # Get column names
Guolin Ke's avatar
Guolin Ke committed
350
    get_colnames = function() {
James Lamb's avatar
James Lamb committed
351

352
      # Check for handle
353
      if (!lgb.is.null.handle(x = private$handle)) {
354
        private$colnames <- .Call(
355
356
          LGBM_DatasetGetFeatureNames_R
          , private$handle
357
        )
358
        return(private$colnames)
James Lamb's avatar
James Lamb committed
359
360
361

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

362
        # Check if dgCMatrix (sparse matrix column compressed)
363
        return(colnames(private$raw_data))
James Lamb's avatar
James Lamb committed
364

Guolin Ke's avatar
Guolin Ke committed
365
      } else {
James Lamb's avatar
James Lamb committed
366

367
        # Trying to work with unknown dimensions is not possible
368
369
370
371
        stop(
          "dim: cannot get dimensions before dataset has been constructed, please call "
          , "lgb.Dataset.construct explicitly"
        )
James Lamb's avatar
James Lamb committed
372

Guolin Ke's avatar
Guolin Ke committed
373
      }
James Lamb's avatar
James Lamb committed
374

Guolin Ke's avatar
Guolin Ke committed
375
    },
James Lamb's avatar
James Lamb committed
376

377
    # Set column names
Guolin Ke's avatar
Guolin Ke committed
378
    set_colnames = function(colnames) {
James Lamb's avatar
James Lamb committed
379

380
381
      # Check column names non-existence
      if (is.null(colnames)) {
382
        return(invisible(self))
383
      }
James Lamb's avatar
James Lamb committed
384

385
      # Check empty column names
Guolin Ke's avatar
Guolin Ke committed
386
      colnames <- as.character(colnames)
387
      if (length(colnames) == 0L) {
388
        return(invisible(self))
389
      }
James Lamb's avatar
James Lamb committed
390

391
      # Write column names
Guolin Ke's avatar
Guolin Ke committed
392
      private$colnames <- colnames
393
      if (!lgb.is.null.handle(x = private$handle)) {
James Lamb's avatar
James Lamb committed
394

395
        # Merge names with tab separation
Guolin Ke's avatar
Guolin Ke committed
396
        merged_name <- paste0(as.list(private$colnames), collapse = "\t")
397
398
        .Call(
          LGBM_DatasetSetFeatureNames_R
399
          , private$handle
400
          , merged_name
401
        )
James Lamb's avatar
James Lamb committed
402

Guolin Ke's avatar
Guolin Ke committed
403
      }
James Lamb's avatar
James Lamb committed
404

405
      return(invisible(self))
James Lamb's avatar
James Lamb committed
406

Guolin Ke's avatar
Guolin Ke committed
407
    },
James Lamb's avatar
James Lamb committed
408

409
    # Get information
Guolin Ke's avatar
Guolin Ke committed
410
    getinfo = function(name) {
James Lamb's avatar
James Lamb committed
411

412
      # Check if attribute key is in the known attribute list
413
414
      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
415
      }
James Lamb's avatar
James Lamb committed
416

417
      # Check for info name and handle
418
      if (is.null(private$info[[name]])) {
419

420
        if (lgb.is.null.handle(x = private$handle)) {
421
          stop("Cannot perform getinfo before constructing Dataset.")
422
        }
423

424
        # Get field size of info
425
        info_len <- 0L
426
427
        .Call(
          LGBM_DatasetGetFieldSize_R
428
          , private$handle
429
          , name
430
          , info_len
431
        )
James Lamb's avatar
James Lamb committed
432

433
        # Check if info is not empty
434
        if (info_len > 0L) {
James Lamb's avatar
James Lamb committed
435

436
          # Get back fields
Guolin Ke's avatar
Guolin Ke committed
437
          ret <- NULL
438
439
440
441
442
          ret <- if (name == "group") {
            integer(info_len) # Integer
          } else {
            numeric(info_len) # Numeric
          }
James Lamb's avatar
James Lamb committed
443

444
445
          .Call(
            LGBM_DatasetGetField_R
446
            , private$handle
447
            , name
448
            , ret
449
          )
James Lamb's avatar
James Lamb committed
450

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

Guolin Ke's avatar
Guolin Ke committed
453
454
        }
      }
James Lamb's avatar
James Lamb committed
455

456
      return(private$info[[name]])
James Lamb's avatar
James Lamb committed
457

Guolin Ke's avatar
Guolin Ke committed
458
    },
James Lamb's avatar
James Lamb committed
459

460
    # Set information
Guolin Ke's avatar
Guolin Ke committed
461
    setinfo = function(name, info) {
James Lamb's avatar
James Lamb committed
462

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

468
469
470
471
472
473
      # 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
474

475
      # Store information privately
Guolin Ke's avatar
Guolin Ke committed
476
      private$info[[name]] <- info
James Lamb's avatar
James Lamb committed
477

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

480
        if (length(info) > 0L) {
James Lamb's avatar
James Lamb committed
481

482
483
          .Call(
            LGBM_DatasetSetField_R
484
            , private$handle
485
            , name
486
487
488
            , info
            , length(info)
          )
James Lamb's avatar
James Lamb committed
489

490
491
          private$version <- private$version + 1L

Guolin Ke's avatar
Guolin Ke committed
492
        }
James Lamb's avatar
James Lamb committed
493

Guolin Ke's avatar
Guolin Ke committed
494
      }
James Lamb's avatar
James Lamb committed
495

496
      return(invisible(self))
James Lamb's avatar
James Lamb committed
497

Guolin Ke's avatar
Guolin Ke committed
498
    },
James Lamb's avatar
James Lamb committed
499

500
    # Slice dataset
Guolin Ke's avatar
Guolin Ke committed
501
    slice = function(idxset, ...) {
James Lamb's avatar
James Lamb committed
502

503
504
505
506
507
508
509
510
511
512
      additional_params <- list(...)
      if (length(additional_params) > 0L) {
        warning(paste0(
          "Dataset$slice(): Found the following passed through '...': "
          , paste(names(additional_params), collapse = ", ")
          , ". These are ignored and should be removed. "
          , "In future releases of lightgbm, this warning will become an error."
        ))
      }

513
      # Perform slicing
514
515
516
517
518
519
520
521
522
523
524
525
526
      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
          , ...
        )
527
      )
James Lamb's avatar
James Lamb committed
528

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

531
532
533
    # [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.
534
    update_params = function(params) {
535
536
537
      if (length(params) == 0L) {
        return(invisible(self))
      }
538
      if (lgb.is.null.handle(x = private$handle)) {
539
        private$params <- utils::modifyList(private$params, params)
540
      } else {
541
542
        tryCatch({
          .Call(
543
            LGBM_DatasetUpdateParamChecking_R
544
545
546
547
548
549
            , 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
550
          if (is.null(private$raw_data)) {
551
            stop(e)
552
553
          }

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

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

564
565
566
567
568
569
570
571
572
573
574
    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)
    },

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

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

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

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

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

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

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

601
      # Set known references
602
603
604
      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
605

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

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

614
615
        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
616

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Guolin Ke's avatar
Guolin Ke committed
774
775
}

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

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

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

808
}
Guolin Ke's avatar
Guolin Ke committed
809

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

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

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

Guolin Ke's avatar
Guolin Ke committed
834
835
}

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

861
862
863
864
865
866
867
868
869
870
  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."
    ))
  }

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

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

Guolin Ke's avatar
Guolin Ke committed
878
879
}

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

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

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

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

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

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

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

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

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

936
  }
James Lamb's avatar
James Lamb committed
937

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

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

Guolin Ke's avatar
Guolin Ke committed
953
954
}

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

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

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

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

Guolin Ke's avatar
Guolin Ke committed
989
990
}

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

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

1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
  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."
    ))
  }

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

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

Guolin Ke's avatar
Guolin Ke committed
1052
1053
}

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

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

1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
  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."
    ))
  }

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

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

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

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

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

1146
1147
}

1148
1149
1150
#' @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
1151
1152
#' @param dataset object of class \code{lgb.Dataset}
#' @param reference object of class \code{lgb.Dataset}
James Lamb's avatar
James Lamb committed
1153
#'
1154
#' @return the dataset you passed in
James Lamb's avatar
James Lamb committed
1155
#'
Guolin Ke's avatar
Guolin Ke committed
1156
#' @examples
1157
#' \donttest{
1158
#' # create training Dataset
1159
1160
1161
#' data(agaricus.train, package ="lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
1162
1163
#'
#' # create a validation Dataset, using dtrain as a reference
1164
1165
#' data(agaricus.test, package = "lightgbm")
#' test <- agaricus.test
1166
#' dtest <- lgb.Dataset(test$data, label = test$label)
1167
#' lgb.Dataset.set.reference(dtest, dtrain)
1168
#' }
Guolin Ke's avatar
Guolin Ke committed
1169
1170
1171
#' @rdname lgb.Dataset.set.reference
#' @export
lgb.Dataset.set.reference <- function(dataset, reference) {
James Lamb's avatar
James Lamb committed
1172

1173
  if (!lgb.is.Dataset(x = dataset)) {
1174
    stop("lgb.Dataset.set.reference: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1175
  }
James Lamb's avatar
James Lamb committed
1176

1177
  return(invisible(dataset$set_reference(reference = reference)))
Guolin Ke's avatar
Guolin Ke committed
1178
1179
}

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

1199
  if (!lgb.is.Dataset(x = dataset)) {
1200
    stop("lgb.Dataset.set: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1201
  }
James Lamb's avatar
James Lamb committed
1202

1203
1204
  if (!is.character(fname)) {
    stop("lgb.Dataset.set: fname should be a character or a file connection")
Guolin Ke's avatar
Guolin Ke committed
1205
  }
James Lamb's avatar
James Lamb committed
1206

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