lgb.Dataset.R 32.3 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
Guolin Ke's avatar
Guolin Ke committed
13
      if (!lgb.is.null.handle(private$handle)) {
James Lamb's avatar
James Lamb committed
14

15
        # Freeing up handle
Guolin Ke's avatar
Guolin Ke committed
16
17
        lgb.call("LGBM_DatasetFree_R", ret = NULL, private$handle)
        private$handle <- NULL
James Lamb's avatar
James Lamb committed
18

Guolin Ke's avatar
Guolin Ke committed
19
      }
James Lamb's avatar
James Lamb committed
20

Guolin Ke's avatar
Guolin Ke committed
21
    },
James Lamb's avatar
James Lamb committed
22

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

35
36
37
38
39
40
41
42
      # validate inputs early to avoid unnecessary computation
      if (!(is.null(reference) || lgb.check.r6.class(reference, "lgb.Dataset"))) {
          stop("lgb.Dataset: If provided, reference must be a ", sQuote("lgb.Dataset"))
      }
      if (!(is.null(predictor) || lgb.check.r6.class(predictor, "lgb.Predictor"))) {
          stop("lgb.Dataset: If provided, predictor must be a ", sQuote("lgb.Predictor"))
      }

43
      # Check for additional parameters
44
      additional_params <- list(...)
James Lamb's avatar
James Lamb committed
45

46
47
      # Create known attributes list
      INFO_KEYS <- c("label", "weight", "init_score", "group")
James Lamb's avatar
James Lamb committed
48

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

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

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

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

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

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

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

67
68
69
70
71
72
73
      # 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
74

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

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

Guolin Ke's avatar
Guolin Ke committed
88
    },
James Lamb's avatar
James Lamb committed
89

90
91
92
    create_valid = function(data,
                            info = list(),
                            ...) {
James Lamb's avatar
James Lamb committed
93

94
      # Create new dataset
95
96
97
98
99
100
101
102
103
104
105
106
      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
107

108
      return(invisible(ret))
James Lamb's avatar
James Lamb committed
109

Guolin Ke's avatar
Guolin Ke committed
110
    },
James Lamb's avatar
James Lamb committed
111

112
    # Dataset constructor
Guolin Ke's avatar
Guolin Ke committed
113
    construct = function() {
James Lamb's avatar
James Lamb committed
114

115
      # Check for handle null
Guolin Ke's avatar
Guolin Ke committed
116
      if (!lgb.is.null.handle(private$handle)) {
117
        return(invisible(self))
Guolin Ke's avatar
Guolin Ke committed
118
      }
James Lamb's avatar
James Lamb committed
119

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

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

131
132
      # Get categorical feature index
      if (!is.null(private$categorical_feature)) {
James Lamb's avatar
James Lamb committed
133

134
        # Check for character name
135
        if (is.character(private$categorical_feature)) {
James Lamb's avatar
James Lamb committed
136

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

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

147
          } else {
James Lamb's avatar
James Lamb committed
148

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

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

163
          }
James Lamb's avatar
James Lamb committed
164

165
        # Store indices for categorical features
166
        private$params$categorical_feature <- cate_indices
James Lamb's avatar
James Lamb committed
167

168
      }
James Lamb's avatar
James Lamb committed
169

Guolin Ke's avatar
Guolin Ke committed
170
171
      # Check has header or not
      has_header <- FALSE
172
      if (!is.null(private$params$has_header) || !is.null(private$params$header)) {
173
174
175
        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
176
177
178
          has_header <- TRUE
        }
      }
James Lamb's avatar
James Lamb committed
179

Guolin Ke's avatar
Guolin Ke committed
180
181
      # Generate parameter str
      params_str <- lgb.params2str(private$params)
James Lamb's avatar
James Lamb committed
182

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

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

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

196
197
198
199
200
201
202
          handle <- lgb.call(
            "LGBM_DatasetCreateFromFile_R"
            , ret = handle
            , lgb.c_str(private$raw_data)
            , params_str
            , ref_handle
          )
James Lamb's avatar
James Lamb committed
203

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

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

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

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

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

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

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

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

252
        # Construct subset
253
254
255
256
257
258
259
260
        handle <- lgb.call(
          "LGBM_DatasetGetSubset_R"
          , ret = handle
          , 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
261

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

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

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

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

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

289
      }
James Lamb's avatar
James Lamb committed
290

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

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

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

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

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

