lgb.Dataset.R 31.6 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
      # Check for additional parameters
36
      additional_params <- list(...)
James Lamb's avatar
James Lamb committed
37

38
39
      # Create known attributes list
      INFO_KEYS <- c("label", "weight", "init_score", "group")
James Lamb's avatar
James Lamb committed
40

41
      # Check if attribute key is in the known attribute list
42
      for (key in names(additional_params)) {
James Lamb's avatar
James Lamb committed
43

44
        # Key existing
45
        if (key %in% INFO_KEYS) {
James Lamb's avatar
James Lamb committed
46

47
          # Store as info
48
          info[[key]] <- additional_params[[key]]
James Lamb's avatar
James Lamb committed
49

Guolin Ke's avatar
Guolin Ke committed
50
        } else {
James Lamb's avatar
James Lamb committed
51

52
          # Store as param
53
          params[[key]] <- additional_params[[key]]
James Lamb's avatar
James Lamb committed
54

Guolin Ke's avatar
Guolin Ke committed
55
        }
James Lamb's avatar
James Lamb committed
56

Guolin Ke's avatar
Guolin Ke committed
57
      }
James Lamb's avatar
James Lamb committed
58

59
      # Check for dataset reference
Guolin Ke's avatar
Guolin Ke committed
60
61
      if (!is.null(reference)) {
        if (!lgb.check.r6.class(reference, "lgb.Dataset")) {
62
          stop("lgb.Dataset: Can only use ", sQuote("lgb.Dataset"), " as reference")
Guolin Ke's avatar
Guolin Ke committed
63
64
        }
      }
James Lamb's avatar
James Lamb committed
65

66
      # Check for predictor reference
Guolin Ke's avatar
Guolin Ke committed
67
68
      if (!is.null(predictor)) {
        if (!lgb.check.r6.class(predictor, "lgb.Predictor")) {
69
          stop("lgb.Dataset: Only can use ", sQuote("lgb.Predictor"), " as predictor")
Guolin Ke's avatar
Guolin Ke committed
70
71
        }
      }
James Lamb's avatar
James Lamb committed
72

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

170
          }
James Lamb's avatar
James Lamb committed
171

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

175
      }
James Lamb's avatar
James Lamb committed
176

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

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

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

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

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

203
204
205
206
207
208
209
          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
210

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

213
          # Are we using a matrix?
214
215
216
217
218
219
220
221
222
          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
223
224

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

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

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

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

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

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

259
        # Construct subset
260
261
262
263
264
265
266
267
        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
268

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

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

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

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

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

296
      }
James Lamb's avatar
James Lamb committed
297

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

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

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

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

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

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

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

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

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

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

329
      # Check for handle
Guolin Ke's avatar
Guolin Ke committed
330
      if (!lgb.is.null.handle(private$handle)) {
James Lamb's avatar
James Lamb committed
331

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

335
336
337
        # 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
338
339
340

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

341
        # Check if dgCMatrix (sparse matrix column compressed)
342
        # NOTE: requires Matrix package
343
        dim(private$raw_data)
James Lamb's avatar
James Lamb committed
344

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

347
        # Trying to work with unknown dimensions is not possible
348
349
350
351
        stop(
          "dim: cannot get dimensions before dataset has been constructed, "
          , "please call lgb.Dataset.construct explicitly"
        )
James Lamb's avatar
James Lamb committed
352

Guolin Ke's avatar
Guolin Ke committed
353
      }
James Lamb's avatar
James Lamb committed
354

Guolin Ke's avatar
Guolin Ke committed
355
    },
James Lamb's avatar
James Lamb committed
356

357
    # Get column names
