lgb.Dataset.R 35.2 KB
Newer Older
James Lamb's avatar
James Lamb committed
1
#' @importFrom methods is
James Lamb's avatar
James Lamb committed
2
3
4
#' @importFrom R6 R6Class
Dataset <- R6::R6Class(

5
  classname = "lgb.Dataset",
6
  cloneable = FALSE,
Guolin Ke's avatar
Guolin Ke committed
7
  public = list(
James Lamb's avatar
James Lamb committed
8

9
    # Finalize will free up the handles
Guolin Ke's avatar
Guolin Ke committed
10
    finalize = function() {
James Lamb's avatar
James Lamb committed
11

12
      # Check the need for freeing handle
13
      if (!lgb.is.null.handle(x = private$handle)) {
James Lamb's avatar
James Lamb committed
14

15
        # Freeing up handle
16
17
18
19
        .Call(
          LGBM_DatasetFree_R
          , private$handle
        )
Guolin Ke's avatar
Guolin Ke committed
20
        private$handle <- NULL
James Lamb's avatar
James Lamb committed
21

Guolin Ke's avatar
Guolin Ke committed
22
      }
James Lamb's avatar
James Lamb committed
23

24
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.check.r6.class(object = reference, name = "lgb.Dataset"))) {
42
43
          stop("lgb.Dataset: If provided, reference must be a ", sQuote("lgb.Dataset"))
      }
44
      if (!(is.null(predictor) || lgb.check.r6.class(object = predictor, name = "lgb.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
52
      # Create known attributes list
      INFO_KEYS <- c("label", "weight", "init_score", "group")
James Lamb's avatar
James Lamb committed
53

54
      # Check if attribute key is in the known attribute list
55
      for (key in names(additional_params)) {
James Lamb's avatar
James Lamb committed
56

57
        # Key existing
58
        if (key %in% INFO_KEYS) {
James Lamb's avatar
James Lamb committed
59

60
          # Store as info
61
          info[[key]] <- additional_params[[key]]
James Lamb's avatar
James Lamb committed
62

Guolin Ke's avatar
Guolin Ke committed
63
        } else {
James Lamb's avatar
James Lamb committed
64

65
          # Store as param
66
          params[[key]] <- additional_params[[key]]
James Lamb's avatar
James Lamb committed
67

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

Guolin Ke's avatar
Guolin Ke committed
70
      }
James Lamb's avatar
James Lamb committed
71

72
73
74
75
76
77
78
      # 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
79

80
81
82
      # Setup private attributes
      private$raw_data <- data
      private$params <- params
Guolin Ke's avatar
Guolin Ke committed
83
      private$reference <- reference
84
      private$colnames <- colnames
85

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

93
94
      return(invisible(NULL))

Guolin Ke's avatar
Guolin Ke committed
95
    },
James Lamb's avatar
James Lamb committed
96

97
98
99
    create_valid = function(data,
                            info = list(),
                            ...) {
James Lamb's avatar
James Lamb committed
100

101
      # Create new dataset
102
103
104
105
106
107
108
109
110
111
112
113
      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
114

115
      return(invisible(ret))
James Lamb's avatar
James Lamb committed
116

Guolin Ke's avatar
Guolin Ke committed
117
    },
James Lamb's avatar
James Lamb committed
118

119
    # Dataset constructor
Guolin Ke's avatar
Guolin Ke committed
120
    construct = function() {
James Lamb's avatar
James Lamb committed
121

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

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

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

138
139
      # Get categorical feature index
      if (!is.null(private$categorical_feature)) {
James Lamb's avatar
James Lamb committed
140

141
        # Check for character name
142
        if (is.character(private$categorical_feature)) {
James Lamb's avatar
James Lamb committed
143

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

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

154
          } else {
James Lamb's avatar
James Lamb committed
155

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

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

170
          }
James Lamb's avatar
James Lamb committed
171

172
        # Store indices for categorical features
173
        private$params$categorical_feature <- cate_indices
James Lamb's avatar
James Lamb committed
174

175
      }
James Lamb's avatar
James Lamb committed
176

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

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

190
      # Get handle of reference dataset
Guolin Ke's avatar
Guolin Ke committed
191
192
193
194
      ref_handle <- NULL
      if (!is.null(private$reference)) {
        ref_handle <- private$reference$.__enclos_env__$private$get_handle()
      }
Guolin Ke's avatar
Guolin Ke committed
195
      handle <- lgb.null.handle()
James Lamb's avatar
James Lamb committed
196

197
      # Not subsetting
Guolin Ke's avatar
Guolin Ke committed
198
      if (is.null(private$used_indices)) {
James Lamb's avatar
James Lamb committed
199

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

203
204
          .Call(
            LGBM_DatasetCreateFromFile_R
205
            , lgb.c_str(x = private$raw_data)
206
207
            , params_str
            , ref_handle
208
            , handle
209
          )
James Lamb's avatar
James Lamb committed
210

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

213
          # Are we using a matrix?
214
215
          .Call(
            LGBM_DatasetCreateFromMat_R
216
217
218
219
220
            , private$raw_data
            , nrow(private$raw_data)
            , ncol(private$raw_data)
            , params_str
            , ref_handle
221
            , handle
222
          )
James Lamb's avatar
James Lamb committed
223
224

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

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

244
          # Unknown data type
245
246
247
248
          stop(
            "lgb.Dataset.construct: does not support constructing from "
            , sQuote(class(private$raw_data))
          )
James Lamb's avatar
James Lamb committed
249

Guolin Ke's avatar
Guolin Ke committed
250
        }
James Lamb's avatar
James Lamb committed
251

Guolin Ke's avatar
Guolin Ke committed
252
      } else {
James Lamb's avatar
James Lamb committed
253

254
        # Reference is empty
Guolin Ke's avatar
Guolin Ke committed
255
        if (is.null(private$reference)) {
256
          stop("lgb.Dataset.construct: reference cannot be NULL for constructing data subset")
Guolin Ke's avatar
Guolin Ke committed
257
        }
James Lamb's avatar
James Lamb committed
258

259
        # Construct subset
260
261
        .Call(
          LGBM_DatasetGetSubset_R
262
263
264
265
          , ref_handle
          , c(private$used_indices) # Adding c() fixes issue in R v3.5
          , length(private$used_indices)
          , params_str
266
          , handle
267
        )
James Lamb's avatar
James Lamb committed
268

Guolin Ke's avatar
Guolin Ke committed
269
      }
270
      if (lgb.is.null.handle(x = handle)) {
Guolin Ke's avatar
Guolin Ke committed
271
272
        stop("lgb.Dataset.construct: cannot create Dataset handle")
      }
273
      # Setup class and private type
Guolin Ke's avatar
Guolin Ke committed
274
275
      class(handle) <- "lgb.Dataset.handle"
      private$handle <- handle
James Lamb's avatar
James Lamb committed
276

277
278
      # Set feature names
      if (!is.null(private$colnames)) {
279
        self$set_colnames(colnames = private$colnames)
280
      }
281

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

285
        # Setup initial scores
286
        init_score <- private$predictor$predict(
287
          data = private$raw_data
288
289
290
          , rawscore = TRUE
          , reshape = TRUE
        )
James Lamb's avatar
James Lamb committed
291

292
        # Not needed to transpose, for is col_marjor
Guolin Ke's avatar
Guolin Ke committed
293
294
        init_score <- as.vector(init_score)
        private$info$init_score <- init_score
James Lamb's avatar
James Lamb committed
295

296
      }
James Lamb's avatar
James Lamb committed
297

298
299
300
      # Should we free raw data?
      if (isTRUE(private$free_raw_data)) {
        private$raw_data <- NULL
Guolin Ke's avatar
Guolin Ke committed
301
      }
James Lamb's avatar
James Lamb committed
302

303
      # Get private information
304
      if (length(private$info) > 0L) {
James Lamb's avatar
James Lamb committed
305

306
        # Set infos
307
        for (i in seq_along(private$info)) {
James Lamb's avatar
James Lamb committed
308

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

Guolin Ke's avatar
Guolin Ke committed
312
        }
James Lamb's avatar
James Lamb committed
313

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

316
      # Get label information existence
317
      if (is.null(self$getinfo(name = "label"))) {
Guolin Ke's avatar
Guolin Ke committed
318
319
        stop("lgb.Dataset.construct: label should be set")
      }
James Lamb's avatar
James Lamb committed
320

321
      return(invisible(self))
James Lamb's avatar
James Lamb committed
322

Guolin Ke's avatar
Guolin Ke committed
323
    },
James Lamb's avatar
James Lamb committed
324

325
    # Dimension function
Guolin Ke's avatar
Guolin Ke committed
326
    dim = function() {
James Lamb's avatar
James Lamb committed
327

328
      # Check for handle
329
      if (!lgb.is.null.handle(x = private$handle)) {
James Lamb's avatar
James Lamb committed
330

331
332
        num_row <- 0L
        num_col <- 0L
James Lamb's avatar
James Lamb committed
333

334
        # Get numeric data and numeric features
335
336
337
338
339
340
341
342
343
344
        .Call(
          LGBM_DatasetGetNumData_R
          , private$handle
          , num_row
        )
        .Call(
          LGBM_DatasetGetNumFeature_R
          , private$handle
          , num_col
        )
345
        return(
346
          c(num_row, num_col)
347
        )
James Lamb's avatar
James Lamb committed
348
349
350

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

351
        # Check if dgCMatrix (sparse matrix column compressed)
352
        # NOTE: requires Matrix package
353
        return(dim(private$raw_data))
James Lamb's avatar
James Lamb committed
354

Guolin Ke's avatar
Guolin Ke committed
355
      } else {
James Lamb's avatar
James Lamb committed
356

357
        # Trying to work with unknown dimensions is not possible
358
359
360
361
        stop(
          "dim: cannot get dimensions before dataset has been constructed, "
          , "please call lgb.Dataset.construct explicitly"
        )
James Lamb's avatar
James Lamb committed
362

Guolin Ke's avatar
Guolin Ke committed
363
      }
James Lamb's avatar
James Lamb committed
364

Guolin Ke's avatar
Guolin Ke committed
365
    },
James Lamb's avatar
James Lamb committed
366

367
    # Get column names
Guolin Ke's avatar
Guolin Ke committed
368
    get_colnames = function() {
James Lamb's avatar
James Lamb committed
369

370
      # Check for handle
371
      if (!lgb.is.null.handle(x = private$handle)) {
James Lamb's avatar
James Lamb committed
372

373
        # Get feature names and write them
374
375
376
377
378
379
380
381
382
        buf_len <- as.integer(1024L * 1024L)
        act_len <- 0L
        buf <- raw(buf_len)
        .Call(
          LGBM_DatasetGetFeatureNames_R
          , private$handle
          , buf_len
          , act_len
          , buf
383
        )
384
385
386
387
388
389
390
391
392
393
394
395
        if (act_len > buf_len) {
          buf_len <- act_len
          buf <- raw(buf_len)
          .Call(
            LGBM_DatasetGetFeatureNames_R
            , private$handle
            , buf_len
            , act_len
            , buf
          )
        }
        cnames <- lgb.encode.char(arr = buf, len = act_len)
396
        private$colnames <- as.character(base::strsplit(cnames, "\t")[[1L]])
397
        return(private$colnames)
James Lamb's avatar
James Lamb committed
398
399
400

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

401
        # Check if dgCMatrix (sparse matrix column compressed)
402
        return(colnames(private$raw_data))
James Lamb's avatar
James Lamb committed
403

Guolin Ke's avatar
Guolin Ke committed
404
      } else {
James Lamb's avatar
James Lamb committed
405

406
        # Trying to work with unknown dimensions is not possible
407
408
409
410
        stop(
          "dim: cannot get dimensions before dataset has been constructed, please call "
          , "lgb.Dataset.construct explicitly"
        )
James Lamb's avatar
James Lamb committed
411

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

Guolin Ke's avatar
Guolin Ke committed
414
    },
James Lamb's avatar
James Lamb committed
415

416
    # Set column names
Guolin Ke's avatar
Guolin Ke committed
417
    set_colnames = function(colnames) {
James Lamb's avatar
James Lamb committed
418

419
420
      # Check column names non-existence
      if (is.null(colnames)) {
421
        return(invisible(self))
422
      }
James Lamb's avatar
James Lamb committed
423

424
      # Check empty column names
Guolin Ke's avatar
Guolin Ke committed
425
      colnames <- as.character(colnames)
426
      if (length(colnames) == 0L) {
427
        return(invisible(self))
428
      }
James Lamb's avatar
James Lamb committed
429

430
      # Write column names
Guolin Ke's avatar
Guolin Ke committed
431
      private$colnames <- colnames
432
      if (!lgb.is.null.handle(x = private$handle)) {
James Lamb's avatar
James Lamb committed
433

434
        # Merge names with tab separation
Guolin Ke's avatar
Guolin Ke committed
435
        merged_name <- paste0(as.list(private$colnames), collapse = "\t")
436
437
        .Call(
          LGBM_DatasetSetFeatureNames_R
438
          , private$handle
439
          , lgb.c_str(x = merged_name)
440
        )
James Lamb's avatar
James Lamb committed
441

Guolin Ke's avatar
Guolin Ke committed
442
      }
James Lamb's avatar
James Lamb committed
443

444
      return(invisible(self))
James Lamb's avatar
James Lamb committed
445

Guolin Ke's avatar
Guolin Ke committed
446
    },
James Lamb's avatar
James Lamb committed
447

448
    # Get information
Guolin Ke's avatar
Guolin Ke committed
449
    getinfo = function(name) {
James Lamb's avatar
James Lamb committed
450

451
      # Create known attributes list
452
      INFONAMES <- c("label", "weight", "init_score", "group")
James Lamb's avatar
James Lamb committed
453

454
      # Check if attribute key is in the known attribute list
455
      if (!is.character(name) || length(name) != 1L || !name %in% INFONAMES) {
456
        stop("getinfo: name must one of the following: ", paste0(sQuote(INFONAMES), collapse = ", "))
Guolin Ke's avatar
Guolin Ke committed
457
      }
James Lamb's avatar
James Lamb committed
458

459
      # Check for info name and handle
460
      if (is.null(private$info[[name]])) {
461

462
        if (lgb.is.null.handle(x = private$handle)) {
463
          stop("Cannot perform getinfo before constructing Dataset.")
464
        }
465

466
        # Get field size of info
467
        info_len <- 0L
468
469
        .Call(
          LGBM_DatasetGetFieldSize_R
470
          , private$handle
471
          , lgb.c_str(x = name)
472
          , info_len
473
        )
James Lamb's avatar
James Lamb committed
474

475
        # Check if info is not empty
476
        if (info_len > 0L) {
James Lamb's avatar
James Lamb committed
477

478
          # Get back fields
Guolin Ke's avatar
Guolin Ke committed
479
          ret <- NULL
480
481
482
483
484
          ret <- if (name == "group") {
            integer(info_len) # Integer
          } else {
            numeric(info_len) # Numeric
          }
James Lamb's avatar
James Lamb committed
485

486
487
          .Call(
            LGBM_DatasetGetField_R
488
            , private$handle
489
            , lgb.c_str(x = name)
490
            , ret
491
          )
James Lamb's avatar
James Lamb committed
492

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

Guolin Ke's avatar
Guolin Ke committed
495
496
        }
      }
James Lamb's avatar
James Lamb committed
497

498
      return(private$info[[name]])
James Lamb's avatar
James Lamb committed
499

Guolin Ke's avatar
Guolin Ke committed
500
    },
James Lamb's avatar
James Lamb committed
501

502
    # Set information
Guolin Ke's avatar
Guolin Ke committed
503
    setinfo = function(name, info) {
James Lamb's avatar
James Lamb committed
504

505
      # Create known attributes list
506
      INFONAMES <- c("label", "weight", "init_score", "group")
James Lamb's avatar
James Lamb committed
507

508
      # Check if attribute key is in the known attribute list
509
      if (!is.character(name) || length(name) != 1L || !name %in% INFONAMES) {
510
511
        stop("setinfo: name must one of the following: ", paste0(sQuote(INFONAMES), collapse = ", "))
      }
James Lamb's avatar
James Lamb committed
512

513
514
515
516
517
518
      # 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
519

520
      # Store information privately
Guolin Ke's avatar
Guolin Ke committed
521
      private$info[[name]] <- info
James Lamb's avatar
James Lamb committed
522

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

525
        if (length(info) > 0L) {
James Lamb's avatar
James Lamb committed
526

527
528
          .Call(
            LGBM_DatasetSetField_R
529
            , private$handle
530
            , lgb.c_str(x = name)
531
532
533
            , info
            , length(info)
          )
James Lamb's avatar
James Lamb committed
534

535
536
          private$version <- private$version + 1L

Guolin Ke's avatar
Guolin Ke committed
537
        }
James Lamb's avatar
James Lamb committed
538

Guolin Ke's avatar
Guolin Ke committed
539
      }
James Lamb's avatar
James Lamb committed
540

541
      return(invisible(self))
James Lamb's avatar
James Lamb committed
542

Guolin Ke's avatar
Guolin Ke committed
543
    },
James Lamb's avatar
James Lamb committed
544

545
    # Slice dataset
Guolin Ke's avatar
Guolin Ke committed
546
    slice = function(idxset, ...) {
James Lamb's avatar
James Lamb committed
547

548
      # Perform slicing
549
550
551
552
553
554
555
556
557
558
559
560
561
      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
          , ...
        )
562
      )
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
567
568
    # [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.
569
    update_params = function(params) {
570
571
572
      if (length(params) == 0L) {
        return(invisible(self))
      }
573
      if (lgb.is.null.handle(x = private$handle)) {
574
575
        private$params <- modifyList(private$params, params)
      } else {
576
577
        tryCatch({
          .Call(
578
            LGBM_DatasetUpdateParamChecking_R
579
580
581
582
583
584
            , 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
585
          if (is.null(private$raw_data)) {
586
            stop(e)
587
588
          }

589
590
          # If updating failed but raw data is available, modify the params
          # on the R side and re-set ("deconstruct") the Dataset
591
592
          private$params <- modifyList(private$params, params)
          self$finalize()
593
        })
594
      }
595
      return(invisible(self))
James Lamb's avatar
James Lamb committed
596

Guolin Ke's avatar
Guolin Ke committed
597
    },
James Lamb's avatar
James Lamb committed
598

599
600
601
602
603
604
605
606
607
608
609
    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)
    },

610
    # Set categorical feature parameter
611
    set_categorical_feature = function(categorical_feature) {
James Lamb's avatar
James Lamb committed
612

613
614
      # Check for identical input
      if (identical(private$categorical_feature, categorical_feature)) {
615
        return(invisible(self))
616
      }
James Lamb's avatar
James Lamb committed
617

618
      # Check for empty data
619
      if (is.null(private$raw_data)) {
620
621
        stop("set_categorical_feature: cannot set categorical feature after freeing raw data,
          please set ", sQuote("free_raw_data = FALSE"), " when you construct lgb.Dataset")
622
      }
James Lamb's avatar
James Lamb committed
623

624
      # Overwrite categorical features
625
      private$categorical_feature <- categorical_feature
James Lamb's avatar
James Lamb committed
626

627
      # Finalize and return self
628
      self$finalize()
629
      return(invisible(self))
James Lamb's avatar
James Lamb committed
630

631
    },
James Lamb's avatar
James Lamb committed
632

633
    # Set reference
Guolin Ke's avatar
Guolin Ke committed
634
    set_reference = function(reference) {
James Lamb's avatar
James Lamb committed
635

636
      # Set known references
637
638
639
      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
640

641
642
      # Check for identical references
      if (identical(private$reference, reference)) {
643
        return(invisible(self))
644
      }
James Lamb's avatar
James Lamb committed
645

646
      # Check for empty data
Guolin Ke's avatar
Guolin Ke committed
647
      if (is.null(private$raw_data)) {
James Lamb's avatar
James Lamb committed
648

649
650
        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
651

Guolin Ke's avatar
Guolin Ke committed
652
      }
James Lamb's avatar
James Lamb committed
653

654
      # Check for non-existing reference
Guolin Ke's avatar
Guolin Ke committed
655
      if (!is.null(reference)) {
James Lamb's avatar
James Lamb committed
656

657
        # Reference is unknown
658
        if (!lgb.check.r6.class(object = reference, name = "lgb.Dataset")) {
659
          stop("set_reference: Can only use lgb.Dataset as a reference")
Guolin Ke's avatar
Guolin Ke committed
660
        }
James Lamb's avatar
James Lamb committed
661

Guolin Ke's avatar
Guolin Ke committed
662
      }
James Lamb's avatar
James Lamb committed
663

664
      # Store reference
Guolin Ke's avatar
Guolin Ke committed
665
      private$reference <- reference
James Lamb's avatar
James Lamb committed
666

667
      # Finalize and return self
Guolin Ke's avatar
Guolin Ke committed
668
      self$finalize()
669
      return(invisible(self))
James Lamb's avatar
James Lamb committed
670

Guolin Ke's avatar
Guolin Ke committed
671
    },
James Lamb's avatar
James Lamb committed
672

673
    # Save binary model
Guolin Ke's avatar
Guolin Ke committed
674
    save_binary = function(fname) {
James Lamb's avatar
James Lamb committed
675

676
      # Store binary data
Guolin Ke's avatar
Guolin Ke committed
677
      self$construct()
678
679
      .Call(
        LGBM_DatasetSaveBinary_R
680
        , private$handle
681
        , lgb.c_str(x = fname)
682
      )
683
      return(invisible(self))
Guolin Ke's avatar
Guolin Ke committed
684
    }
James Lamb's avatar
James Lamb committed
685

Guolin Ke's avatar
Guolin Ke committed
686
687
  ),
  private = list(
688
689
690
691
692
    handle = NULL,
    raw_data = NULL,
    params = list(),
    reference = NULL,
    colnames = NULL,
693
    categorical_feature = NULL,
694
695
696
697
    predictor = NULL,
    free_raw_data = TRUE,
    used_indices = NULL,
    info = NULL,
698
    version = 0L,
James Lamb's avatar
James Lamb committed
699

700
701
    # Get handle
    get_handle = function() {
James Lamb's avatar
James Lamb committed
702

703
      # Get handle and construct if needed
704
      if (lgb.is.null.handle(x = private$handle)) {
705
706
        self$construct()
      }
707
      return(private$handle)
James Lamb's avatar
James Lamb committed
708

Guolin Ke's avatar
Guolin Ke committed
709
    },
James Lamb's avatar
James Lamb committed
710

711
    # Set predictor
Guolin Ke's avatar
Guolin Ke committed
712
    set_predictor = function(predictor) {
James Lamb's avatar
James Lamb committed
713

714
      if (identical(private$predictor, predictor)) {
715
        return(invisible(self))
716
      }
James Lamb's avatar
James Lamb committed
717

718
      # Check for empty data
Guolin Ke's avatar
Guolin Ke committed
719
      if (is.null(private$raw_data)) {
720
721
        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
722
      }
James Lamb's avatar
James Lamb committed
723

724
      # Check for empty predictor
Guolin Ke's avatar
Guolin Ke committed
725
      if (!is.null(predictor)) {
James Lamb's avatar
James Lamb committed
726

727
        # Predictor is unknown
728
        if (!lgb.check.r6.class(object = predictor, name = "lgb.Predictor")) {
729
          stop("set_predictor: Can only use lgb.Predictor as predictor")
Guolin Ke's avatar
Guolin Ke committed
730
        }
James Lamb's avatar
James Lamb committed
731

Guolin Ke's avatar
Guolin Ke committed
732
      }
James Lamb's avatar
James Lamb committed
733

734
      # Store predictor
Guolin Ke's avatar
Guolin Ke committed
735
      private$predictor <- predictor
James Lamb's avatar
James Lamb committed
736

737
      # Finalize and return self
Guolin Ke's avatar
Guolin Ke committed
738
      self$finalize()
739
      return(invisible(self))
James Lamb's avatar
James Lamb committed
740

Guolin Ke's avatar
Guolin Ke committed
741
    }
James Lamb's avatar
James Lamb committed
742

Guolin Ke's avatar
Guolin Ke committed
743
744
745
  )
)

