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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

67
68
69
70
71
72
73
      # Check for matrix format
      if (is.matrix(data)) {
        # Check whether matrix is the correct type first ("double")
        if (storage.mode(data) != "double") {
          storage.mode(data) <- "double"
        }
      }
James Lamb's avatar
James Lamb committed
74

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

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

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

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

94
      # Create new dataset
95
96
97
98
99
100
101
102
103
104
105
106
      ret <- Dataset$new(
        data = data
        , params = private$params
        , reference = self
        , colnames = private$colnames
        , categorical_feature = private$categorical_feature
        , predictor = private$predictor
        , free_raw_data = private$free_raw_data
        , used_indices = NULL
        , info = info
        , ...
      )
James Lamb's avatar
James Lamb committed
107

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

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

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

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

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

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

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

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

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

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

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

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

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

164
          }
James Lamb's avatar
James Lamb committed
165

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

169
      }
James Lamb's avatar
James Lamb committed
170

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

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

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

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

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

197
198
199
200
201
202
203
          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
204

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

207
          # Are we using a matrix?
208
209
210
211
212
213
214
215
216
          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
217
218

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

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

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

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

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

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

253
        # Construct subset
254
255
256
257
258
259
260
261
        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
262

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

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

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

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

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

290
      }
James Lamb's avatar
James Lamb committed
291

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

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

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

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

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

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

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

315
316
      # Return self
      return(invisible(self))
James Lamb's avatar
James Lamb committed
317

Guolin Ke's avatar
Guolin Ke committed
318
    },
James Lamb's avatar
James Lamb committed
319

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

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

326
327
        num_row <- 0L
        num_col <- 0L
James Lamb's avatar
James Lamb committed
328

329
330
331
        # 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
332
333
334

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

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

Guolin Ke's avatar
Guolin Ke committed
339
      } else {
James Lamb's avatar
James Lamb committed
340

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

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

Guolin Ke's avatar
Guolin Ke committed
349
    },
James Lamb's avatar
James Lamb committed
350

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

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

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

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

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

Guolin Ke's avatar
Guolin Ke committed
367
      } else {
James Lamb's avatar
James Lamb committed
368

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

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

Guolin Ke's avatar
Guolin Ke committed
377
    },
James Lamb's avatar
James Lamb committed
378

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

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

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

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

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

Guolin Ke's avatar
Guolin Ke committed
406
      }
James Lamb's avatar
James Lamb committed
407

408
      # Return self
409
      return(invisible(self))
James Lamb's avatar
James Lamb committed
410

Guolin Ke's avatar
Guolin Ke committed
411
    },
James Lamb's avatar
James Lamb committed
412

413
    # Get information
Guolin Ke's avatar
Guolin Ke committed
414
    getinfo = function(name) {
James Lamb's avatar
James Lamb committed
415

416
      # Create known attributes list
417
      INFONAMES <- c("label", "weight", "init_score", "group")
James Lamb's avatar
James Lamb committed
418

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

424
      # Check for info name and handle
425
      if (is.null(private$info[[name]])) {
426

427
        if (lgb.is.null.handle(private$handle)) {
428
          stop("Cannot perform getinfo before constructing Dataset.")
429
        }
430

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

440
        # Check if info is not empty
441
        if (info_len > 0L) {
James Lamb's avatar
James Lamb committed
442

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

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

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

Guolin Ke's avatar
Guolin Ke committed
460
461
        }
      }
James Lamb's avatar
James Lamb committed
462

463
      private$info[[name]]
James Lamb's avatar
James Lamb committed
464

Guolin Ke's avatar
Guolin Ke committed
465
    },
James Lamb's avatar
James Lamb committed
466

467
    # Set information
Guolin Ke's avatar
Guolin Ke committed
468
    setinfo = function(name, info) {
James Lamb's avatar
James Lamb committed
469

470
      # Create known attributes list
471
      INFONAMES <- c("label", "weight", "init_score", "group")
James Lamb's avatar
James Lamb committed
472

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

478
479
480
481
482
483
      # 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
484

485
      # Store information privately
Guolin Ke's avatar
Guolin Ke committed
486
      private$info[[name]] <- info
James Lamb's avatar
James Lamb committed
487

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

490
        if (length(info) > 0L) {
James Lamb's avatar
James Lamb committed
491

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

501
502
          private$version <- private$version + 1L

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

Guolin Ke's avatar
Guolin Ke committed
505
      }
James Lamb's avatar
James Lamb committed
506

507
      # Return self
508
      return(invisible(self))
James Lamb's avatar
James Lamb committed
509

Guolin Ke's avatar
Guolin Ke committed
510
    },
James Lamb's avatar
James Lamb committed
511

512
    # Slice dataset