Guolin Ke's avatar
Guolin Ke committed
358
    get_colnames = function() {
James Lamb's avatar
James Lamb committed
359

360
      # Check for handle
Guolin Ke's avatar
Guolin Ke committed
361
      if (!lgb.is.null.handle(private$handle)) {
James Lamb's avatar
James Lamb committed
362

363
        # Get feature names and write them
364
        cnames <- lgb.call.return.str("LGBM_DatasetGetFeatureNames_R", private$handle)
365
        private$colnames <- as.character(base::strsplit(cnames, "\t")[[1L]])
366
        private$colnames
James Lamb's avatar
James Lamb committed
367
368
369

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

370
        # Check if dgCMatrix (sparse matrix column compressed)
371
        colnames(private$raw_data)
James Lamb's avatar
James Lamb committed
372

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

375
        # Trying to work with unknown dimensions is not possible
376
377
378
379
        stop(
          "dim: cannot get dimensions before dataset has been constructed, please call "
          , "lgb.Dataset.construct explicitly"
        )
James Lamb's avatar
James Lamb committed
380

Guolin Ke's avatar
Guolin Ke committed
381
      }
James Lamb's avatar
James Lamb committed
382

Guolin Ke's avatar
Guolin Ke committed
383
    },
James Lamb's avatar
James Lamb committed
384

385
    # Set column names