746
747
748
#' @title Construct \code{lgb.Dataset} object
#' @description Construct \code{lgb.Dataset} object from dense matrix, sparse matrix
#'              or local file (that was created previously by saving an \code{lgb.Dataset}).
Guolin Ke's avatar
Guolin Ke committed
749
#' @param data a \code{matrix} object, a \code{dgCMatrix} object or a character representing a filename
750
751
752
753
754
755
756
#' @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
757
#' @param colnames names of columns
758
759
760
761
762
763
764
765
#' @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
766
#' @param info a list of information of the \code{lgb.Dataset} object
Guolin Ke's avatar
Guolin Ke committed
767
#' @param ... other information to pass to \code{info} or parameters pass to \code{params}
James Lamb's avatar
James Lamb committed
768
#'
Guolin Ke's avatar
Guolin Ke committed
769
#' @return constructed dataset
James Lamb's avatar
James Lamb committed
770
#'
Guolin Ke's avatar
Guolin Ke committed
771
#' @examples
772
#' \donttest{
773
774
775
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
776
777
778
#' data_file <- tempfile(fileext = ".data")
#' lgb.Dataset.save(dtrain, data_file)
#' dtrain <- lgb.Dataset(data_file)
779
#' lgb.Dataset.construct(dtrain)
780
#' }
Guolin Ke's avatar
Guolin Ke committed
781
782
#' @export
lgb.Dataset <- function(data,
783
784
785
                        params = list(),
                        reference = NULL,
                        colnames = NULL,
786
                        categorical_feature = NULL,
787
788
                        free_raw_data = TRUE,
                        info = list(),
Guolin Ke's avatar
Guolin Ke committed
789
                        ...) {
James Lamb's avatar
James Lamb committed
790

791
  # Create new dataset
792
793
794
795
796
797
798
799
800
801
802
803
804
805
  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
806

Guolin Ke's avatar
Guolin Ke committed
807
808
}