Guolin Ke's avatar
Guolin Ke committed
513
    slice = function(idxset, ...) {
James Lamb's avatar
James Lamb committed
514

515
      # Perform slicing
516
517
518
519
520
521
522
523
524
525
526
527
      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
528

Guolin Ke's avatar
Guolin Ke committed
529
    },
James Lamb's avatar
James Lamb committed
530

531
    # Update parameters
532
    update_params = function(params) {
533
534
535
536
537
538
539
540
541
542
      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)
543
          , lgb.params2str(params)
544
545
          , call_state
          , PACKAGE = "lib_lightgbm"
546
        )
547
548
549
550
551
552
553
554
555
556
557
558
        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()
        }
559
      }
560
      return(invisible(self))
James Lamb's avatar
James Lamb committed
561

Guolin Ke's avatar
Guolin Ke committed
562
    },
James Lamb's avatar
James Lamb committed
563

564
565
566
567
568
569
570
571
572
573
574
    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)
    },

575
    # Set categorical feature parameter
576
    set_categorical_feature = function(categorical_feature) {
James Lamb's avatar
James Lamb committed
577

578
579
      # Check for identical input
      if (identical(private$categorical_feature, categorical_feature)) {
580
        return(invisible(self))
581
      }
James Lamb's avatar
James Lamb committed
582

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

589
      # Overwrite categorical features
590
      private$categorical_feature <- categorical_feature
James Lamb's avatar
James Lamb committed
591

592
      # Finalize and return self
593
      self$finalize()
594
      return(invisible(self))
James Lamb's avatar
James Lamb committed
595

596
    },
James Lamb's avatar
James Lamb committed
597

598
    # Set reference
Guolin Ke's avatar
Guolin Ke committed
599
    set_reference = function(reference) {
James Lamb's avatar
James Lamb committed
600

601
      # Set known references
602
      self$set_categorical_feature(reference$.__enclos_env__$private$categorical_feature)
Guolin Ke's avatar
Guolin Ke committed
603
604
      self$set_colnames(reference$get_colnames())
      private$set_predictor(reference$.__enclos_env__$private$predictor)
James Lamb's avatar
James Lamb committed
605

606
607
      # Check for identical references
      if (identical(private$reference, reference)) {
608
        return(invisible(self))
609
      }
James Lamb's avatar
James Lamb committed
610

611
      # Check for empty data
Guolin Ke's avatar
Guolin Ke committed
612
      if (is.null(private$raw_data)) {
James Lamb's avatar
James Lamb committed
613

614
615
        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
616

Guolin Ke's avatar
Guolin Ke committed
617
      }
James Lamb's avatar
James Lamb committed
618

619
      # Check for non-existing reference
Guolin Ke's avatar
Guolin Ke committed
620
      if (!is.null(reference)) {
James Lamb's avatar
James Lamb committed
621

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

Guolin Ke's avatar
Guolin Ke committed
627
      }
James Lamb's avatar
James Lamb committed
628

629
      # Store reference
Guolin Ke's avatar
Guolin Ke committed
630
      private$reference <- reference
James Lamb's avatar
James Lamb committed
631

632
      # Finalize and return self
Guolin Ke's avatar
Guolin Ke committed
633
      self$finalize()
634
      return(invisible(self))
James Lamb's avatar
James Lamb committed
635

Guolin Ke's avatar
Guolin Ke committed
636
    },
James Lamb's avatar
James Lamb committed
637

638
    # Save binary model
Guolin Ke's avatar
Guolin Ke committed
639
    save_binary = function(fname) {
James Lamb's avatar
James Lamb committed
640

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

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

666
667
    # Get handle
    get_handle = function() {
James Lamb's avatar
James Lamb committed
668

669
670
671
672
      # Get handle and construct if needed
      if (lgb.is.null.handle(private$handle)) {
        self$construct()
      }
673
      private$handle
James Lamb's avatar
James Lamb committed
674

Guolin Ke's avatar
Guolin Ke committed
675
    },
James Lamb's avatar
James Lamb committed
676

677
    # Set predictor
Guolin Ke's avatar
Guolin Ke committed
678
    set_predictor = function(predictor) {
James Lamb's avatar
James Lamb committed
679

680
681
      # Return self is identical predictor
      if (identical(private$predictor, predictor)) {
682
        return(invisible(self))
683
      }
James Lamb's avatar
James Lamb committed
684

685
      # Check for empty data
Guolin Ke's avatar
Guolin Ke committed
686
      if (is.null(private$raw_data)) {
687
688
        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
689
      }
James Lamb's avatar
James Lamb committed
690

691
      # Check for empty predictor
Guolin Ke's avatar
Guolin Ke committed
692
      if (!is.null(predictor)) {
James Lamb's avatar
James Lamb committed
693

694
        # Predictor is unknown
Guolin Ke's avatar
Guolin Ke committed
695
        if (!lgb.check.r6.class(predictor, "lgb.Predictor")) {
696
          stop("set_predictor: Can only use lgb.Predictor as predictor")
Guolin Ke's avatar
Guolin Ke committed
697
        }
James Lamb's avatar
James Lamb committed
698

Guolin Ke's avatar
Guolin Ke committed
699
      }
James Lamb's avatar
James Lamb committed
700

701
      # Store predictor
Guolin Ke's avatar
Guolin Ke committed
702
      private$predictor <- predictor
James Lamb's avatar
James Lamb committed
703

704
      # Finalize and return self
Guolin Ke's avatar
Guolin Ke committed
705
      self$finalize()
706
      return(invisible(self))
James Lamb's avatar
James Lamb committed
707

Guolin Ke's avatar
Guolin Ke committed
708
    }
James Lamb's avatar
James Lamb committed
709

Guolin Ke's avatar
Guolin Ke committed
710
711
712
  )
)