Guolin Ke's avatar
Guolin Ke committed
386
    set_colnames = function(colnames) {
James Lamb's avatar
James Lamb committed
387

388
389
      # Check column names non-existence
      if (is.null(colnames)) {
390
        return(invisible(self))
391
      }
James Lamb's avatar
James Lamb committed
392

393
      # Check empty column names
Guolin Ke's avatar
Guolin Ke committed
394
      colnames <- as.character(colnames)
395
      if (length(colnames) == 0L) {
396
        return(invisible(self))
397
      }
James Lamb's avatar
James Lamb committed
398

399
      # Write column names
Guolin Ke's avatar
Guolin Ke committed
400
401
      private$colnames <- colnames
      if (!lgb.is.null.handle(private$handle)) {
James Lamb's avatar
James Lamb committed
402

403
        # Merge names with tab separation
Guolin Ke's avatar
Guolin Ke committed
404
        merged_name <- paste0(as.list(private$colnames), collapse = "\t")
405
406
407
408
409
410
        lgb.call(
          "LGBM_DatasetSetFeatureNames_R"
          , ret = NULL
          , private$handle
          , lgb.c_str(merged_name)
        )
James Lamb's avatar
James Lamb committed
411

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

414
      # Return self
415
      return(invisible(self))
James Lamb's avatar
James Lamb committed
416

Guolin Ke's avatar
Guolin Ke committed
417
    },
James Lamb's avatar
James Lamb committed
418

419
    # Get information
Guolin Ke's avatar
Guolin Ke committed
420
    getinfo = function(name) {
James Lamb's avatar
James Lamb committed
421

422
      # Create known attributes list
423
      INFONAMES <- c("label", "weight", "init_score", "group")
James Lamb's avatar
James Lamb committed
424

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

430
      # Check for info name and handle
431
      if (is.null(private$info[[name]])) {
432

433
        if (lgb.is.null.handle(private$handle)) {
434
          stop("Cannot perform getinfo before constructing Dataset.")
435
        }
436

437
        # Get field size of info
438
        info_len <- 0L
439
440
441
442
443
444
        info_len <- lgb.call(
          "LGBM_DatasetGetFieldSize_R"
          , ret = info_len
          , private$handle
          , lgb.c_str(name)
        )
James Lamb's avatar
James Lamb committed
445

446
        # Check if info is not empty
447
        if (info_len > 0L) {
James Lamb's avatar
James Lamb committed
448

449
          # Get back fields
Guolin Ke's avatar
Guolin Ke committed
450
          ret <- NULL
451
452
453
454
455
          ret <- if (name == "group") {
            integer(info_len) # Integer
          } else {
            numeric(info_len) # Numeric
          }
James Lamb's avatar
James Lamb committed
456

457
458
459
460
461
462
          ret <- lgb.call(
            "LGBM_DatasetGetField_R"
            , ret = ret
            , private$handle
            , lgb.c_str(name)
          )
James Lamb's avatar
James Lamb committed
463

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

Guolin Ke's avatar
Guolin Ke committed
466
467
        }
      }
James Lamb's avatar
James Lamb committed
468

469
      private$info[[name]]
James Lamb's avatar
James Lamb committed
470

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

473
    # Set information
Guolin Ke's avatar
Guolin Ke committed
474
    setinfo = function(name, info) {
James Lamb's avatar
James Lamb committed
475

476
      # Create known attributes list
477
      INFONAMES <- c("label", "weight", "init_score", "group")
James Lamb's avatar
James Lamb committed
478

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

484
485
486
487
488
489
      # 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
490

491
      # Store information privately
Guolin Ke's avatar
Guolin Ke committed
492
      private$info[[name]] <- info
James Lamb's avatar
James Lamb committed
493

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

496
        if (length(info) > 0L) {
James Lamb's avatar
James Lamb committed
497

498
499
500
501
502
503
504
505
          lgb.call(
            "LGBM_DatasetSetField_R"
            , ret = NULL
            , private$handle
            , lgb.c_str(name)
            , info
            , length(info)
          )
James Lamb's avatar
James Lamb committed
506

507
508
          private$version <- private$version + 1L

Guolin Ke's avatar
Guolin Ke committed
509
        }
James Lamb's avatar
James Lamb committed
510

Guolin Ke's avatar
Guolin Ke committed
511
      }
James Lamb's avatar
James Lamb committed
512

513
      # Return self
514
      return(invisible(self))
James Lamb's avatar
James Lamb committed
515

Guolin Ke's avatar
Guolin Ke committed
516
    },
James Lamb's avatar
James Lamb committed
517

518
    # Slice dataset
Guolin Ke's avatar
Guolin Ke committed
519
    slice = function(idxset, ...) {
James Lamb's avatar
James Lamb committed
520

521
      # Perform slicing
522
523
524
525
526
527
528
529
530
531
532
533
      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
534

Guolin Ke's avatar
Guolin Ke committed
535
    },
James Lamb's avatar
James Lamb committed
536

537
    # Update parameters
538
    update_params = function(params) {
James Lamb's avatar
James Lamb committed
539

540
      # Parameter updating
541
      if (!lgb.is.null.handle(private$handle)) {
542
543
544
545
546
547
        lgb.call(
          "LGBM_DatasetUpdateParam_R"
          , ret = NULL
          , private$handle
          , lgb.params2str(params)
        )
548
549
        return(invisible(self))
      }
Guolin Ke's avatar
Guolin Ke committed
550
      private$params <- modifyList(private$params, params)
551
      return(invisible(self))
James Lamb's avatar
James Lamb committed
552

Guolin Ke's avatar
Guolin Ke committed
553
    },
James Lamb's avatar
James Lamb committed
554

555
    # Set categorical feature parameter
556
    set_categorical_feature = function(categorical_feature) {
James Lamb's avatar
James Lamb committed
557

558
559
      # Check for identical input
      if (identical(private$categorical_feature, categorical_feature)) {
560
        return(invisible(self))
561
      }
James Lamb's avatar
James Lamb committed
562

563
      # Check for empty data
564
      if (is.null(private$raw_data)) {
565
566
        stop("set_categorical_feature: cannot set categorical feature after freeing raw data,
          please set ", sQuote("free_raw_data = FALSE"), " when you construct lgb.Dataset")
567
      }
James Lamb's avatar
James Lamb committed
568

569
      # Overwrite categorical features
570
      private$categorical_feature <- categorical_feature
James Lamb's avatar
James Lamb committed
571

572
      # Finalize and return self
573
      self$finalize()
574
      return(invisible(self))
James Lamb's avatar
James Lamb committed
575

576
    },
James Lamb's avatar
James Lamb committed
577

578
    # Set reference
Guolin Ke's avatar
Guolin Ke committed
579
    set_reference = function(reference) {
James Lamb's avatar
James Lamb committed
580

581
      # Set known references
582
      self$set_categorical_feature(reference$.__enclos_env__$private$categorical_feature)
Guolin Ke's avatar
Guolin Ke committed
583
584
      self$set_colnames(reference$get_colnames())
      private$set_predictor(reference$.__enclos_env__$private$predictor)
James Lamb's avatar
James Lamb committed
585

586
587
      # Check for identical references
      if (identical(private$reference, reference)) {
588
        return(invisible(self))
589
      }
James Lamb's avatar
James Lamb committed
590

591
      # Check for empty data
Guolin Ke's avatar
Guolin Ke committed
592
      if (is.null(private$raw_data)) {
James Lamb's avatar
James Lamb committed
593

594
595
        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
596

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

599
      # Check for non-existing reference
Guolin Ke's avatar
Guolin Ke committed
600
      if (!is.null(reference)) {
James Lamb's avatar
James Lamb committed
601

602
        # Reference is unknown
Guolin Ke's avatar
Guolin Ke committed
603
        if (!lgb.check.r6.class(reference, "lgb.Dataset")) {
604
          stop("set_reference: Can only use lgb.Dataset as a reference")
Guolin Ke's avatar
Guolin Ke committed
605
        }
James Lamb's avatar
James Lamb committed
606

Guolin Ke's avatar
Guolin Ke committed
607
      }
James Lamb's avatar
James Lamb committed
608

609
      # Store reference
Guolin Ke's avatar
Guolin Ke committed
610
      private$reference <- reference
James Lamb's avatar
James Lamb committed
611

612
      # Finalize and return self
Guolin Ke's avatar
Guolin Ke committed
613
      self$finalize()
614
      return(invisible(self))
James Lamb's avatar
James Lamb committed
615

Guolin Ke's avatar
Guolin Ke committed
616
    },
James Lamb's avatar
James Lamb committed
617

618
    # Save binary model
Guolin Ke's avatar
Guolin Ke committed
619
    save_binary = function(fname) {
James Lamb's avatar
James Lamb committed
620

621
      # Store binary data
Guolin Ke's avatar
Guolin Ke committed
622
      self$construct()
623
624
625
626
627
628
      lgb.call(
        "LGBM_DatasetSaveBinary_R"
        , ret = NULL
        , private$handle
        , lgb.c_str(fname)
      )
629
      return(invisible(self))
Guolin Ke's avatar
Guolin Ke committed
630
    }
James Lamb's avatar
James Lamb committed
631

Guolin Ke's avatar
Guolin Ke committed
632
633
  ),
  private = list(
634
635
636
637
638
    handle = NULL,
    raw_data = NULL,
    params = list(),
    reference = NULL,
    colnames = NULL,
639
    categorical_feature = NULL,
640
641
642
643
    predictor = NULL,
    free_raw_data = TRUE,
    used_indices = NULL,
    info = NULL,
644
    version = 0L,
James Lamb's avatar
James Lamb committed
645

646
647
    # Get handle
    get_handle = function() {
James Lamb's avatar
James Lamb committed
648

649
650
651
652
      # Get handle and construct if needed
      if (lgb.is.null.handle(private$handle)) {
        self$construct()
      }
653
      private$handle
James Lamb's avatar
James Lamb committed
654

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

657
    # Set predictor
Guolin Ke's avatar
Guolin Ke committed
658
    set_predictor = function(predictor) {
James Lamb's avatar
James Lamb committed
659

660
661
      # Return self is identical predictor
      if (identical(private$predictor, predictor)) {
662
        return(invisible(self))
663
      }
James Lamb's avatar
James Lamb committed
664

665
      # Check for empty data
Guolin Ke's avatar
Guolin Ke committed
666
      if (is.null(private$raw_data)) {
667
668
        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
669
      }
James Lamb's avatar
James Lamb committed
670

671
      # Check for empty predictor
Guolin Ke's avatar
Guolin Ke committed
672
      if (!is.null(predictor)) {
James Lamb's avatar
James Lamb committed
673

674
        # Predictor is unknown
Guolin Ke's avatar
Guolin Ke committed
675
        if (!lgb.check.r6.class(predictor, "lgb.Predictor")) {
676
          stop("set_predictor: Can only use lgb.Predictor as predictor")
Guolin Ke's avatar
Guolin Ke committed
677
        }
James Lamb's avatar
James Lamb committed
678

Guolin Ke's avatar
Guolin Ke committed
679
      }
James Lamb's avatar
James Lamb committed
680

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

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

Guolin Ke's avatar
Guolin Ke committed
688
    }
James Lamb's avatar
James Lamb committed
689

Guolin Ke's avatar
Guolin Ke committed
690
691
692
  )
)

693
694
695
#' @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
696
697
698
699
#' @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
700
#' @param categorical_feature categorical features
Guolin Ke's avatar
Guolin Ke committed
701
#' @param free_raw_data TRUE for need to free raw data after construct
Nikita Titov's avatar
Nikita Titov committed
702
#' @param info a list of information of the \code{lgb.Dataset} object
Guolin Ke's avatar
Guolin Ke committed
703
#' @param ... other information to pass to \code{info} or parameters pass to \code{params}
James Lamb's avatar
James Lamb committed
704
#'
Guolin Ke's avatar
Guolin Ke committed
705
#' @return constructed dataset
James Lamb's avatar
James Lamb committed
706
#'
Guolin Ke's avatar
Guolin Ke committed
707
#' @examples
708
709
710
711
712
713
714
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.save(dtrain, "lgb.Dataset.data")
#' dtrain <- lgb.Dataset("lgb.Dataset.data")
#' lgb.Dataset.construct(dtrain)
James Lamb's avatar
James Lamb committed
715
#'
Guolin Ke's avatar
Guolin Ke committed
716
717
#' @export
lgb.Dataset <- function(data,
718
719
720
                        params = list(),
                        reference = NULL,
                        colnames = NULL,
721
                        categorical_feature = NULL,
722
723
                        free_raw_data = TRUE,
                        info = list(),
Guolin Ke's avatar
Guolin Ke committed
724
                        ...) {
James Lamb's avatar
James Lamb committed
725

726
  # Create new dataset
727
728
729
730
731
732
733
734
735
736
737
738
  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
739

Guolin Ke's avatar
Guolin Ke committed
740
741
}

742
743
744
#' @name lgb.Dataset.create.valid
#' @title Construct validation data
#' @description Construct validation data according to training data
Guolin Ke's avatar
Guolin Ke committed
745
746
#' @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
747
#' @param info a list of information of the \code{lgb.Dataset} object
Guolin Ke's avatar
Guolin Ke committed
748
#' @param ... other information to pass to \code{info}.
James Lamb's avatar
James Lamb committed
749
#'
Guolin Ke's avatar
Guolin Ke committed
750
#' @return constructed dataset
James Lamb's avatar
James Lamb committed
751
#'
Guolin Ke's avatar
Guolin Ke committed
752
#' @examples
753
754
755
756
757
758
759
#' library(lightgbm)
#' 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)
James Lamb's avatar
James Lamb committed
760
#'
Guolin Ke's avatar
Guolin Ke committed
761
#' @export
762
lgb.Dataset.create.valid <- function(dataset, data, info = list(), ...) {
James Lamb's avatar
James Lamb committed
763

764
  # Check if dataset is not a dataset
765
766
  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
767
  }
James Lamb's avatar
James Lamb committed
768

769
  # Create validation dataset
770
  invisible(dataset$create_valid(data, info, ...))
James Lamb's avatar
James Lamb committed
771

772
}
Guolin Ke's avatar
Guolin Ke committed
773

774
775
776
#' @name lgb.Dataset.construct
#' @title Construct Dataset explicitly
#' @description Construct Dataset explicitly
Guolin Ke's avatar
Guolin Ke committed
777
#' @param dataset Object of class \code{lgb.Dataset}
James Lamb's avatar
James Lamb committed
778
#'
Guolin Ke's avatar
Guolin Ke committed
779
#' @examples
780
781
782
783
784
#' library(lightgbm)
#' 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
785
#'
Guolin Ke's avatar
Guolin Ke committed
786
787
#' @export
lgb.Dataset.construct <- function(dataset) {
James Lamb's avatar
James Lamb committed
788

789
  # Check if dataset is not a dataset
790
791
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.construct: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
792
  }
James Lamb's avatar
James Lamb committed
793

794
  # Construct the dataset
795
  invisible(dataset$construct())
James Lamb's avatar
James Lamb committed
796

Guolin Ke's avatar
Guolin Ke committed
797
798
}