Guolin Ke's avatar
Guolin Ke committed
307
      }
James Lamb's avatar
James Lamb committed
308

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

314
      return(invisible(self))
James Lamb's avatar
James Lamb committed
315

Guolin Ke's avatar
Guolin Ke committed
316
    },
James Lamb's avatar
James Lamb committed
317

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

321
      # Check for handle
Guolin Ke's avatar
Guolin Ke committed
322
      if (!lgb.is.null.handle(private$handle)) {
James Lamb's avatar
James Lamb committed
323

324
325
        num_row <- 0L
        num_col <- 0L
James Lamb's avatar
James Lamb committed
326

327
328
329
        # Get numeric data and numeric features
        c(lgb.call("LGBM_DatasetGetNumData_R", ret = num_row, private$handle),
          lgb.call("LGBM_DatasetGetNumFeature_R", ret = num_col, private$handle))
James Lamb's avatar
James Lamb committed
330
331
332

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

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

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

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

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

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

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

352
      # Check for handle
Guolin Ke's avatar
Guolin Ke committed
353
      if (!lgb.is.null.handle(private$handle)) {
James Lamb's avatar
James Lamb committed
354

355
        # Get feature names and write them
356
        cnames <- lgb.call.return.str("LGBM_DatasetGetFeatureNames_R", private$handle)
357
        private$colnames <- as.character(base::strsplit(cnames, "\t")[[1L]])
358
        private$colnames
James Lamb's avatar
James Lamb committed
359
360
361

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

413
      # Create known attributes list
414
      INFONAMES <- c("label", "weight", "init_score", "group")
James Lamb's avatar
James Lamb committed
415

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

421
      # Check for info name and handle
422
      if (is.null(private$info[[name]])) {
423

424
        if (lgb.is.null.handle(private$handle)) {
425
          stop("Cannot perform getinfo before constructing Dataset.")
426
        }
427

428
        # Get field size of info
429
        info_len <- 0L
430
431
432
433
434
435
        info_len <- lgb.call(
          "LGBM_DatasetGetFieldSize_R"
          , ret = info_len
          , private$handle
          , lgb.c_str(name)
        )
James Lamb's avatar
James Lamb committed
436

437
        # Check if info is not empty
438
        if (info_len > 0L) {
James Lamb's avatar
James Lamb committed
439

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

448
449
450
451
452
453
          ret <- lgb.call(
            "LGBM_DatasetGetField_R"
            , ret = ret
            , private$handle
            , lgb.c_str(name)
          )
James Lamb's avatar
James Lamb committed
454

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

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

460
      private$info[[name]]
James Lamb's avatar
James Lamb committed
461

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

464
    # Set information
Guolin Ke's avatar
Guolin Ke committed
465
    setinfo = function(name, info) {
James Lamb's avatar
James Lamb committed
466

467
      # Create known attributes list
468
      INFONAMES <- c("label", "weight", "init_score", "group")
James Lamb's avatar
James Lamb committed
469

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

475
476
477
478
479
480
      # 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
481

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

485
      if (!lgb.is.null.handle(private$handle) && !is.null(info)) {
James Lamb's avatar
James Lamb committed
486

487
        if (length(info) > 0L) {
James Lamb's avatar
James Lamb committed
488

489
490
491
492
493
494
495
496
          lgb.call(
            "LGBM_DatasetSetField_R"
            , ret = NULL
            , private$handle
            , lgb.c_str(name)
            , info
            , length(info)
          )
James Lamb's avatar
James Lamb committed
497

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

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

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

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

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

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

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

Guolin Ke's avatar
Guolin Ke committed
525
    },
James Lamb's avatar
James Lamb committed
526

527
    # Update parameters
528
    update_params = function(params) {
529
530
531
532
533
534
535
536
537
538
      if (length(params) == 0L) {
        return(invisible(self))
      }
      if (lgb.is.null.handle(private$handle)) {
        private$params <- modifyList(private$params, params)
      } else {
        call_state <- 0L
        call_state <- .Call(
          "LGBM_DatasetUpdateParamChecking_R"
          , lgb.params2str(private$params)
539
          , lgb.params2str(params)
540
541
          , call_state
          , PACKAGE = "lib_lightgbm"
542
        )
543
544
545
546
547
548
549
550
551
552
553
554
        call_state <- as.integer(call_state)
        if (call_state != 0L) {

          # raise error if raw data is freed
          if (is.null(private$raw_data)) {
            lgb.last_error()
          }

          # Overwrite paramms
          private$params <- modifyList(private$params, params)
          self$finalize()
        }
555
      }
556
      return(invisible(self))
James Lamb's avatar
James Lamb committed
557

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

560
561
562
563
564
565
566
567
568
569
570
    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)
    },

571
    # Set categorical feature parameter
572
    set_categorical_feature = function(categorical_feature) {
James Lamb's avatar
James Lamb committed
573

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

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

585
      # Overwrite categorical features
586
      private$categorical_feature <- categorical_feature
James Lamb's avatar
James Lamb committed
587

588
      # Finalize and return self
589
      self$finalize()
590
      return(invisible(self))
James Lamb's avatar
James Lamb committed
591

592
    },
James Lamb's avatar
James Lamb committed
593

594
    # Set reference
Guolin Ke's avatar
Guolin Ke committed
595
    set_reference = function(reference) {
James Lamb's avatar
James Lamb committed
596

597
      # Set known references
598
      self$set_categorical_feature(reference$.__enclos_env__$private$categorical_feature)
Guolin Ke's avatar
Guolin Ke committed
599
600
      self$set_colnames(reference$get_colnames())
      private$set_predictor(reference$.__enclos_env__$private$predictor)
James Lamb's avatar
James Lamb committed
601

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

607
      # Check for empty data
Guolin Ke's avatar
Guolin Ke committed
608
      if (is.null(private$raw_data)) {
James Lamb's avatar
James Lamb committed
609

610
611
        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
612

Guolin Ke's avatar
Guolin Ke committed
613
      }
James Lamb's avatar
James Lamb committed
614

615
      # Check for non-existing reference
Guolin Ke's avatar
Guolin Ke committed
616
      if (!is.null(reference)) {
James Lamb's avatar
James Lamb committed
617

618
        # Reference is unknown
Guolin Ke's avatar
Guolin Ke committed
619
        if (!lgb.check.r6.class(reference, "lgb.Dataset")) {
620
          stop("set_reference: Can only use lgb.Dataset as a reference")
Guolin Ke's avatar
Guolin Ke committed
621
        }
James Lamb's avatar
James Lamb committed
622

Guolin Ke's avatar
Guolin Ke committed
623
      }
James Lamb's avatar
James Lamb committed
624

625
      # Store reference
Guolin Ke's avatar
Guolin Ke committed
626
      private$reference <- reference
James Lamb's avatar
James Lamb committed
627

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

Guolin Ke's avatar
Guolin Ke committed
632
    },
James Lamb's avatar
James Lamb committed
633

634
    # Save binary model
Guolin Ke's avatar
Guolin Ke committed
635
    save_binary = function(fname) {
James Lamb's avatar
James Lamb committed
636

637
      # Store binary data
Guolin Ke's avatar
Guolin Ke committed
638
      self$construct()
639
640
641
642
643
644
      lgb.call(
        "LGBM_DatasetSaveBinary_R"
        , ret = NULL
        , private$handle
        , lgb.c_str(fname)
      )
645
      return(invisible(self))
Guolin Ke's avatar
Guolin Ke committed
646
    }
James Lamb's avatar
James Lamb committed
647

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

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

665
666
667
668
      # Get handle and construct if needed
      if (lgb.is.null.handle(private$handle)) {
        self$construct()
      }
669
      private$handle
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
    # Set predictor
Guolin Ke's avatar
Guolin Ke committed
674
    set_predictor = function(predictor) {
James Lamb's avatar
James Lamb committed
675

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

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

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

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

Guolin Ke's avatar
Guolin Ke committed
694
      }
James Lamb's avatar
James Lamb committed
695

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

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

Guolin Ke's avatar
Guolin Ke committed
703
    }
James Lamb's avatar
James Lamb committed
704

Guolin Ke's avatar
Guolin Ke committed
705
706
707
  )
)

708
709
710
#' @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
711
712
713
714
#' @param data a \code{matrix} object, a \code{dgCMatrix} object or a character representing a filename
#' @param params a list of parameters
#' @param reference reference dataset
#' @param colnames names of columns
715
#' @param categorical_feature categorical features
Guolin Ke's avatar
Guolin Ke committed
716
#' @param free_raw_data TRUE for need to free raw data after construct
Nikita Titov's avatar
Nikita Titov committed
717
#' @param info a list of information of the \code{lgb.Dataset} object
Guolin Ke's avatar
Guolin Ke committed
718
#' @param ... other information to pass to \code{info} or parameters pass to \code{params}
James Lamb's avatar
James Lamb committed
719
#'
Guolin Ke's avatar
Guolin Ke committed
720
#' @return constructed dataset
James Lamb's avatar
James Lamb committed
721
#'
Guolin Ke's avatar
Guolin Ke committed
722
#' @examples
723
#' \donttest{
724
725
726
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
727
728
729
#' data_file <- tempfile(fileext = ".data")
#' lgb.Dataset.save(dtrain, data_file)
#' dtrain <- lgb.Dataset(data_file)
730
#' lgb.Dataset.construct(dtrain)
731
#' }
Guolin Ke's avatar
Guolin Ke committed
732
733
#' @export
lgb.Dataset <- function(data,
734
735
736
                        params = list(),
                        reference = NULL,
                        colnames = NULL,
737
                        categorical_feature = NULL,
738
739
                        free_raw_data = TRUE,
                        info = list(),
Guolin Ke's avatar
Guolin Ke committed
740
                        ...) {
James Lamb's avatar
James Lamb committed
741

742
  # Create new dataset
743
744
745
746
747
748
749
750
751
752
753
754
  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
755

Guolin Ke's avatar
Guolin Ke committed
756
757
}

758
759
760
#' @name lgb.Dataset.create.valid
#' @title Construct validation data
#' @description Construct validation data according to training data
Guolin Ke's avatar
Guolin Ke committed
761
762
#' @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
763
#' @param info a list of information of the \code{lgb.Dataset} object
Guolin Ke's avatar
Guolin Ke committed
764
#' @param ... other information to pass to \code{info}.
James Lamb's avatar
James Lamb committed
765
#'
Guolin Ke's avatar
Guolin Ke committed
766
#' @return constructed dataset
James Lamb's avatar
James Lamb committed
767
#'
Guolin Ke's avatar
Guolin Ke committed
768
#' @examples
769
#' \donttest{
770
771
772
773
774
775
#' 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)
776
#' }
Guolin Ke's avatar
Guolin Ke committed
777
#' @export
778
lgb.Dataset.create.valid <- function(dataset, data, info = list(), ...) {
James Lamb's avatar
James Lamb committed
779

780
  # Check if dataset is not a dataset
781
782
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.create.valid: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
783
  }
James Lamb's avatar
James Lamb committed
784

785
  # Create validation dataset
786
  invisible(dataset$create_valid(data, info, ...))
James Lamb's avatar
James Lamb committed
787

788
}
Guolin Ke's avatar
Guolin Ke committed
789

790
791
792
#' @name lgb.Dataset.construct
#' @title Construct Dataset explicitly
#' @description Construct Dataset explicitly
Guolin Ke's avatar
Guolin Ke committed
793
#' @param dataset Object of class \code{lgb.Dataset}
James Lamb's avatar
James Lamb committed
794
#'
Guolin Ke's avatar
Guolin Ke committed
795
#' @examples
796
#' \donttest{
797
798
799
800
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
801
#' }
802
#' @return constructed dataset
Guolin Ke's avatar
Guolin Ke committed
803
804
#' @export
lgb.Dataset.construct <- function(dataset) {
James Lamb's avatar
James Lamb committed
805

806
  # Check if dataset is not a dataset
807
808
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.construct: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
809
  }
James Lamb's avatar
James Lamb committed
810

811
  # Construct the dataset
812
  invisible(dataset$construct())
James Lamb's avatar
James Lamb committed
813

Guolin Ke's avatar
Guolin Ke committed
814
815
}