713
714
715
#' @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
716
717
718
719
#' @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
720
#' @param categorical_feature categorical features
Guolin Ke's avatar
Guolin Ke committed
721
#' @param free_raw_data TRUE for need to free raw data after construct
Nikita Titov's avatar
Nikita Titov committed
722
#' @param info a list of information of the \code{lgb.Dataset} object
Guolin Ke's avatar
Guolin Ke committed
723
#' @param ... other information to pass to \code{info} or parameters pass to \code{params}
James Lamb's avatar
James Lamb committed
724
#'
Guolin Ke's avatar
Guolin Ke committed
725
#' @return constructed dataset
James Lamb's avatar
James Lamb committed
726
#'
Guolin Ke's avatar
Guolin Ke committed
727
#' @examples
728
729
730
731
732
733
734
#' 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
735
#'
Guolin Ke's avatar
Guolin Ke committed
736
737
#' @export
lgb.Dataset <- function(data,
738
739
740
                        params = list(),
                        reference = NULL,
                        colnames = NULL,
741
                        categorical_feature = NULL,
742
743
                        free_raw_data = TRUE,
                        info = list(),
Guolin Ke's avatar
Guolin Ke committed
744
                        ...) {
James Lamb's avatar
James Lamb committed
745

746
  # Create new dataset
747
748
749
750
751
752
753
754
755
756
757
758
  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
759

Guolin Ke's avatar
Guolin Ke committed
760
761
}

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

784
  # Check if dataset is not a dataset
785
786
  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
787
  }
James Lamb's avatar
James Lamb committed
788

789
  # Create validation dataset
790
  invisible(dataset$create_valid(data, info, ...))
James Lamb's avatar
James Lamb committed
791

792
}
Guolin Ke's avatar
Guolin Ke committed
793

794
795
796
#' @name lgb.Dataset.construct
#' @title Construct Dataset explicitly
#' @description Construct Dataset explicitly
Guolin Ke's avatar
Guolin Ke committed
797
#' @param dataset Object of class \code{lgb.Dataset}
James Lamb's avatar
James Lamb committed
798
#'
Guolin Ke's avatar
Guolin Ke committed
799
#' @examples
800
801
802
803
804
#' 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
805
#'
Guolin Ke's avatar
Guolin Ke committed
806
807
#' @export
lgb.Dataset.construct <- function(dataset) {
James Lamb's avatar
James Lamb committed
808

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

814
  # Construct the dataset
815
  invisible(dataset$construct())
James Lamb's avatar
James Lamb committed
816

Guolin Ke's avatar
Guolin Ke committed
817
818
}

819
820
#' @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
821
822
#' @param x Object of class \code{lgb.Dataset}
#' @param ... other parameters
James Lamb's avatar
James Lamb committed
823
#'
Guolin Ke's avatar
Guolin Ke committed
824
#' @return a vector of numbers of rows and of columns
James Lamb's avatar
James Lamb committed
825
#'
Guolin Ke's avatar
Guolin Ke committed
826
827
828
#' @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
829
#'
Guolin Ke's avatar
Guolin Ke committed
830
#' @examples
831
832
833
834
#' 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
835
#'
836
837
838
#' 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
839
#'
Guolin Ke's avatar
Guolin Ke committed
840
841
842
#' @rdname dim
#' @export
dim.lgb.Dataset <- function(x, ...) {
James Lamb's avatar
James Lamb committed
843

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

849
  # Return dimensions
850
  x$dim()
James Lamb's avatar
James Lamb committed
851

Guolin Ke's avatar
Guolin Ke committed
852
853
}

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

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

885
  # Return dimension names
886
  list(NULL, x$get_colnames())
James Lamb's avatar
James Lamb committed
887

Guolin Ke's avatar
Guolin Ke committed
888
889
890
891
892
}

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

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

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