799
800
#' @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
801
802
#' @param x Object of class \code{lgb.Dataset}
#' @param ... other parameters
James Lamb's avatar
James Lamb committed
803
#'
Guolin Ke's avatar
Guolin Ke committed
804
#' @return a vector of numbers of rows and of columns
James Lamb's avatar
James Lamb committed
805
#'
Guolin Ke's avatar
Guolin Ke committed
806
807
808
#' @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
809
#'
Guolin Ke's avatar
Guolin Ke committed
810
#' @examples
811
812
813
814
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
James Lamb's avatar
James Lamb committed
815
#'
816
817
818
#' stopifnot(nrow(dtrain) == nrow(train$data))
#' stopifnot(ncol(dtrain) == ncol(train$data))
#' stopifnot(all(dim(dtrain) == dim(train$data)))
James Lamb's avatar
James Lamb committed
819
#'
Guolin Ke's avatar
Guolin Ke committed
820
821
822
#' @rdname dim
#' @export
dim.lgb.Dataset <- function(x, ...) {
James Lamb's avatar
James Lamb committed
823

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

829
  # Return dimensions
830
  x$dim()
James Lamb's avatar
James Lamb committed
831

Guolin Ke's avatar
Guolin Ke committed
832
833
}

834
835
836
#' @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
837
838
#' @param x object of class \code{lgb.Dataset}
#' @param value a list of two elements: the first one is ignored
839
#'              and the second one is column names
Guolin Ke's avatar
Guolin Ke committed
840
841
842
843
844
845
#'
#' @details
#' Generic \code{dimnames} methods are used by \code{colnames}.
#' Since row names are irrelevant, it is recommended to use \code{colnames} directly.
#'
#' @examples
846
847
848
849
850
851
852
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
#' dimnames(dtrain)
#' colnames(dtrain)
853
#' colnames(dtrain) <- make.names(seq_len(ncol(train$data)))
854
#' print(dtrain, verbose = TRUE)
James Lamb's avatar
James Lamb committed
855
#'
Guolin Ke's avatar
Guolin Ke committed
856
857
858
#' @rdname dimnames.lgb.Dataset
#' @export
dimnames.lgb.Dataset <- function(x) {
James Lamb's avatar
James Lamb committed
859

860
  # Check if dataset is not a dataset
861
862
  if (!lgb.is.Dataset(x)) {
    stop("dimnames.lgb.Dataset: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
863
  }
James Lamb's avatar
James Lamb committed
864

865
  # Return dimension names
866
  list(NULL, x$get_colnames())
James Lamb's avatar
James Lamb committed
867

Guolin Ke's avatar
Guolin Ke committed
868
869
870
871
872
}

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

874
875
  # Check if invalid element list
  if (!is.list(value) || length(value) != 2L) {
876
    stop("invalid ", sQuote("value"), " given: must be a list of two elements")
877
  }
James Lamb's avatar
James Lamb committed
878

879
880
881
882
  # Check for unknown row names
  if (!is.null(value[[1L]])) {
    stop("lgb.Dataset does not have rownames")
  }
James Lamb's avatar
James Lamb committed
883

884
  # Check for second value missing
885
  if (is.null(value[[2L]])) {
James Lamb's avatar
James Lamb committed
886

887
    # No column names
Guolin Ke's avatar
Guolin Ke committed
888
889
    x$set_colnames(NULL)
    return(x)
James Lamb's avatar
James Lamb committed
890

891
  }
James Lamb's avatar
James Lamb committed
892

893
  # Check for unmatching column size
894
  if (ncol(x) != length(value[[2L]])) {
895
896
    stop(
      "can't assign "
897
      , sQuote(length(value[[2L]]))
898
899
900
901
      , " colnames to an lgb.Dataset with "
      , sQuote(ncol(x))
      , " columns"
    )
Guolin Ke's avatar
Guolin Ke committed
902
  }
James Lamb's avatar
James Lamb committed
903

904
  # Set column names properly, and return
905
  x$set_colnames(value[[2L]])
906
  x
James Lamb's avatar
James Lamb committed
907

Guolin Ke's avatar
Guolin Ke committed
908
909
}

