lgb.Dataset.R 32.1 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
#' \dontrun{
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
#' \dontrun{
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
#' \dontrun{
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
#' }
Guolin Ke's avatar
Guolin Ke committed
802
803
#' @export
lgb.Dataset.construct <- function(dataset) {
James Lamb's avatar
James Lamb committed
804

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

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

Guolin Ke's avatar
Guolin Ke committed
813
814
}

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

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

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

Guolin Ke's avatar
Guolin Ke committed
847
848
}

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

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

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

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

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

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

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

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

Guolin Ke's avatar
Guolin Ke committed
901
902
    x$set_colnames(NULL)
    return(x)
James Lamb's avatar
James Lamb committed
903

904
  }
James Lamb's avatar
James Lamb committed
905

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

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

Guolin Ke's avatar
Guolin Ke committed
921
922
}

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

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

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

955
  # Return sliced set
956
  invisible(dataset$slice(idxset, ...))
James Lamb's avatar
James Lamb committed
957

Guolin Ke's avatar
Guolin Ke committed
958
959
}

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

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

1000
  # Check if dataset is not a dataset
1001
1002
  if (!lgb.is.Dataset(dataset)) {
    stop("getinfo.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1003
  }
James Lamb's avatar
James Lamb committed
1004

1005
  dataset$getinfo(name)
James Lamb's avatar
James Lamb committed
1006

Guolin Ke's avatar
Guolin Ke committed
1007
1008
}

1009
1010
1011
#' @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
1012
#' @param dataset Object of class \code{lgb.Dataset}
Guolin Ke's avatar
Guolin Ke committed
1013
1014
1015
1016
#' @param name the name of the field to get
#' @param info the specific field of information to set
#' @param ... other parameters
#' @return passed object
James Lamb's avatar
James Lamb committed
1017
#'
Guolin Ke's avatar
Guolin Ke committed
1018
1019
#' @details
#' The \code{name} field can be one of the following:
James Lamb's avatar
James Lamb committed
1020
#'
Guolin Ke's avatar
Guolin Ke committed
1021
#' \itemize{
1022
1023
1024
1025
1026
1027
1028
#'     \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
1029
#' }
James Lamb's avatar
James Lamb committed
1030
#'
Guolin Ke's avatar
Guolin Ke committed
1031
#' @examples
1032
#' \dontrun{
1033
1034
1035
1036
#' 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
1037
#'
1038
1039
#' labels <- lightgbm::getinfo(dtrain, "label")
#' lightgbm::setinfo(dtrain, "label", 1 - labels)
James Lamb's avatar
James Lamb committed
1040
#'
1041
1042
#' labels2 <- lightgbm::getinfo(dtrain, "label")
#' stopifnot(all.equal(labels2, 1 - labels))
1043
#' }
Guolin Ke's avatar
Guolin Ke committed
1044
#' @export
1045
1046
1047
setinfo <- function(dataset, ...) {
  UseMethod("setinfo")
}
Guolin Ke's avatar
Guolin Ke committed
1048
1049
1050
1051

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

1053
1054
  if (!lgb.is.Dataset(dataset)) {
    stop("setinfo.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1055
  }
James Lamb's avatar
James Lamb committed
1056

1057
  # Set information
1058
  invisible(dataset$setinfo(name, info))
Guolin Ke's avatar
Guolin Ke committed
1059
1060
}

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

1085
1086
1087
  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
1088

1089
  # Set categoricals
1090
  invisible(dataset$set_categorical_feature(categorical_feature))
James Lamb's avatar
James Lamb committed
1091

1092
1093
}

1094
1095
1096
#' @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
1097
1098
#' @param dataset object of class \code{lgb.Dataset}
#' @param reference object of class \code{lgb.Dataset}
James Lamb's avatar
James Lamb committed
1099
#'
Guolin Ke's avatar
Guolin Ke committed
1100
#' @return passed dataset
James Lamb's avatar
James Lamb committed
1101
#'
Guolin Ke's avatar
Guolin Ke committed
1102
#' @examples
1103
#' \dontrun{
1104
1105
1106
1107
1108
1109
1110
#' 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)
1111
#' }
Guolin Ke's avatar
Guolin Ke committed
1112
1113
1114
#' @rdname lgb.Dataset.set.reference
#' @export
lgb.Dataset.set.reference <- function(dataset, reference) {
James Lamb's avatar
James Lamb committed
1115

1116
  # Check if dataset is not a dataset
1117
1118
  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
1119
  }
James Lamb's avatar
James Lamb committed
1120

1121
  # Set reference
1122
  invisible(dataset$set_reference(reference))
Guolin Ke's avatar
Guolin Ke committed
1123
1124
}

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

1144
  # Check if dataset is not a dataset
1145
1146
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.set: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1147
  }
James Lamb's avatar
James Lamb committed
1148

1149
  # File-type is not matching
1150
1151
  if (!is.character(fname)) {
    stop("lgb.Dataset.set: fname should be a character or a file connection")
Guolin Ke's avatar
Guolin Ke committed
1152
  }
James Lamb's avatar
James Lamb committed
1153

1154
  # Store binary
1155
  invisible(dataset$save_binary(fname))
Guolin Ke's avatar
Guolin Ke committed
1156
}