lgb.Dataset.R 39.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#' @name lgb_shared_dataset_params
#' @title Shared Dataset parameter docs
#' @description Parameter docs for fields used in \code{lgb.Dataset} construction
#' @param label vector of labels to use as the target variable
#' @param weight numeric vector of sample weights
#' @param init_score initial score is the base prediction lightgbm will boost from
#' @param 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.
#' @keywords internal
NULL

16
17
18
19
20
21
22
23
# [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
24
#' @importFrom methods is
James Lamb's avatar
James Lamb committed
25
#' @importFrom R6 R6Class
26
#' @importFrom utils modifyList
James Lamb's avatar
James Lamb committed
27
28
Dataset <- R6::R6Class(

29
  classname = "lgb.Dataset",
30
  cloneable = FALSE,
Guolin Ke's avatar
Guolin Ke committed
31
  public = list(
James Lamb's avatar
James Lamb committed
32

33
    # Finalize will free up the handles
Guolin Ke's avatar
Guolin Ke committed
34
    finalize = function() {
35
36
37
38
39
      .Call(
        LGBM_DatasetFree_R
        , private$handle
      )
      private$handle <- NULL
40
      return(invisible(NULL))
Guolin Ke's avatar
Guolin Ke committed
41
    },
James Lamb's avatar
James Lamb committed
42

43
    # Initialize will create a starter dataset
Guolin Ke's avatar
Guolin Ke committed
44
    initialize = function(data,
45
46
47
                          params = list(),
                          reference = NULL,
                          colnames = NULL,
48
                          categorical_feature = NULL,
49
50
51
                          predictor = NULL,
                          free_raw_data = TRUE,
                          used_indices = NULL,
52
53
54
55
                          label = NULL,
                          weight = NULL,
                          group = NULL,
                          init_score = NULL) {
James Lamb's avatar
James Lamb committed
56

57
      # validate inputs early to avoid unnecessary computation
58
      if (!(is.null(reference) || .is_Dataset(reference))) {
59
60
          stop("lgb.Dataset: If provided, reference must be a ", sQuote("lgb.Dataset"))
      }
61
      if (!(is.null(predictor) || .is_Predictor(predictor))) {
62
63
64
          stop("lgb.Dataset: If provided, predictor must be a ", sQuote("lgb.Predictor"))
      }

65
      info <- list()
66
67
68
69
70
71
72
73
74
75
76
      if (!is.null(label)) {
        info[["label"]] <- label
      }
      if (!is.null(weight)) {
        info[["weight"]] <- weight
      }
      if (!is.null(group)) {
        info[["group"]] <- group
      }
      if (!is.null(init_score)) {
        info[["init_score"]] <- init_score
Guolin Ke's avatar
Guolin Ke committed
77
      }
James Lamb's avatar
James Lamb committed
78

79
80
81
82
83
84
85
      # 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
86

87
88
89
      # Setup private attributes
      private$raw_data <- data
      private$params <- params
Guolin Ke's avatar
Guolin Ke committed
90
      private$reference <- reference
91
      private$colnames <- colnames
92

93
      private$categorical_feature <- categorical_feature
94
95
      private$predictor <- predictor
      private$free_raw_data <- free_raw_data
96
      private$used_indices <- sort(used_indices, decreasing = FALSE)
97
      private$info <- info
98
      private$version <- 0L
James Lamb's avatar
James Lamb committed
99

100
101
      return(invisible(NULL))

Guolin Ke's avatar
Guolin Ke committed
102
    },
James Lamb's avatar
James Lamb committed
103

104
    create_valid = function(data,
105
106
107
108
                            label = NULL,
                            weight = NULL,
                            group = NULL,
                            init_score = NULL,
109
                            params = list()) {
110
111

      # the Dataset's existing parameters should be overwritten by any passed in to this call
112
      params <- modifyList(private$params, params)
113

114
      # Create new dataset
115
116
      ret <- Dataset$new(
        data = data
117
        , params = params
118
119
120
121
122
123
        , reference = self
        , colnames = private$colnames
        , categorical_feature = private$categorical_feature
        , predictor = private$predictor
        , free_raw_data = private$free_raw_data
        , used_indices = NULL
124
125
126
127
        , label = label
        , weight = weight
        , group = group
        , init_score = init_score
128
      )
James Lamb's avatar
James Lamb committed
129

130
      return(invisible(ret))
James Lamb's avatar
James Lamb committed
131

Guolin Ke's avatar
Guolin Ke committed
132
    },
James Lamb's avatar
James Lamb committed
133

134
    # Dataset constructor
Guolin Ke's avatar
Guolin Ke committed
135
    construct = function() {
James Lamb's avatar
James Lamb committed
136

137
      # Check for handle null
138
      if (!.is_null_handle(x = private$handle)) {
139
        return(invisible(self))
Guolin Ke's avatar
Guolin Ke committed
140
      }
James Lamb's avatar
James Lamb committed
141

Guolin Ke's avatar
Guolin Ke committed
142
143
      # Get feature names
      cnames <- NULL
James Lamb's avatar
James Lamb committed
144
      if (is.matrix(private$raw_data) || methods::is(private$raw_data, "dgCMatrix")) {
Guolin Ke's avatar
Guolin Ke committed
145
146
        cnames <- colnames(private$raw_data)
      }
James Lamb's avatar
James Lamb committed
147

148
      # set feature names if they do not exist
149
      if (is.null(private$colnames) && !is.null(cnames)) {
Guolin Ke's avatar
Guolin Ke committed
150
151
        private$colnames <- as.character(cnames)
      }
James Lamb's avatar
James Lamb committed
152

153
154
      # Get categorical feature index
      if (!is.null(private$categorical_feature)) {
James Lamb's avatar
James Lamb committed
155

156
        # Check for character name
157
        if (is.character(private$categorical_feature)) {
James Lamb's avatar
James Lamb committed
158

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

161
            # Provided indices, but some indices are missing?
162
            if (sum(is.na(cate_indices)) > 0L) {
163
              stop(
164
                "lgb.Dataset.construct: supplied an unknown feature in categorical_feature: "
165
166
                , sQuote(private$categorical_feature[is.na(cate_indices)])
              )
167
            }
James Lamb's avatar
James Lamb committed
168

169
          } else {
James Lamb's avatar
James Lamb committed
170

171
            # Check if more categorical features were output over the feature space
172
            data_is_not_filename <- !is.character(private$raw_data)
173
174
175
176
177
178
            if (
              data_is_not_filename
              && !is.null(private$raw_data)
              && is.null(private$used_indices)
              && max(private$categorical_feature) > ncol(private$raw_data)
            ) {
179
              stop(
180
                "lgb.Dataset.construct: supplied a too large value in categorical_feature: "
181
182
                , max(private$categorical_feature)
                , " but only "
183
                , ncol(private$raw_data)
184
185
                , " features"
              )
186
            }
James Lamb's avatar
James Lamb committed
187

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

191
          }
James Lamb's avatar
James Lamb committed
192

193
        # Store indices for categorical features
194
        private$params$categorical_feature <- cate_indices
James Lamb's avatar
James Lamb committed
195

196
      }
James Lamb's avatar
James Lamb committed
197

Guolin Ke's avatar
Guolin Ke committed
198
      # Generate parameter str
199
      params_str <- .params2str(params = private$params)
James Lamb's avatar
James Lamb committed
200

201
      # Get handle of reference dataset
Guolin Ke's avatar
Guolin Ke committed
202
203
204
205
      ref_handle <- NULL
      if (!is.null(private$reference)) {
        ref_handle <- private$reference$.__enclos_env__$private$get_handle()
      }
James Lamb's avatar
James Lamb committed
206

207
      # not subsetting, constructing from raw data
Guolin Ke's avatar
Guolin Ke committed
208
      if (is.null(private$used_indices)) {
James Lamb's avatar
James Lamb committed
209

210
211
212
213
214
215
216
217
218
        if (is.null(private$raw_data)) {
          stop(paste0(
            "Attempting to create a Dataset without any raw data. "
            , "This can happen if you have called Dataset$finalize() or if this Dataset was saved with saveRDS(). "
            , "To avoid this error in the future, use lgb.Dataset.save() or "
            , "Dataset$save_binary() to save lightgbm Datasets."
          ))
        }

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

222
          handle <- .Call(
223
            LGBM_DatasetCreateFromFile_R
224
            , path.expand(private$raw_data)
225
226
227
            , params_str
            , ref_handle
          )
James Lamb's avatar
James Lamb committed
228

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

231
          # Are we using a matrix?
232
          handle <- .Call(
233
            LGBM_DatasetCreateFromMat_R
234
235
236
237
238
239
            , private$raw_data
            , nrow(private$raw_data)
            , ncol(private$raw_data)
            , params_str
            , ref_handle
          )
James Lamb's avatar
James Lamb committed
240
241

        } else if (methods::is(private$raw_data, "dgCMatrix")) {
242
          if (length(private$raw_data@p) > 2147483647L) {
243
244
            stop("Cannot support large CSC matrix")
          }
245
          # Are we using a dgCMatrix (sparse matrix column compressed)
246
          handle <- .Call(
247
            LGBM_DatasetCreateFromCSC_R
248
249
250
251
252
253
254
255
256
            , 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
257

Guolin Ke's avatar
Guolin Ke committed
258
        } else {
James Lamb's avatar
James Lamb committed
259

260
          # Unknown data type
261
262
263
264
          stop(
            "lgb.Dataset.construct: does not support constructing from "
            , sQuote(class(private$raw_data))
          )
James Lamb's avatar
James Lamb committed
265

Guolin Ke's avatar
Guolin Ke committed
266
        }
James Lamb's avatar
James Lamb committed
267

Guolin Ke's avatar
Guolin Ke committed
268
      } else {
James Lamb's avatar
James Lamb committed
269

270
        # Reference is empty
Guolin Ke's avatar
Guolin Ke committed
271
        if (is.null(private$reference)) {
272
          stop("lgb.Dataset.construct: reference cannot be NULL for constructing data subset")
Guolin Ke's avatar
Guolin Ke committed
273
        }
James Lamb's avatar
James Lamb committed
274

275
        # Construct subset
276
        handle <- .Call(
277
          LGBM_DatasetGetSubset_R
278
279
280
281
282
          , 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
283

Guolin Ke's avatar
Guolin Ke committed
284
      }
285
      if (.is_null_handle(x = handle)) {
Guolin Ke's avatar
Guolin Ke committed
286
287
        stop("lgb.Dataset.construct: cannot create Dataset handle")
      }
288
      # Setup class and private type
Guolin Ke's avatar
Guolin Ke committed
289
290
      class(handle) <- "lgb.Dataset.handle"
      private$handle <- handle
James Lamb's avatar
James Lamb committed
291

292
293
      # Set feature names
      if (!is.null(private$colnames)) {
294
        self$set_colnames(colnames = private$colnames)
295
      }
296

297
298
299
300
301
302
303
      # Ensure that private$colnames matches the feature names on the C++ side. This line is necessary
      # in cases like constructing from a file or from a matrix with no column names.
      private$colnames <- .Call(
          LGBM_DatasetGetFeatureNames_R
          , private$handle
      )

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

307
        # Setup initial scores
308
        init_score <- private$predictor$predict(
309
          data = private$raw_data
310
311
          , rawscore = TRUE
        )
James Lamb's avatar
James Lamb committed
312

313
        # Not needed to transpose, for is col_marjor
Guolin Ke's avatar
Guolin Ke committed
314
315
        init_score <- as.vector(init_score)
        private$info$init_score <- init_score
James Lamb's avatar
James Lamb committed
316

317
      }
James Lamb's avatar
James Lamb committed
318

319
320
321
      # Should we free raw data?
      if (isTRUE(private$free_raw_data)) {
        private$raw_data <- NULL
Guolin Ke's avatar
Guolin Ke committed
322
      }
James Lamb's avatar
James Lamb committed
323

324
      # Get private information
325
      if (length(private$info) > 0L) {
James Lamb's avatar
James Lamb committed
326

327
        # Set infos
328
        for (i in seq_along(private$info)) {
James Lamb's avatar
James Lamb committed
329

Guolin Ke's avatar
Guolin Ke committed
330
          p <- private$info[i]
331
332
333
334
          self$set_field(
            field_name = names(p)
            , data = p[[1L]]
          )
James Lamb's avatar
James Lamb committed
335

Guolin Ke's avatar
Guolin Ke committed
336
        }
James Lamb's avatar
James Lamb committed
337

Guolin Ke's avatar
Guolin Ke committed
338
      }
James Lamb's avatar
James Lamb committed
339

340
      # Get label information existence
341
      if (is.null(self$get_field(field_name = "label"))) {
Guolin Ke's avatar
Guolin Ke committed
342
343
        stop("lgb.Dataset.construct: label should be set")
      }
James Lamb's avatar
James Lamb committed
344

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

352
      # Check for handle
353
      if (!.is_null_handle(x = private$handle)) {
James Lamb's avatar
James Lamb committed
354

355
356
        num_row <- 0L
        num_col <- 0L
James Lamb's avatar
James Lamb committed
357

358
        # Get numeric data and numeric features
359
360
361
362
363
364
365
366
367
368
        .Call(
          LGBM_DatasetGetNumData_R
          , private$handle
          , num_row
        )
        .Call(
          LGBM_DatasetGetNumFeature_R
          , private$handle
          , num_col
        )
369
        return(
370
          c(num_row, num_col)
371
        )
James Lamb's avatar
James Lamb committed
372
373
374

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

375
        # Check if dgCMatrix (sparse matrix column compressed)
376
        # NOTE: requires Matrix package
377
        return(dim(private$raw_data))
James Lamb's avatar
James Lamb committed
378

Guolin Ke's avatar
Guolin Ke committed
379
      } else {
James Lamb's avatar
James Lamb committed
380

381
        # Trying to work with unknown dimensions is not possible
382
383
384
385
        stop(
          "dim: cannot get dimensions before dataset has been constructed, "
          , "please call lgb.Dataset.construct explicitly"
        )
James Lamb's avatar
James Lamb committed
386

Guolin Ke's avatar
Guolin Ke committed
387
      }
James Lamb's avatar
James Lamb committed
388

Guolin Ke's avatar
Guolin Ke committed
389
    },
James Lamb's avatar
James Lamb committed
390

391
392
    # Get number of bins for feature
    get_feature_num_bin = function(feature) {
393
      if (.is_null_handle(x = private$handle)) {
394
395
        stop("Cannot get number of bins in feature before constructing Dataset.")
      }
396
397
398
399
400
401
402
      if (is.character(feature)) {
        feature_name <- feature
        feature <- which(private$colnames == feature_name)
        if (length(feature) == 0L) {
          stop(sprintf("feature '%s' not found", feature_name))
        }
      }
403
404
405
406
407
408
409
410
411
412
      num_bin <- integer(1L)
      .Call(
        LGBM_DatasetGetFeatureNumBin_R
        , private$handle
        , feature - 1L
        , num_bin
      )
      return(num_bin)
    },

413
    # Get column names
Guolin Ke's avatar
Guolin Ke committed
414
    get_colnames = function() {
James Lamb's avatar
James Lamb committed
415

416
      # Check for handle
417
      if (!.is_null_handle(x = private$handle)) {
418
        private$colnames <- .Call(
419
420
          LGBM_DatasetGetFeatureNames_R
          , private$handle
421
        )
422
        return(private$colnames)
James Lamb's avatar
James Lamb committed
423
424
425

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

426
        # Check if dgCMatrix (sparse matrix column compressed)
427
        return(colnames(private$raw_data))
James Lamb's avatar
James Lamb committed
428

Guolin Ke's avatar
Guolin Ke committed
429
      } else {
James Lamb's avatar
James Lamb committed
430

431
        # Trying to work with unknown formats is not possible
432
        stop(
433
434
          "Dataset$get_colnames(): cannot get column names before dataset has been constructed, please call "
          , "lgb.Dataset.construct() explicitly"
435
        )
James Lamb's avatar
James Lamb committed
436

Guolin Ke's avatar
Guolin Ke committed
437
      }
James Lamb's avatar
James Lamb committed
438

Guolin Ke's avatar
Guolin Ke committed
439
    },
James Lamb's avatar
James Lamb committed
440

441
    # Set column names
Guolin Ke's avatar
Guolin Ke committed
442
    set_colnames = function(colnames) {
James Lamb's avatar
James Lamb committed
443

444
445
      # Check column names non-existence
      if (is.null(colnames)) {
446
        return(invisible(self))
447
      }
James Lamb's avatar
James Lamb committed
448

449
      # Check empty column names
Guolin Ke's avatar
Guolin Ke committed
450
      colnames <- as.character(colnames)
451
      if (length(colnames) == 0L) {
452
        return(invisible(self))
453
      }
James Lamb's avatar
James Lamb committed
454

455
      # Write column names
Guolin Ke's avatar
Guolin Ke committed
456
      private$colnames <- colnames
457
      if (!.is_null_handle(x = private$handle)) {
James Lamb's avatar
James Lamb committed
458

459
        # Merge names with tab separation
Guolin Ke's avatar
Guolin Ke committed
460
        merged_name <- paste0(as.list(private$colnames), collapse = "\t")
461
462
        .Call(
          LGBM_DatasetSetFeatureNames_R
463
          , private$handle
464
          , merged_name
465
        )
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
      return(invisible(self))
James Lamb's avatar
James Lamb committed
470

Guolin Ke's avatar
Guolin Ke committed
471
    },
James Lamb's avatar
James Lamb committed
472

473
    get_field = function(field_name) {
James Lamb's avatar
James Lamb committed
474

475
      # Check if attribute key is in the known attribute list
476
477
478
      if (!is.character(field_name) || length(field_name) != 1L || !field_name %in% .INFO_KEYS()) {
        stop(
          "Dataset$get_field(): field_name must one of the following: "
479
          , toString(sQuote(.INFO_KEYS()))
480
        )
Guolin Ke's avatar
Guolin Ke committed
481
      }
James Lamb's avatar
James Lamb committed
482

483
      # Check for info name and handle
484
      if (is.null(private$info[[field_name]])) {
485

486
        if (.is_null_handle(x = private$handle)) {
487
          stop("Cannot perform Dataset$get_field() before constructing Dataset.")
488
        }
489

490
        # Get field size of info
491
        info_len <- 0L
492
493
        .Call(
          LGBM_DatasetGetFieldSize_R
494
          , private$handle
495
          , field_name
496
          , info_len
497
        )
James Lamb's avatar
James Lamb committed
498

499
        if (info_len > 0L) {
James Lamb's avatar
James Lamb committed
500

501
          # Get back fields
502
503
          if (field_name == "group") {
            ret <- integer(info_len)
504
          } else {
505
            ret <- numeric(info_len)
506
          }
James Lamb's avatar
James Lamb committed
507

508
509
          .Call(
            LGBM_DatasetGetField_R
510
            , private$handle
511
            , field_name
512
            , ret
513
          )
James Lamb's avatar
James Lamb committed
514

515
          private$info[[field_name]] <- ret
James Lamb's avatar
James Lamb committed
516

Guolin Ke's avatar
Guolin Ke committed
517
518
        }
      }
James Lamb's avatar
James Lamb committed
519

520
      return(private$info[[field_name]])
James Lamb's avatar
James Lamb committed
521

Guolin Ke's avatar
Guolin Ke committed
522
    },
James Lamb's avatar
James Lamb committed
523

524
    set_field = function(field_name, data) {
James Lamb's avatar
James Lamb committed
525

526
      # Check if attribute key is in the known attribute list
527
528
529
      if (!is.character(field_name) || length(field_name) != 1L || !field_name %in% .INFO_KEYS()) {
        stop(
          "Dataset$set_field(): field_name must one of the following: "
530
          , toString(sQuote(.INFO_KEYS()))
531
        )
532
      }
James Lamb's avatar
James Lamb committed
533

534
      # Check for type of information
535
      data <- if (field_name == "group") {
536
        as.integer(data)
537
      } else {
538
        as.numeric(data)
539
      }
James Lamb's avatar
James Lamb committed
540

541
      # Store information privately
542
      private$info[[field_name]] <- data
James Lamb's avatar
James Lamb committed
543

544
      if (!.is_null_handle(x = private$handle) && !is.null(data)) {
James Lamb's avatar
James Lamb committed
545

546
        if (length(data) > 0L) {
James Lamb's avatar
James Lamb committed
547

548
549
          .Call(
            LGBM_DatasetSetField_R
550
            , private$handle
551
552
553
            , field_name
            , data
            , length(data)
554
          )
James Lamb's avatar
James Lamb committed
555

556
557
          private$version <- private$version + 1L

Guolin Ke's avatar
Guolin Ke committed
558
        }
James Lamb's avatar
James Lamb committed
559

Guolin Ke's avatar
Guolin Ke committed
560
      }
James Lamb's avatar
James Lamb committed
561

562
      return(invisible(self))
James Lamb's avatar
James Lamb committed
563

Guolin Ke's avatar
Guolin Ke committed
564
    },
James Lamb's avatar
James Lamb committed
565

566
    slice = function(idxset) {
567

568
569
570
      return(
        Dataset$new(
          data = NULL
571
          , params = private$params
572
573
574
575
576
577
578
          , 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)
        )
579
      )
James Lamb's avatar
James Lamb committed
580

Guolin Ke's avatar
Guolin Ke committed
581
    },
James Lamb's avatar
James Lamb committed
582

583
584
585
    # [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.
586
    update_params = function(params) {
587
588
589
      if (length(params) == 0L) {
        return(invisible(self))
      }
590
      new_params <- utils::modifyList(private$params, params)
591
      if (.is_null_handle(x = private$handle)) {
592
        private$params <- new_params
593
      } else {
594
595
        tryCatch({
          .Call(
596
            LGBM_DatasetUpdateParamChecking_R
597
598
            , .params2str(params = private$params)
            , .params2str(params = new_params)
599
          )
600
          private$params <- new_params
601
602
603
        }, 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
604
          if (is.null(private$raw_data)) {
605
            stop(e)
606
607
          }

608
609
          # If updating failed but raw data is available, modify the params
          # on the R side and re-set ("deconstruct") the Dataset
610
          private$params <- new_params
611
          self$finalize()
612
        })
613
      }
614
      return(invisible(self))
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
619
620
621
622
    # [description] Get only Dataset-specific parameters. This is primarily used by
    #               Booster to update its parameters based on the characteristics of
    #               a Dataset. It should not be used by other methods in this class,
    #               since "verbose" is not a Dataset parameter and needs to be passed
    #               through to avoid globally re-setting verbosity.
623
624
625
626
627
628
629
630
631
632
633
    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)
    },