910
911
912
#' @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
913
#' @param dataset Object of class \code{lgb.Dataset}
914
#' @param idxset an integer vector of indices of rows needed
Guolin Ke's avatar
Guolin Ke committed
915
916
#' @param ... other parameters (currently not used)
#' @return constructed sub dataset
James Lamb's avatar
James Lamb committed
917
#'
Guolin Ke's avatar
Guolin Ke committed
918
#' @examples
919
920
921
922
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
James Lamb's avatar
James Lamb committed
923
#'
924
#' dsub <- lightgbm::slice(dtrain, seq_len(42L))
925
#' lgb.Dataset.construct(dsub)
926
#' labels <- lightgbm::getinfo(dsub, "label")
James Lamb's avatar
James Lamb committed
927
#'
Guolin Ke's avatar
Guolin Ke committed
928
#' @export
929
930
931
slice <- function(dataset, ...) {
  UseMethod("slice")
}
Guolin Ke's avatar
Guolin Ke committed
932
933
934
935

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

937
  # Check if dataset is not a dataset
938
939
  if (!lgb.is.Dataset(dataset)) {
    stop("slice.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
940
  }
James Lamb's avatar
James Lamb committed
941

942
  # Return sliced set
943
  invisible(dataset$slice(idxset, ...))
James Lamb's avatar
James Lamb committed
944

Guolin Ke's avatar
Guolin Ke committed
945
946
}