809
810
811
#' @name lgb.Dataset.create.valid
#' @title Construct validation data
#' @description Construct validation data according to training data
Guolin Ke's avatar
Guolin Ke committed
812
813
#' @param dataset \code{lgb.Dataset} object, training data
#' @param data a \code{matrix} object, a \code{dgCMatrix} object or a character representing a filename
Nikita Titov's avatar
Nikita Titov committed
814
#' @param info a list of information of the \code{lgb.Dataset} object
Guolin Ke's avatar
Guolin Ke committed
815
#' @param ... other information to pass to \code{info}.
James Lamb's avatar
James Lamb committed
816
#'
Guolin Ke's avatar
Guolin Ke committed
817
#' @return constructed dataset
James Lamb's avatar
James Lamb committed
818
#'
Guolin Ke's avatar
Guolin Ke committed
819
#' @examples
820
#' \donttest{
821
822
823
824
825
826
#' 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)
827
#' }
Guolin Ke's avatar
Guolin Ke committed
828
#' @export
829
lgb.Dataset.create.valid <- function(dataset, data, info = list(), ...) {
James Lamb's avatar
James Lamb committed
830

831
  # Check if dataset is not a dataset
832
  if (!lgb.is.Dataset(x = dataset)) {
833
    stop("lgb.Dataset.create.valid: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
834
  }
James Lamb's avatar
James Lamb committed
835

836
  # Create validation dataset
837
  return(invisible(dataset$create_valid(data = data, info = info, ...)))
James Lamb's avatar
James Lamb committed
838

839
}
Guolin Ke's avatar
Guolin Ke committed
840

841
842
843
#' @name lgb.Dataset.construct
#' @title Construct Dataset explicitly
#' @description Construct Dataset explicitly
Guolin Ke's avatar
Guolin Ke committed
844
#' @param dataset Object of class \code{lgb.Dataset}
James Lamb's avatar
James Lamb committed
845
#'
Guolin Ke's avatar
Guolin Ke committed
846
#' @examples
847
#' \donttest{
848
849
850
851
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
852
#' }
853
#' @return constructed dataset
Guolin Ke's avatar
Guolin Ke committed
854
855
#' @export
lgb.Dataset.construct <- function(dataset) {
James Lamb's avatar
James Lamb committed
856

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

862
  # Construct the dataset
863
  return(invisible(dataset$construct()))
James Lamb's avatar
James Lamb committed
864

Guolin Ke's avatar
Guolin Ke committed
865
866
}

867
868
#' @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
869
870
#' @param x Object of class \code{lgb.Dataset}
#' @param ... other parameters
James Lamb's avatar
James Lamb committed
871
#'
Guolin Ke's avatar
Guolin Ke committed
872
#' @return a vector of numbers of rows and of columns
James Lamb's avatar
James Lamb committed
873
#'
Guolin Ke's avatar
Guolin Ke committed
874
875
876
#' @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
877
#'
Guolin Ke's avatar
Guolin Ke committed
878
#' @examples
879
#' \donttest{
880
881
882
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
James Lamb's avatar
James Lamb committed
883
#'
884
885
886
#' stopifnot(nrow(dtrain) == nrow(train$data))
#' stopifnot(ncol(dtrain) == ncol(train$data))
#' stopifnot(all(dim(dtrain) == dim(train$data)))
887
#' }
Guolin Ke's avatar
Guolin Ke committed
888
889
890
#' @rdname dim
#' @export
dim.lgb.Dataset <- function(x, ...) {
James Lamb's avatar
James Lamb committed
891

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

897
  return(x$dim())
James Lamb's avatar
James Lamb committed
898

Guolin Ke's avatar
Guolin Ke committed
899
900
}

901
902
903
#' @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
904
905
#' @param x object of class \code{lgb.Dataset}
#' @param value a list of two elements: the first one is ignored
906
#'              and the second one is column names
Guolin Ke's avatar
Guolin Ke committed
907
908
909
910
911
912
#'
#' @details
#' Generic \code{dimnames} methods are used by \code{colnames}.
#' Since row names are irrelevant, it is recommended to use \code{colnames} directly.
#'
#' @examples
913
#' \donttest{
914
915
916
917
918
919
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
#' dimnames(dtrain)
#' colnames(dtrain)
920
#' colnames(dtrain) <- make.names(seq_len(ncol(train$data)))
921
#' print(dtrain, verbose = TRUE)
922
#' }
Guolin Ke's avatar
Guolin Ke committed
923
#' @rdname dimnames.lgb.Dataset
924
#' @return A list with the dimension names of the dataset
Guolin Ke's avatar
Guolin Ke committed
925
926
#' @export
dimnames.lgb.Dataset <- function(x) {
James Lamb's avatar
James Lamb committed
927

928
  # Check if dataset is not a dataset
929
  if (!lgb.is.Dataset(x = x)) {
930
    stop("dimnames.lgb.Dataset: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
931
  }
James Lamb's avatar
James Lamb committed
932

933
  # Return dimension names
934
  return(list(NULL, x$get_colnames()))
James Lamb's avatar
James Lamb committed
935

Guolin Ke's avatar
Guolin Ke committed
936
937
938
939
940
}

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

942
  # Check if invalid element list
943
  if (!identical(class(value), "list") || length(value) != 2L) {
944
    stop("invalid ", sQuote("value"), " given: must be a list of two elements")
945
  }
James Lamb's avatar
James Lamb committed
946

947
948
949
950
  # Check for unknown row names
  if (!is.null(value[[1L]])) {
    stop("lgb.Dataset does not have rownames")
  }
James Lamb's avatar
James Lamb committed
951

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

954
    x$set_colnames(colnames = NULL)
Guolin Ke's avatar
Guolin Ke committed
955
    return(x)
James Lamb's avatar
James Lamb committed
956

957
  }
James Lamb's avatar
James Lamb committed
958

959
  # Check for unmatching column size
960
  if (ncol(x) != length(value[[2L]])) {
961
962
    stop(
      "can't assign "
963
      , sQuote(length(value[[2L]]))
964
965
966
967
      , " colnames to an lgb.Dataset with "
      , sQuote(ncol(x))
      , " columns"
    )
Guolin Ke's avatar
Guolin Ke committed
968
  }
James Lamb's avatar
James Lamb committed
969

970
  # Set column names properly, and return
971
  x$set_colnames(colnames = value[[2L]])
972
  return(x)
James Lamb's avatar
James Lamb committed
973

Guolin Ke's avatar
Guolin Ke committed
974
975
}