634
    # Set categorical feature parameter
635
    set_categorical_feature = function(categorical_feature) {
James Lamb's avatar
James Lamb committed
636

637
638
      # Check for identical input
      if (identical(private$categorical_feature, categorical_feature)) {
639
        return(invisible(self))
640
      }
James Lamb's avatar
James Lamb committed
641

642
      # Check for empty data
643
      if (is.null(private$raw_data)) {
644
645
        stop("set_categorical_feature: cannot set categorical feature after freeing raw data,
          please set ", sQuote("free_raw_data = FALSE"), " when you construct lgb.Dataset")
646
      }
James Lamb's avatar
James Lamb committed
647

648
      # Overwrite categorical features
649
      private$categorical_feature <- categorical_feature
James Lamb's avatar
James Lamb committed
650

651
      # Finalize and return self
652
      self$finalize()
653
      return(invisible(self))
James Lamb's avatar
James Lamb committed
654

655
    },
James Lamb's avatar
James Lamb committed
656

Guolin Ke's avatar
Guolin Ke committed
657
    set_reference = function(reference) {
James Lamb's avatar
James Lamb committed
658

659
      # setting reference to this same Dataset object doesn't require any changes
660
      if (identical(private$reference, reference)) {
661
        return(invisible(self))
662
      }
James Lamb's avatar
James Lamb committed
663

664
665
      # changing the reference removes the Dataset object on the C++ side, so it should only
      # be done if you still have the raw_data available, so that the new Dataset can be reconstructed
Guolin Ke's avatar
Guolin Ke committed
666
      if (is.null(private$raw_data)) {
667
668
        stop("set_reference: cannot set reference after freeing raw data,
          please set ", sQuote("free_raw_data = FALSE"), " when you construct lgb.Dataset")
Guolin Ke's avatar
Guolin Ke committed
669
      }
James Lamb's avatar
James Lamb committed
670

671
      if (!.is_Dataset(reference)) {
672
        stop("set_reference: Can only use lgb.Dataset as a reference")
Guolin Ke's avatar
Guolin Ke committed
673
      }
James Lamb's avatar
James Lamb committed
674

675
676
677
678
679
      # Set known references
      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)

680
      # Store reference
Guolin Ke's avatar
Guolin Ke committed
681
      private$reference <- reference
James Lamb's avatar
James Lamb committed
682

683
      # Finalize and return self
Guolin Ke's avatar
Guolin Ke committed
684
      self$finalize()
685
      return(invisible(self))
James Lamb's avatar
James Lamb committed
686

Guolin Ke's avatar
Guolin Ke committed
687
    },
James Lamb's avatar
James Lamb committed
688

689
    # Save binary model
Guolin Ke's avatar
Guolin Ke committed
690
    save_binary = function(fname) {
James Lamb's avatar
James Lamb committed
691

692
      # Store binary data
Guolin Ke's avatar
Guolin Ke committed
693
      self$construct()
694
695
      .Call(
        LGBM_DatasetSaveBinary_R
696
        , private$handle
697
        , path.expand(fname)
698
      )
699
      return(invisible(self))
Guolin Ke's avatar
Guolin Ke committed
700
    }
James Lamb's avatar
James Lamb committed
701

Guolin Ke's avatar
Guolin Ke committed
702
703
  ),
  private = list(
704
705
706
707
708
    handle = NULL,
    raw_data = NULL,
    params = list(),
    reference = NULL,
    colnames = NULL,
709
    categorical_feature = NULL,
710
711
712
713
    predictor = NULL,
    free_raw_data = TRUE,
    used_indices = NULL,
    info = NULL,
714
    version = 0L,
James Lamb's avatar
James Lamb committed
715

716
    get_handle = function() {
James Lamb's avatar
James Lamb committed
717

718
      # Get handle and construct if needed
719
      if (.is_null_handle(x = private$handle)) {
720
721
        self$construct()
      }
722
      return(private$handle)
James Lamb's avatar
James Lamb committed
723

Guolin Ke's avatar
Guolin Ke committed
724
    },
James Lamb's avatar
James Lamb committed
725

Guolin Ke's avatar
Guolin Ke committed
726
    set_predictor = function(predictor) {
James Lamb's avatar
James Lamb committed
727

728
      if (identical(private$predictor, predictor)) {
729
        return(invisible(self))
730
      }
James Lamb's avatar
James Lamb committed
731

732
      # Check for empty data
Guolin Ke's avatar
Guolin Ke committed
733
      if (is.null(private$raw_data)) {
734
735
        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
736
      }
James Lamb's avatar
James Lamb committed
737

738
      # Check for empty predictor
Guolin Ke's avatar
Guolin Ke committed
739
      if (!is.null(predictor)) {
James Lamb's avatar
James Lamb committed
740

741
        # Predictor is unknown
742
        if (!.is_Predictor(predictor)) {
743
          stop("set_predictor: Can only use lgb.Predictor as predictor")
Guolin Ke's avatar
Guolin Ke committed
744
        }
James Lamb's avatar
James Lamb committed
745

Guolin Ke's avatar
Guolin Ke committed
746
      }
James Lamb's avatar
James Lamb committed
747

748
      # Store predictor
Guolin Ke's avatar
Guolin Ke committed
749
      private$predictor <- predictor
James Lamb's avatar
James Lamb committed
750

751
      # Finalize and return self
Guolin Ke's avatar
Guolin Ke committed
752
      self$finalize()
753
      return(invisible(self))
James Lamb's avatar
James Lamb committed
754

Guolin Ke's avatar
Guolin Ke committed
755
    }
James Lamb's avatar
James Lamb committed
756

Guolin Ke's avatar
Guolin Ke committed
757
758
759
  )
)