947
948
949
#' @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
950
951
952
953
#' @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
954
#'
Guolin Ke's avatar
Guolin Ke committed
955
956
#' @details
#' The \code{name} field can be one of the following:
James Lamb's avatar
James Lamb committed
957
#'
Guolin Ke's avatar
Guolin Ke committed
958
959
960
#' \itemize{
#'     \item \code{label}: label lightgbm learn from ;
#'     \item \code{weight}: to do a weight rescale ;
Nikita Titov's avatar
Nikita Titov committed
961
962
#'     \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
963
#' }
James Lamb's avatar
James Lamb committed
964
#'
Guolin Ke's avatar
Guolin Ke committed
965
#' @examples
966
967
968
969
970
#' library(lightgbm)
#' 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
971
#'
972
973
#' labels <- lightgbm::getinfo(dtrain, "label")
#' lightgbm::setinfo(dtrain, "label", 1 - labels)
James Lamb's avatar
James Lamb committed
974
#'
975
976
#' labels2 <- lightgbm::getinfo(dtrain, "label")
#' stopifnot(all(labels2 == 1 - labels))
James Lamb's avatar
James Lamb committed
977
#'
Guolin Ke's avatar
Guolin Ke committed
978
#' @export
979
980
981
getinfo <- function(dataset, ...) {
  UseMethod("getinfo")
}
Guolin Ke's avatar
Guolin Ke committed
982
983
984
985

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