976
977
978
#' @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
979
#' @param dataset Object of class \code{lgb.Dataset}
980
#' @param idxset an integer vector of indices of rows needed
Guolin Ke's avatar
Guolin Ke committed
981
982
#' @param ... other parameters (currently not used)
#' @return constructed sub dataset
James Lamb's avatar
James Lamb committed
983
#'
Guolin Ke's avatar
Guolin Ke committed
984
#' @examples
985
#' \donttest{
986
987
988
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
James Lamb's avatar
James Lamb committed
989
#'
990
#' dsub <- lightgbm::slice(dtrain, seq_len(42L))
991
#' lgb.Dataset.construct(dsub)
992
#' labels <- lightgbm::getinfo(dsub, "label")
993
#' }
Guolin Ke's avatar
Guolin Ke committed
994
#' @export
995
996
997
slice <- function(dataset, ...) {
  UseMethod("slice")
}
Guolin Ke's avatar
Guolin Ke committed
998
999
1000
1001

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

1003
  # Check if dataset is not a dataset
1004
  if (!lgb.is.Dataset(x = dataset)) {
1005
    stop("slice.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1006
  }
James Lamb's avatar
James Lamb committed
1007

1008
  # Return sliced set
1009
  return(invisible(dataset$slice(idxset = idxset, ...)))
James Lamb's avatar
James Lamb committed
1010

Guolin Ke's avatar
Guolin Ke committed
1011
1012
}