760
761
762
#' @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}).
763
#' @inheritParams lgb_shared_dataset_params
764
765
766
#' @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
767
768
769
770
771
772
773
#' @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
774
#' @param colnames names of columns
775
776
777
778
779
780
781
782
#' @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}.
James Lamb's avatar
James Lamb committed
783
#'
Guolin Ke's avatar
Guolin Ke committed
784
#' @return constructed dataset
James Lamb's avatar
James Lamb committed
785
#'
Guolin Ke's avatar
Guolin Ke committed
786
#' @examples
787
#' \donttest{
788
789
#' \dontshow{setLGBMthreads(2L)}
#' \dontshow{data.table::setDTthreads(1L)}
790
791
792
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
793
794
795
#' data_file <- tempfile(fileext = ".data")
#' lgb.Dataset.save(dtrain, data_file)
#' dtrain <- lgb.Dataset(data_file)
796
#' lgb.Dataset.construct(dtrain)
797
#' }
Guolin Ke's avatar
Guolin Ke committed
798
799
#' @export
lgb.Dataset <- function(data,
800
801
802
                        params = list(),
                        reference = NULL,
                        colnames = NULL,
803
                        categorical_feature = NULL,
804
                        free_raw_data = TRUE,
805
806
807
                        label = NULL,
                        weight = NULL,
                        group = NULL,
808
                        init_score = NULL) {
809

810
811
812
813
814
815
816
817
818
819
  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
820
821
822
823
      , label = label
      , weight = weight
      , group = group
      , init_score = init_score
824
825
    ))
  )