987
  # Check if dataset is not a dataset
988
989
  if (!lgb.is.Dataset(dataset)) {
    stop("getinfo.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
990
  }
James Lamb's avatar
James Lamb committed
991

992
  # Return information
993
  dataset$getinfo(name)
James Lamb's avatar
James Lamb committed
994

Guolin Ke's avatar
Guolin Ke committed
995
996
}

997
998
999
#' @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
1000
#' @param dataset Object of class \code{lgb.Dataset}
Guolin Ke's avatar
Guolin Ke committed
1001
1002
1003
1004
#' @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
1005
#'
Guolin Ke's avatar
Guolin Ke committed
1006
1007
#' @details
#' The \code{name} field can be one of the following:
James Lamb's avatar
James Lamb committed
1008
#'
Guolin Ke's avatar
Guolin Ke committed
1009
#' \itemize{
1010
1011
1012
1013
1014
1015
1016
#'     \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
1017
#' }
James Lamb's avatar
James Lamb committed
1018
#'
Guolin Ke's avatar
Guolin Ke committed
1019
#' @examples
1020
1021
1022
1023
1024
#' library(lightgbm)
#' 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
1025
#'
1026
1027
#' labels <- lightgbm::getinfo(dtrain, "label")
#' lightgbm::setinfo(dtrain, "label", 1 - labels)
James Lamb's avatar
James Lamb committed
1028
#'
1029
1030
#' labels2 <- lightgbm::getinfo(dtrain, "label")
#' stopifnot(all.equal(labels2, 1 - labels))
James Lamb's avatar
James Lamb committed
1031
#'
Guolin Ke's avatar
Guolin Ke committed
1032
#' @export
1033
1034
1035
setinfo <- function(dataset, ...) {
  UseMethod("setinfo")
}
Guolin Ke's avatar
Guolin Ke committed
1036
1037
1038
1039

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