1013
1014
1015
#' @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
1016
1017
1018
1019
#' @param dataset Object of class \code{lgb.Dataset}
#' @param name the name of the information field to get (see details)
#' @param ... other parameters
#' @return info data
James Lamb's avatar
James Lamb committed
1020
#'
Guolin Ke's avatar
Guolin Ke committed
1021
1022
#' @details
#' The \code{name} field can be one of the following:
James Lamb's avatar
James Lamb committed
1023
#'
Guolin Ke's avatar
Guolin Ke committed
1024
1025
1026
#' \itemize{
#'     \item \code{label}: label lightgbm learn from ;
#'     \item \code{weight}: to do a weight rescale ;
1027
1028
1029
1030
1031
#'     \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
1032
#'     \item \code{init_score}: initial score is the base prediction lightgbm will boost from.
Guolin Ke's avatar
Guolin Ke committed
1033
#' }
James Lamb's avatar
James Lamb committed
1034
#'
Guolin Ke's avatar
Guolin Ke committed
1035
#' @examples
1036
#' \donttest{
1037
1038
1039
1040
#' 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
1041
#'
1042
1043
#' labels <- lightgbm::getinfo(dtrain, "label")
#' lightgbm::setinfo(dtrain, "label", 1 - labels)
James Lamb's avatar
James Lamb committed
1044
#'
1045
1046
#' labels2 <- lightgbm::getinfo(dtrain, "label")
#' stopifnot(all(labels2 == 1 - labels))
1047
#' }
Guolin Ke's avatar
Guolin Ke committed
1048
#' @export
1049
1050
1051
getinfo <- function(dataset, ...) {
  UseMethod("getinfo")
}
Guolin Ke's avatar
Guolin Ke committed
1052
1053
1054
1055

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