James Lamb's avatar
James Lamb committed
826

Guolin Ke's avatar
Guolin Ke committed
827
828
}

829
830
831
#' @name lgb.Dataset.create.valid
#' @title Construct validation data
#' @description Construct validation data according to training data
832
#' @inheritParams lgb_shared_dataset_params
Guolin Ke's avatar
Guolin Ke committed
833
#' @param dataset \code{lgb.Dataset} object, training data
834
835
836
#' @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
837
838
839
840
841
#' @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. If this is an empty list (the default), the validation Dataset
#'               will have the same parameters as the Dataset passed to argument \code{dataset}.
James Lamb's avatar
James Lamb committed
842
#'
Guolin Ke's avatar
Guolin Ke committed
843
#' @return constructed dataset
James Lamb's avatar
James Lamb committed
844
#'
Guolin Ke's avatar
Guolin Ke committed
845
#' @examples
846
#' \donttest{
847
848
#' \dontshow{setLGBMthreads(2L)}
#' \dontshow{data.table::setDTthreads(1L)}
849
850
851
852
853
854
#' 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)
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
#'
#' # parameters can be changed between the training data and validation set,
#' # for example to account for training data in a text file with a header row
#' # and validation data in a text file without it
#' train_file <- tempfile(pattern = "train_", fileext = ".csv")
#' write.table(
#'   data.frame(y = rnorm(100L), x1 = rnorm(100L), x2 = rnorm(100L))
#'   , file = train_file
#'   , sep = ","
#'   , col.names = TRUE
#'   , row.names = FALSE
#'   , quote = FALSE
#' )
#'
#' valid_file <- tempfile(pattern = "valid_", fileext = ".csv")
#' write.table(
#'   data.frame(y = rnorm(100L), x1 = rnorm(100L), x2 = rnorm(100L))
#'   , file = valid_file
#'   , sep = ","
#'   , col.names = FALSE
#'   , row.names = FALSE
#'   , quote = FALSE
#' )
#'
#' dtrain <- lgb.Dataset(
#'   data = train_file
#'   , params = list(has_header = TRUE)
#' )
#' dtrain$construct()
#'
#' dvalid <- lgb.Dataset(
#'   data = valid_file
#'   , params = list(has_header = FALSE)
#' )
#' dvalid$construct()
890
#' }
Guolin Ke's avatar
Guolin Ke committed
891
#' @export
892
893
894
895
896
897
lgb.Dataset.create.valid <- function(dataset,
                                     data,
                                     label = NULL,
                                     weight = NULL,
                                     group = NULL,
                                     init_score = NULL,
898
                                     params = list()) {
James Lamb's avatar
James Lamb committed
899

900
  if (!.is_Dataset(x = dataset)) {
901
    stop("lgb.Dataset.create.valid: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
902
  }
James Lamb's avatar
James Lamb committed
903

904
  # Create validation dataset
905
906
907
908
909
910
911
  return(invisible(
    dataset$create_valid(
      data = data
      , label = label
      , weight = weight
      , group = group
      , init_score = init_score
912
      , params = params
913
914
    )
  ))
James Lamb's avatar
James Lamb committed
915

916
}
Guolin Ke's avatar
Guolin Ke committed
917

918
919
920
#' @name lgb.Dataset.construct
#' @title Construct Dataset explicitly
#' @description Construct Dataset explicitly
Guolin Ke's avatar
Guolin Ke committed
921
#' @param dataset Object of class \code{lgb.Dataset}
James Lamb's avatar
James Lamb committed
922
#'
Guolin Ke's avatar
Guolin Ke committed
923
#' @examples
924
#' \donttest{
925
926
#' \dontshow{setLGBMthreads(2L)}
#' \dontshow{data.table::setDTthreads(1L)}
927
928
929
930
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
931
#' }
932
#' @return constructed dataset
Guolin Ke's avatar
Guolin Ke committed
933
934
#' @export
lgb.Dataset.construct <- function(dataset) {
James Lamb's avatar
James Lamb committed
935

936
  if (!.is_Dataset(x = dataset)) {
937
    stop("lgb.Dataset.construct: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
938
  }
James Lamb's avatar
James Lamb committed
939

940
  return(invisible(dataset$construct()))
James Lamb's avatar
James Lamb committed
941

Guolin Ke's avatar
Guolin Ke committed
942
943
}

944
945
#' @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
946
#' @param x Object of class \code{lgb.Dataset}
James Lamb's avatar
James Lamb committed
947
#'
Guolin Ke's avatar
Guolin Ke committed
948
#' @return a vector of numbers of rows and of columns
James Lamb's avatar
James Lamb committed
949
#'
Guolin Ke's avatar
Guolin Ke committed
950
951
952
#' @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
953
#'
Guolin Ke's avatar
Guolin Ke committed
954
#' @examples
955
#' \donttest{
956
957
#' \dontshow{setLGBMthreads(2L)}
#' \dontshow{data.table::setDTthreads(1L)}
958
959
960
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
James Lamb's avatar
James Lamb committed
961
#'
962
963
964
#' stopifnot(nrow(dtrain) == nrow(train$data))
#' stopifnot(ncol(dtrain) == ncol(train$data))
#' stopifnot(all(dim(dtrain) == dim(train$data)))
965
#' }
Guolin Ke's avatar
Guolin Ke committed
966
967
#' @rdname dim
#' @export
968
dim.lgb.Dataset <- function(x) {
969

970
  if (!.is_Dataset(x = x)) {
971
    stop("dim.lgb.Dataset: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
972
  }
James Lamb's avatar
James Lamb committed
973

974
  return(x$dim())
James Lamb's avatar
James Lamb committed
975

Guolin Ke's avatar
Guolin Ke committed
976
977
}

978
979
980
#' @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
981
982
#' @param x object of class \code{lgb.Dataset}
#' @param value a list of two elements: the first one is ignored
983
#'              and the second one is column names
Guolin Ke's avatar
Guolin Ke committed
984
985
986
987
988
989
#'
#' @details
#' Generic \code{dimnames} methods are used by \code{colnames}.
#' Since row names are irrelevant, it is recommended to use \code{colnames} directly.
#'
#' @examples
990
#' \donttest{
991
992
#' \dontshow{setLGBMthreads(2L)}
#' \dontshow{data.table::setDTthreads(1L)}
993
994
995
996
997
998
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
#' dimnames(dtrain)
#' colnames(dtrain)
999
#' colnames(dtrain) <- make.names(seq_len(ncol(train$data)))
1000
#' print(dtrain, verbose = TRUE)
1001
#' }
Guolin Ke's avatar
Guolin Ke committed
1002
#' @rdname dimnames.lgb.Dataset
1003
#' @return A list with the dimension names of the dataset
Guolin Ke's avatar
Guolin Ke committed
1004
1005
#' @export
dimnames.lgb.Dataset <- function(x) {
James Lamb's avatar
James Lamb committed
1006

1007
  if (!.is_Dataset(x = x)) {
1008
    stop("dimnames.lgb.Dataset: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1009
  }
James Lamb's avatar
James Lamb committed
1010

1011
  # Return dimension names
1012
  return(list(NULL, x$get_colnames()))
James Lamb's avatar
James Lamb committed
1013

Guolin Ke's avatar
Guolin Ke committed
1014
1015
1016
1017
1018
}

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

1020
  # Check if invalid element list
1021
  if (!identical(class(value), "list") || length(value) != 2L) {
1022
    stop("invalid ", sQuote("value"), " given: must be a list of two elements")
1023
  }
James Lamb's avatar
James Lamb committed
1024

1025
1026
1027
1028
  # Check for unknown row names
  if (!is.null(value[[1L]])) {
    stop("lgb.Dataset does not have rownames")
  }
James Lamb's avatar
James Lamb committed
1029

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

1032
    x$set_colnames(colnames = NULL)
Guolin Ke's avatar
Guolin Ke committed
1033
    return(x)
James Lamb's avatar
James Lamb committed
1034

1035
  }
James Lamb's avatar
James Lamb committed
1036

1037
  # Check for unmatching column size
1038
  if (ncol(x) != length(value[[2L]])) {
1039
1040
    stop(
      "can't assign "
1041
      , sQuote(length(value[[2L]]))
1042
1043
1044
1045
      , " colnames to an lgb.Dataset with "
      , sQuote(ncol(x))
      , " columns"
    )
Guolin Ke's avatar
Guolin Ke committed
1046
  }
James Lamb's avatar
James Lamb committed
1047

1048
  # Set column names properly, and return
1049
  x$set_colnames(colnames = value[[2L]])
1050
  return(x)
James Lamb's avatar
James Lamb committed
1051

Guolin Ke's avatar
Guolin Ke committed
1052
1053
}

1054
1055
1056
#' @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
1057
#' @param dataset Object of class \code{lgb.Dataset}
1058
#' @param idxset an integer vector of indices of rows needed
Guolin Ke's avatar
Guolin Ke committed
1059
#' @return constructed sub dataset
James Lamb's avatar
James Lamb committed
1060
#'
Guolin Ke's avatar
Guolin Ke committed
1061
#' @examples
1062
#' \donttest{
1063
1064
#' \dontshow{setLGBMthreads(2L)}
#' \dontshow{data.table::setDTthreads(1L)}
1065
1066
1067
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
James Lamb's avatar
James Lamb committed
1068
#'
1069
#' dsub <- lgb.slice.Dataset(dtrain, seq_len(42L))
1070
#' lgb.Dataset.construct(dsub)
1071
#' labels <- lightgbm::get_field(dsub, "label")
1072
#' }
Guolin Ke's avatar
Guolin Ke committed
1073
#' @export
1074
lgb.slice.Dataset <- function(dataset, idxset) {
James Lamb's avatar
James Lamb committed
1075

1076
  if (!.is_Dataset(x = dataset)) {
1077
    stop("lgb.slice.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1078
  }
James Lamb's avatar
James Lamb committed
1079

1080
  return(invisible(dataset$slice(idxset = idxset)))
James Lamb's avatar
James Lamb committed
1081

Guolin Ke's avatar
Guolin Ke committed
1082
1083
}

1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
#' @name get_field
#' @title Get one attribute of a \code{lgb.Dataset}
#' @description Get one attribute of a \code{lgb.Dataset}
#' @param dataset Object of class \code{lgb.Dataset}
#' @param field_name String with the name of the attribute to get. One of the following.
#' \itemize{
#'     \item \code{label}: label lightgbm learns from ;
#'     \item \code{weight}: to do a weight rescale ;
#'     \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.}
#'     \item \code{init_score}: initial score is the base prediction lightgbm will boost from.
#' }
#' @return requested attribute
#'
#' @examples
#' \donttest{
1103
1104
#' \dontshow{setLGBMthreads(2L)}
#' \dontshow{data.table::setDTthreads(1L)}
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
#'
#' labels <- lightgbm::get_field(dtrain, "label")
#' lightgbm::set_field(dtrain, "label", 1 - labels)
#'
#' labels2 <- lightgbm::get_field(dtrain, "label")
#' stopifnot(all(labels2 == 1 - labels))
#' }
#' @export
get_field <- function(dataset, field_name) {
  UseMethod("get_field")
}

#' @rdname get_field
#' @export
get_field.lgb.Dataset <- function(dataset, field_name) {

  # Check if dataset is not a dataset
1126
  if (!.is_Dataset(x = dataset)) {
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
    stop("get_field.lgb.Dataset(): input dataset should be an lgb.Dataset object")
  }

  return(dataset$get_field(field_name = field_name))

}

#' @name set_field
#' @title Set one attribute of a \code{lgb.Dataset} object
#' @description Set one attribute of a \code{lgb.Dataset}
#' @param dataset Object of class \code{lgb.Dataset}
#' @param field_name String with the name of the attribute to set. One of the following.
#' \itemize{
#'     \item \code{label}: label lightgbm learns from ;
#'     \item \code{weight}: to do a weight rescale ;
#'     \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.}
#'     \item \code{init_score}: initial score is the base prediction lightgbm will boost from.
#' }
#' @param data The data for the field. See examples.
#' @return The \code{lgb.Dataset} you passed in.
#'
#' @examples
#' \donttest{
1154
1155
#' \dontshow{setLGBMthreads(2L)}
#' \dontshow{data.table::setDTthreads(1L)}
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
#'
#' labels <- lightgbm::get_field(dtrain, "label")
#' lightgbm::set_field(dtrain, "label", 1 - labels)
#'
#' labels2 <- lightgbm::get_field(dtrain, "label")
#' stopifnot(all.equal(labels2, 1 - labels))
#' }
#' @export
set_field <- function(dataset, field_name, data) {
  UseMethod("set_field")
}

#' @rdname set_field
#' @export
set_field.lgb.Dataset <- function(dataset, field_name, data) {

1176
  if (!.is_Dataset(x = dataset)) {
1177
1178
1179
1180
    stop("set_field.lgb.Dataset: input dataset should be an lgb.Dataset object")
  }

  return(invisible(dataset$set_field(field_name = field_name, data = data)))
Guolin Ke's avatar
Guolin Ke committed
1181
1182
}

1183
1184
1185
1186
#' @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.
1187
#' @param dataset object of class \code{lgb.Dataset}
1188
1189
1190
#' @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").
1191
#' @return the dataset you passed in
James Lamb's avatar
James Lamb committed
1192
#'
1193
#' @examples
1194
#' \donttest{
1195
1196
#' \dontshow{setLGBMthreads(2L)}
#' \dontshow{data.table::setDTthreads(1L)}
1197
1198
1199
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
1200
1201
1202
#' data_file <- tempfile(fileext = ".data")
#' lgb.Dataset.save(dtrain, data_file)
#' dtrain <- lgb.Dataset(data_file)
1203
#' lgb.Dataset.set.categorical(dtrain, 1L:2L)
1204
#' }
1205
1206
1207
#' @rdname lgb.Dataset.set.categorical
#' @export
lgb.Dataset.set.categorical <- function(dataset, categorical_feature) {
James Lamb's avatar
James Lamb committed
1208

1209
  if (!.is_Dataset(x = dataset)) {
1210
1211
    stop("lgb.Dataset.set.categorical: input dataset should be an lgb.Dataset object")
  }
James Lamb's avatar
James Lamb committed
1212

1213
  return(invisible(dataset$set_categorical_feature(categorical_feature = categorical_feature)))
James Lamb's avatar
James Lamb committed
1214

1215
1216
}

1217
1218
1219
#' @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
1220
1221
#' @param dataset object of class \code{lgb.Dataset}
#' @param reference object of class \code{lgb.Dataset}
James Lamb's avatar
James Lamb committed
1222
#'
1223
#' @return the dataset you passed in
James Lamb's avatar
James Lamb committed
1224
#'
Guolin Ke's avatar
Guolin Ke committed
1225
#' @examples
1226
#' \donttest{
1227
1228
#' \dontshow{setLGBMthreads(2L)}
#' \dontshow{data.table::setDTthreads(1L)}
1229
#' # create training Dataset
1230
1231
1232
#' data(agaricus.train, package ="lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
1233
1234
#'
#' # create a validation Dataset, using dtrain as a reference
1235
1236
#' data(agaricus.test, package = "lightgbm")
#' test <- agaricus.test
1237
#' dtest <- lgb.Dataset(test$data, label = test$label)
1238
#' lgb.Dataset.set.reference(dtest, dtrain)
1239
#' }
Guolin Ke's avatar
Guolin Ke committed
1240
1241
1242
#' @rdname lgb.Dataset.set.reference
#' @export
lgb.Dataset.set.reference <- function(dataset, reference) {
James Lamb's avatar
James Lamb committed
1243

1244
  if (!.is_Dataset(x = dataset)) {
1245
    stop("lgb.Dataset.set.reference: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1246
  }
James Lamb's avatar
James Lamb committed
1247

1248
  return(invisible(dataset$set_reference(reference = reference)))
Guolin Ke's avatar
Guolin Ke committed
1249
1250
}

1251
1252
1253
1254
#' @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
1255
1256
#' @param dataset object of class \code{lgb.Dataset}
#' @param fname object filename of output file
James Lamb's avatar
James Lamb committed
1257
#'
1258
#' @return the dataset you passed in
James Lamb's avatar
James Lamb committed
1259
#'
Guolin Ke's avatar
Guolin Ke committed
1260
#' @examples
1261
#' \donttest{
1262
1263
#' \dontshow{setLGBMthreads(2L)}
#' \dontshow{data.table::setDTthreads(1L)}
1264
1265
1266
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
1267
#' lgb.Dataset.save(dtrain, tempfile(fileext = ".bin"))
1268
#' }
Guolin Ke's avatar
Guolin Ke committed
1269
1270
#' @export
lgb.Dataset.save <- function(dataset, fname) {
James Lamb's avatar
James Lamb committed
1271

1272
  if (!.is_Dataset(x = dataset)) {
1273
    stop("lgb.Dataset.save: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1274
  }
James Lamb's avatar
James Lamb committed
1275

1276
  if (!is.character(fname)) {
1277
    stop("lgb.Dataset.save: fname should be a character or a file connection")
Guolin Ke's avatar
Guolin Ke committed
1278
  }
James Lamb's avatar
James Lamb committed
1279

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