1041
  # Check if dataset is not a dataset
1042
1043
  if (!lgb.is.Dataset(dataset)) {
    stop("setinfo.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1044
  }
James Lamb's avatar
James Lamb committed
1045

1046
  # Set information
1047
  invisible(dataset$setinfo(name, info))
Guolin Ke's avatar
Guolin Ke committed
1048
1049
}

1050
1051
1052
1053
#' @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.
1054
#' @param dataset object of class \code{lgb.Dataset}
1055
1056
1057
#' @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").
1058
#' @return passed dataset
James Lamb's avatar
James Lamb committed
1059
#'
1060
#' @examples
1061
1062
1063
1064
1065
1066
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.save(dtrain, "lgb.Dataset.data")
#' dtrain <- lgb.Dataset("lgb.Dataset.data")
1067
#' lgb.Dataset.set.categorical(dtrain, 1L:2L)
James Lamb's avatar
James Lamb committed
1068
#'
1069
1070
1071
#' @rdname lgb.Dataset.set.categorical
#' @export
lgb.Dataset.set.categorical <- function(dataset, categorical_feature) {
James Lamb's avatar
James Lamb committed
1072

1073
  # Check if dataset is not a dataset
1074
1075
1076
  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
1077

1078
  # Set categoricals
1079
  invisible(dataset$set_categorical_feature(categorical_feature))
James Lamb's avatar
James Lamb committed
1080

1081
1082
}

1083
1084
1085
#' @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
1086
1087
#' @param dataset object of class \code{lgb.Dataset}
#' @param reference object of class \code{lgb.Dataset}
James Lamb's avatar
James Lamb committed
1088
#'
Guolin Ke's avatar
Guolin Ke committed
1089
#' @return passed dataset
James Lamb's avatar
James Lamb committed
1090
#'
Guolin Ke's avatar
Guolin Ke committed
1091
#' @examples
1092
1093
1094
1095
1096
1097
1098
1099
#' library(lightgbm)
#' 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)
James Lamb's avatar
James Lamb committed
1100
#'
Guolin Ke's avatar
Guolin Ke committed
1101
1102
1103
#' @rdname lgb.Dataset.set.reference
#' @export
lgb.Dataset.set.reference <- function(dataset, reference) {
James Lamb's avatar
James Lamb committed
1104

1105
  # Check if dataset is not a dataset
1106
1107
  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
1108
  }
James Lamb's avatar
James Lamb committed
1109

1110
  # Set reference
1111
  invisible(dataset$set_reference(reference))
Guolin Ke's avatar
Guolin Ke committed
1112
1113
}

1114
1115
1116
1117
#' @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
1118
1119
#' @param dataset object of class \code{lgb.Dataset}
#' @param fname object filename of output file
James Lamb's avatar
James Lamb committed
1120
#'
Guolin Ke's avatar
Guolin Ke committed
1121
#' @return passed dataset
James Lamb's avatar
James Lamb committed
1122
#'
Guolin Ke's avatar
Guolin Ke committed
1123
#' @examples
1124
1125
1126
1127
1128
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.save(dtrain, "data.bin")
Guolin Ke's avatar
Guolin Ke committed
1129
1130
#' @export
lgb.Dataset.save <- function(dataset, fname) {
James Lamb's avatar
James Lamb committed
1131

1132
  # Check if dataset is not a dataset
1133
1134
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.set: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1135
  }
James Lamb's avatar
James Lamb committed
1136

1137
  # File-type is not matching
1138
1139
  if (!is.character(fname)) {
    stop("lgb.Dataset.set: fname should be a character or a file connection")
Guolin Ke's avatar
Guolin Ke committed
1140
  }
James Lamb's avatar
James Lamb committed
1141

1142
  # Store binary
1143
  invisible(dataset$save_binary(fname))
Guolin Ke's avatar
Guolin Ke committed
1144
}