1057
  # Check if dataset is not a dataset
1058
  if (!lgb.is.Dataset(x = dataset)) {
1059
    stop("getinfo.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1060
  }
James Lamb's avatar
James Lamb committed
1061

1062
  return(dataset$getinfo(name = name))
James Lamb's avatar
James Lamb committed
1063

Guolin Ke's avatar
Guolin Ke committed
1064
1065
}

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

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

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

1115
  # Set information
1116
  return(invisible(dataset$setinfo(name = name, info = info)))
Guolin Ke's avatar
Guolin Ke committed
1117
1118
}

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

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

1147
  # Set categoricals
1148
  return(invisible(dataset$set_categorical_feature(categorical_feature = categorical_feature)))
James Lamb's avatar
James Lamb committed
1149

1150
1151
}

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

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

1179
  # Set reference
1180
  return(invisible(dataset$set_reference(reference = reference)))
Guolin Ke's avatar
Guolin Ke committed
1181
1182
}

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

1202
  # Check if dataset is not a dataset
1203
  if (!lgb.is.Dataset(x = dataset)) {
1204
    stop("lgb.Dataset.set: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1205
  }
James Lamb's avatar
James Lamb committed
1206

1207
  # File-type is not matching
1208
1209
  if (!is.character(fname)) {
    stop("lgb.Dataset.set: fname should be a character or a file connection")
Guolin Ke's avatar
Guolin Ke committed
1210
  }
James Lamb's avatar
James Lamb committed
1211

1212
  # Store binary
1213
  return(invisible(dataset$save_binary(fname = fname)))
Guolin Ke's avatar
Guolin Ke committed
1214
}