904
  # Check for second value missing
905
  if (is.null(value[[2L]])) {
James Lamb's avatar
James Lamb committed
906

907
    # No column names
Guolin Ke's avatar
Guolin Ke committed
908
909
    x$set_colnames(NULL)
    return(x)
James Lamb's avatar
James Lamb committed
910

911
  }
James Lamb's avatar
James Lamb committed
912

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

924
  # Set column names properly, and return
925
  x$set_colnames(value[[2L]])
926
  x
James Lamb's avatar
James Lamb committed
927

Guolin Ke's avatar
Guolin Ke committed
928
929
}

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

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

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

962
  # Return sliced set
963
  invisible(dataset$slice(idxset, ...))
James Lamb's avatar
James Lamb committed
964

Guolin Ke's avatar
Guolin Ke committed
965
966
}

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

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

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

1012
  # Return information
1013
  dataset$getinfo(name)
James Lamb's avatar
James Lamb committed
1014

Guolin Ke's avatar
Guolin Ke committed
1015
1016
}

1017
1018
1019
#' @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
1020
#' @param dataset Object of class \code{lgb.Dataset}
Guolin Ke's avatar
Guolin Ke committed
1021
1022
1023
1024
#' @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
1025
#'
Guolin Ke's avatar
Guolin Ke committed
1026
1027
#' @details
#' The \code{name} field can be one of the following:
James Lamb's avatar
James Lamb committed
1028
#'
Guolin Ke's avatar
Guolin Ke committed
1029
#' \itemize{
1030
1031
1032
1033
1034
1035
1036
#'     \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
1037
#' }
James Lamb's avatar
James Lamb committed
1038
#'
Guolin Ke's avatar
Guolin Ke committed
1039
#' @examples
1040
1041
1042
1043
1044
#' 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
1045
#'
1046
1047
#' labels <- lightgbm::getinfo(dtrain, "label")
#' lightgbm::setinfo(dtrain, "label", 1 - labels)
James Lamb's avatar
James Lamb committed
1048
#'
1049
1050
#' labels2 <- lightgbm::getinfo(dtrain, "label")
#' stopifnot(all.equal(labels2, 1 - labels))
James Lamb's avatar
James Lamb committed
1051
#'
Guolin Ke's avatar
Guolin Ke committed
1052
#' @export
1053
1054
1055
setinfo <- function(dataset, ...) {
  UseMethod("setinfo")
}
Guolin Ke's avatar
Guolin Ke committed
1056
1057
1058
1059

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

1061
  # Check if dataset is not a dataset
1062
1063
  if (!lgb.is.Dataset(dataset)) {
    stop("setinfo.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1064
  }
James Lamb's avatar
James Lamb committed
1065

1066
  # Set information
1067
  invisible(dataset$setinfo(name, info))
Guolin Ke's avatar
Guolin Ke committed
1068
1069
}

1070
1071
1072
1073
#' @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.
1074
#' @param dataset object of class \code{lgb.Dataset}
1075
1076
1077
#' @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").
1078
#' @return passed dataset
James Lamb's avatar
James Lamb committed
1079
#'
1080
#' @examples
1081
1082
1083
1084
1085
1086
#' 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")
1087
#' lgb.Dataset.set.categorical(dtrain, 1L:2L)
James Lamb's avatar
James Lamb committed
1088
#'
1089
1090
1091
#' @rdname lgb.Dataset.set.categorical
#' @export
lgb.Dataset.set.categorical <- function(dataset, categorical_feature) {
James Lamb's avatar
James Lamb committed
1092

1093
  # Check if dataset is not a dataset
1094
1095
1096
  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
1097

1098
  # Set categoricals
1099
  invisible(dataset$set_categorical_feature(categorical_feature))
James Lamb's avatar
James Lamb committed
1100

1101
1102
}

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

1125
  # Check if dataset is not a dataset
1126
1127
  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
1128
  }
James Lamb's avatar
James Lamb committed
1129

1130
  # Set reference
1131
  invisible(dataset$set_reference(reference))
Guolin Ke's avatar
Guolin Ke committed
1132
1133
}

1134
1135
1136
1137
#' @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
1138
1139
#' @param dataset object of class \code{lgb.Dataset}
#' @param fname object filename of output file
James Lamb's avatar
James Lamb committed
1140
#'
Guolin Ke's avatar
Guolin Ke committed
1141
#' @return passed dataset
James Lamb's avatar
James Lamb committed
1142
#'
Guolin Ke's avatar
Guolin Ke committed
1143
#' @examples
1144
1145
1146
1147
1148
#' 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
1149
1150
#' @export
lgb.Dataset.save <- function(dataset, fname) {
James Lamb's avatar
James Lamb committed
1151

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

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

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