816
817
#' @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
818
819
#' @param x Object of class \code{lgb.Dataset}
#' @param ... other parameters
James Lamb's avatar
James Lamb committed
820
#'
Guolin Ke's avatar
Guolin Ke committed
821
#' @return a vector of numbers of rows and of columns
James Lamb's avatar
James Lamb committed
822
#'
Guolin Ke's avatar
Guolin Ke committed
823
824
825
#' @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
826
#'
Guolin Ke's avatar
Guolin Ke committed
827
#' @examples
828
#' \donttest{
829
830
831
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
James Lamb's avatar
James Lamb committed
832
#'
833
834
835
#' stopifnot(nrow(dtrain) == nrow(train$data))
#' stopifnot(ncol(dtrain) == ncol(train$data))
#' stopifnot(all(dim(dtrain) == dim(train$data)))
836
#' }
Guolin Ke's avatar
Guolin Ke committed
837
838
839
#' @rdname dim
#' @export
dim.lgb.Dataset <- function(x, ...) {
James Lamb's avatar
James Lamb committed
840

841
  # Check if dataset is not a dataset
842
843
  if (!lgb.is.Dataset(x)) {
    stop("dim.lgb.Dataset: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
844
  }
James Lamb's avatar
James Lamb committed
845

846
  x$dim()
James Lamb's avatar
James Lamb committed
847

Guolin Ke's avatar
Guolin Ke committed
848
849
}

850
851
852
#' @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
853
854
#' @param x object of class \code{lgb.Dataset}
#' @param value a list of two elements: the first one is ignored
855
#'              and the second one is column names
Guolin Ke's avatar
Guolin Ke committed
856
857
858
859
860
861
#'
#' @details
#' Generic \code{dimnames} methods are used by \code{colnames}.
#' Since row names are irrelevant, it is recommended to use \code{colnames} directly.
#'
#' @examples
862
#' \donttest{
863
864
865
866
867
868
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
#' dimnames(dtrain)
#' colnames(dtrain)
869
#' colnames(dtrain) <- make.names(seq_len(ncol(train$data)))
870
#' print(dtrain, verbose = TRUE)
871
#' }
Guolin Ke's avatar
Guolin Ke committed
872
#' @rdname dimnames.lgb.Dataset
873
#' @return A list with the dimension names of the dataset
Guolin Ke's avatar
Guolin Ke committed
874
875
#' @export
dimnames.lgb.Dataset <- function(x) {
James Lamb's avatar
James Lamb committed
876

877
  # Check if dataset is not a dataset
878
879
  if (!lgb.is.Dataset(x)) {
    stop("dimnames.lgb.Dataset: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
880
  }
James Lamb's avatar
James Lamb committed
881

882
  # Return dimension names
883
  list(NULL, x$get_colnames())
James Lamb's avatar
James Lamb committed
884

Guolin Ke's avatar
Guolin Ke committed
885
886
887
}

#' @rdname dimnames.lgb.Dataset
888
#' @return A list with the dimension names of the dataset
Guolin Ke's avatar
Guolin Ke committed
889
890
#' @export
`dimnames<-.lgb.Dataset` <- function(x, value) {
James Lamb's avatar
James Lamb committed
891

892
  # Check if invalid element list
893
  if (!identical(class(value), "list") || length(value) != 2L) {
894
    stop("invalid ", sQuote("value"), " given: must be a list of two elements")
895
  }
James Lamb's avatar
James Lamb committed
896

897
898
899
900
  # Check for unknown row names
  if (!is.null(value[[1L]])) {
    stop("lgb.Dataset does not have rownames")
  }
James Lamb's avatar
James Lamb committed
901

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

Guolin Ke's avatar
Guolin Ke committed
904
905
    x$set_colnames(NULL)
    return(x)
James Lamb's avatar
James Lamb committed
906

907
  }
James Lamb's avatar
James Lamb committed
908

909
  # Check for unmatching column size
910
  if (ncol(x) != length(value[[2L]])) {
911
912
    stop(
      "can't assign "
913
      , sQuote(length(value[[2L]]))
914
915
916
917
      , " colnames to an lgb.Dataset with "
      , sQuote(ncol(x))
      , " columns"
    )
Guolin Ke's avatar
Guolin Ke committed
918
  }
James Lamb's avatar
James Lamb committed
919

920
  # Set column names properly, and return
921
  x$set_colnames(value[[2L]])
922
  x
James Lamb's avatar
James Lamb committed
923

Guolin Ke's avatar
Guolin Ke committed
924
925
}

926
927
928
#' @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
929
#' @param dataset Object of class \code{lgb.Dataset}
930
#' @param idxset an integer vector of indices of rows needed
Guolin Ke's avatar
Guolin Ke committed
931
932
#' @param ... other parameters (currently not used)
#' @return constructed sub dataset
James Lamb's avatar
James Lamb committed
933
#'
Guolin Ke's avatar
Guolin Ke committed
934
#' @examples
935
#' \donttest{
936
937
938
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
James Lamb's avatar
James Lamb committed
939
#'
940
#' dsub <- lightgbm::slice(dtrain, seq_len(42L))
941
#' lgb.Dataset.construct(dsub)
942
#' labels <- lightgbm::getinfo(dsub, "label")
943
#' }
Guolin Ke's avatar
Guolin Ke committed
944
#' @export
945
946
947
slice <- function(dataset, ...) {
  UseMethod("slice")
}
Guolin Ke's avatar
Guolin Ke committed
948
949

#' @rdname slice
950
#' @return constructed sub dataset
Guolin Ke's avatar
Guolin Ke committed
951
952
#' @export
slice.lgb.Dataset <- function(dataset, idxset, ...) {
James Lamb's avatar
James Lamb committed
953

954
  # Check if dataset is not a dataset
955
956
  if (!lgb.is.Dataset(dataset)) {
    stop("slice.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
957
  }
James Lamb's avatar
James Lamb committed
958

959
  # Return sliced set
960
  invisible(dataset$slice(idxset, ...))
James Lamb's avatar
James Lamb committed
961

Guolin Ke's avatar
Guolin Ke committed
962
963
}

964
965
966
#' @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
967
968
969
970
#' @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
971
#'
Guolin Ke's avatar
Guolin Ke committed
972
973
#' @details
#' The \code{name} field can be one of the following:
James Lamb's avatar
James Lamb committed
974
#'
Guolin Ke's avatar
Guolin Ke committed
975
976
977
#' \itemize{
#'     \item \code{label}: label lightgbm learn from ;
#'     \item \code{weight}: to do a weight rescale ;
Nikita Titov's avatar
Nikita Titov committed
978
979
#'     \item \code{group}: group size ;
#'     \item \code{init_score}: initial score is the base prediction lightgbm will boost from.
Guolin Ke's avatar
Guolin Ke committed
980
#' }
James Lamb's avatar
James Lamb committed
981
#'
Guolin Ke's avatar
Guolin Ke committed
982
#' @examples
983
#' \donttest{
984
985
986
987
#' 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
988
#'
989
990
#' labels <- lightgbm::getinfo(dtrain, "label")
#' lightgbm::setinfo(dtrain, "label", 1 - labels)
James Lamb's avatar
James Lamb committed
991
#'
992
993
#' labels2 <- lightgbm::getinfo(dtrain, "label")
#' stopifnot(all(labels2 == 1 - labels))
994
#' }
Guolin Ke's avatar
Guolin Ke committed
995
#' @export
996
997
998
getinfo <- function(dataset, ...) {
  UseMethod("getinfo")
}
Guolin Ke's avatar
Guolin Ke committed
999
1000

#' @rdname getinfo
1001
#' @return info data
Guolin Ke's avatar
Guolin Ke committed
1002
1003
#' @export
getinfo.lgb.Dataset <- function(dataset, name, ...) {
James Lamb's avatar
James Lamb committed
1004

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

1010
  dataset$getinfo(name)
James Lamb's avatar
James Lamb committed
1011

Guolin Ke's avatar
Guolin Ke committed
1012
1013
}

1014
1015
1016
#' @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
1017
#' @param dataset Object of class \code{lgb.Dataset}
Guolin Ke's avatar
Guolin Ke committed
1018
1019
1020
#' @param name the name of the field to get
#' @param info the specific field of information to set
#' @param ... other parameters
1021
#' @return the dataset you passed in
James Lamb's avatar
James Lamb committed
1022
#'
Guolin Ke's avatar
Guolin Ke committed
1023
1024
#' @details
#' The \code{name} field can be one of the following:
James Lamb's avatar
James Lamb committed
1025
#'
Guolin Ke's avatar
Guolin Ke committed
1026
#' \itemize{
1027
1028
1029
1030
1031
1032
1033
#'     \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.
#'         For example, if you have a 1000-row dataset that contains 250 4-document query results,
#'         set this to \code{rep(4L, 250L)}}
Guolin Ke's avatar
Guolin Ke committed
1034
#' }
James Lamb's avatar
James Lamb committed
1035
#'
Guolin Ke's avatar
Guolin Ke committed
1036
#' @examples
1037
#' \donttest{
1038
1039
1040
1041
#' 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
1042
#'
1043
1044
#' labels <- lightgbm::getinfo(dtrain, "label")
#' lightgbm::setinfo(dtrain, "label", 1 - labels)
James Lamb's avatar
James Lamb committed
1045
#'
1046
1047
#' labels2 <- lightgbm::getinfo(dtrain, "label")
#' stopifnot(all.equal(labels2, 1 - labels))
1048
#' }
Guolin Ke's avatar
Guolin Ke committed
1049
#' @export
1050
1051
1052
setinfo <- function(dataset, ...) {
  UseMethod("setinfo")
}
Guolin Ke's avatar
Guolin Ke committed
1053
1054

#' @rdname setinfo
1055
#' @return the dataset you passed in
Guolin Ke's avatar
Guolin Ke committed
1056
1057
#' @export
setinfo.lgb.Dataset <- function(dataset, name, info, ...) {
James Lamb's avatar
James Lamb committed
1058

1059
1060
  if (!lgb.is.Dataset(dataset)) {
    stop("setinfo.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1061
  }
James Lamb's avatar
James Lamb committed
1062

1063
  # Set information
1064
  invisible(dataset$setinfo(name, info))
Guolin Ke's avatar
Guolin Ke committed
1065
1066
}

1067
1068
1069
1070
#' @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.
1071
#' @param dataset object of class \code{lgb.Dataset}
1072
1073
1074
#' @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").
1075
#' @return the dataset you passed in
James Lamb's avatar
James Lamb committed
1076
#'
1077
#' @examples
1078
#' \donttest{
1079
1080
1081
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
1082
1083
1084
#' data_file <- tempfile(fileext = ".data")
#' lgb.Dataset.save(dtrain, data_file)
#' dtrain <- lgb.Dataset(data_file)
1085
#' lgb.Dataset.set.categorical(dtrain, 1L:2L)
1086
#' }
1087
1088
1089
#' @rdname lgb.Dataset.set.categorical
#' @export
lgb.Dataset.set.categorical <- function(dataset, categorical_feature) {
James Lamb's avatar
James Lamb committed
1090

1091
1092
1093
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.set.categorical: input dataset should be an lgb.Dataset object")
  }
James Lamb's avatar
James Lamb committed
1094

1095
  # Set categoricals
1096
  invisible(dataset$set_categorical_feature(categorical_feature))
James Lamb's avatar
James Lamb committed
1097

1098
1099
}

1100
1101
1102
#' @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
1103
1104
#' @param dataset object of class \code{lgb.Dataset}
#' @param reference object of class \code{lgb.Dataset}
James Lamb's avatar
James Lamb committed
1105
#'
1106
#' @return the dataset you passed in
James Lamb's avatar
James Lamb committed
1107
#'
Guolin Ke's avatar
Guolin Ke committed
1108
#' @examples
1109
#' \donttest{
1110
1111
1112
1113
1114
1115
1116
#' 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)
1117
#' }
Guolin Ke's avatar
Guolin Ke committed
1118
1119
1120
#' @rdname lgb.Dataset.set.reference
#' @export
lgb.Dataset.set.reference <- function(dataset, reference) {
James Lamb's avatar
James Lamb committed
1121

1122
  # Check if dataset is not a dataset
1123
1124
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.set.reference: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1125
  }
James Lamb's avatar
James Lamb committed
1126

1127
  # Set reference
1128
  invisible(dataset$set_reference(reference))
Guolin Ke's avatar
Guolin Ke committed
1129
1130
}

1131
1132
1133
1134
#' @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
1135
1136
#' @param dataset object of class \code{lgb.Dataset}
#' @param fname object filename of output file
James Lamb's avatar
James Lamb committed
1137
#'
1138
#' @return the dataset you passed in
James Lamb's avatar
James Lamb committed
1139
#'
Guolin Ke's avatar
Guolin Ke committed
1140
#' @examples
1141
#' \donttest{
1142
1143
1144
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
1145
#' lgb.Dataset.save(dtrain, tempfile(fileext = ".bin"))
1146
#' }
Guolin Ke's avatar
Guolin Ke committed
1147
1148
#' @export
lgb.Dataset.save <- function(dataset, fname) {
James Lamb's avatar
James Lamb committed
1149

1150
  # Check if dataset is not a dataset
1151
1152
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.set: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1153
  }
James Lamb's avatar
James Lamb committed
1154

1155
  # File-type is not matching
1156
1157
  if (!is.character(fname)) {
    stop("lgb.Dataset.set: fname should be a character or a file connection")
Guolin Ke's avatar
Guolin Ke committed
1158
  }
James Lamb's avatar
James Lamb committed
1159

1160
  # Store binary
1161
  invisible(dataset$save_binary(fname))
Guolin Ke's avatar
Guolin Ke committed
1162
}