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

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

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

24
25
      return(invisible(NULL))

Guolin Ke's avatar
Guolin Ke committed
26
    },
James Lamb's avatar
James Lamb committed
27

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

40
      # validate inputs early to avoid unnecessary computation
41
      if (!(is.null(reference) || lgb.check.r6.class(object = reference, name = "lgb.Dataset"))) {
42
43
          stop("lgb.Dataset: If provided, reference must be a ", sQuote("lgb.Dataset"))
      }
44
      if (!(is.null(predictor) || lgb.check.r6.class(object = predictor, name = "lgb.Predictor"))) {
45
46
47
          stop("lgb.Dataset: If provided, predictor must be a ", sQuote("lgb.Predictor"))
      }

48
      # Check for additional parameters
49
      additional_params <- list(...)
James Lamb's avatar
James Lamb committed
50

51
52
      # Create known attributes list
      INFO_KEYS <- c("label", "weight", "init_score", "group")
James Lamb's avatar
James Lamb committed
53

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

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

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

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

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

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

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

72
73
74
75
76
77
78
      # Check for matrix format
      if (is.matrix(data)) {
        # Check whether matrix is the correct type first ("double")
        if (storage.mode(data) != "double") {
          storage.mode(data) <- "double"
        }
      }
James Lamb's avatar
James Lamb committed
79

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

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

93
94
      return(invisible(NULL))

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

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

101
      # Create new dataset
102
103
104
105
106
107
108
109
110
111
112
113
      ret <- Dataset$new(
        data = data
        , params = private$params
        , reference = self
        , colnames = private$colnames
        , categorical_feature = private$categorical_feature
        , predictor = private$predictor
        , free_raw_data = private$free_raw_data
        , used_indices = NULL
        , info = info
        , ...
      )
James Lamb's avatar
James Lamb committed
114

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

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

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

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

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

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

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

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

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

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

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

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

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

170
          }
James Lamb's avatar
James Lamb committed
171

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

175
      }
James Lamb's avatar
James Lamb committed
176

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

296
      }
James Lamb's avatar
James Lamb committed
297

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

370
      # Check for handle
371
      if (!lgb.is.null.handle(x = private$handle)) {
372
        private$colnames <- .Call(
373
374
          LGBM_DatasetGetFeatureNames_R
          , private$handle
375
        )
376
        return(private$colnames)
James Lamb's avatar
James Lamb committed
377
378
379

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

380
        # Check if dgCMatrix (sparse matrix column compressed)
381
        return(colnames(private$raw_data))
James Lamb's avatar
James Lamb committed
382

Guolin Ke's avatar
Guolin Ke committed
383
      } else {
James Lamb's avatar
James Lamb committed
384

385
        # Trying to work with unknown dimensions is not possible
386
387
388
389
        stop(
          "dim: cannot get dimensions before dataset has been constructed, please call "
          , "lgb.Dataset.construct explicitly"
        )
James Lamb's avatar
James Lamb committed
390

Guolin Ke's avatar
Guolin Ke committed
391
      }
James Lamb's avatar
James Lamb committed
392

Guolin Ke's avatar
Guolin Ke committed
393
    },
James Lamb's avatar
James Lamb committed
394

395
    # Set column names
Guolin Ke's avatar
Guolin Ke committed
396
    set_colnames = function(colnames) {
James Lamb's avatar
James Lamb committed
397

398
399
      # Check column names non-existence
      if (is.null(colnames)) {
400
        return(invisible(self))
401
      }
James Lamb's avatar
James Lamb committed
402

403
      # Check empty column names
Guolin Ke's avatar
Guolin Ke committed
404
      colnames <- as.character(colnames)
405
      if (length(colnames) == 0L) {
406
        return(invisible(self))
407
      }
James Lamb's avatar
James Lamb committed
408

409
      # Write column names
Guolin Ke's avatar
Guolin Ke committed
410
      private$colnames <- colnames
411
      if (!lgb.is.null.handle(x = private$handle)) {
James Lamb's avatar
James Lamb committed
412

413
        # Merge names with tab separation
Guolin Ke's avatar
Guolin Ke committed
414
        merged_name <- paste0(as.list(private$colnames), collapse = "\t")
415
416
        .Call(
          LGBM_DatasetSetFeatureNames_R
417
          , private$handle
418
          , merged_name
419
        )
James Lamb's avatar
James Lamb committed
420

Guolin Ke's avatar
Guolin Ke committed
421
      }
James Lamb's avatar
James Lamb committed
422

423
      return(invisible(self))
James Lamb's avatar
James Lamb committed
424

Guolin Ke's avatar
Guolin Ke committed
425
    },
James Lamb's avatar
James Lamb committed
426

427
    # Get information
Guolin Ke's avatar
Guolin Ke committed
428
    getinfo = function(name) {
James Lamb's avatar
James Lamb committed
429

430
      # Create known attributes list
431
      INFONAMES <- c("label", "weight", "init_score", "group")
James Lamb's avatar
James Lamb committed
432

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

438
      # Check for info name and handle
439
      if (is.null(private$info[[name]])) {
440

441
        if (lgb.is.null.handle(x = private$handle)) {
442
          stop("Cannot perform getinfo before constructing Dataset.")
443
        }
444

445
        # Get field size of info
446
        info_len <- 0L
447
448
        .Call(
          LGBM_DatasetGetFieldSize_R
449
          , private$handle
450
          , name
451
          , info_len
452
        )
James Lamb's avatar
James Lamb committed
453

454
        # Check if info is not empty
455
        if (info_len > 0L) {
James Lamb's avatar
James Lamb committed
456

457
          # Get back fields
Guolin Ke's avatar
Guolin Ke committed
458
          ret <- NULL
459
460
461
462
463
          ret <- if (name == "group") {
            integer(info_len) # Integer
          } else {
            numeric(info_len) # Numeric
          }
James Lamb's avatar
James Lamb committed
464

465
466
          .Call(
            LGBM_DatasetGetField_R
467
            , private$handle
468
            , name
469
            , ret
470
          )
James Lamb's avatar
James Lamb committed
471

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

Guolin Ke's avatar
Guolin Ke committed
474
475
        }
      }
James Lamb's avatar
James Lamb committed
476

477
      return(private$info[[name]])
James Lamb's avatar
James Lamb committed
478

Guolin Ke's avatar
Guolin Ke committed
479
    },
James Lamb's avatar
James Lamb committed
480

481
    # Set information
Guolin Ke's avatar
Guolin Ke committed
482
    setinfo = function(name, info) {
James Lamb's avatar
James Lamb committed
483

484
      # Create known attributes list
485
      INFONAMES <- c("label", "weight", "init_score", "group")
James Lamb's avatar
James Lamb committed
486

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

492
493
494
495
496
497
      # 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
498

499
      # Store information privately
Guolin Ke's avatar
Guolin Ke committed
500
      private$info[[name]] <- info
James Lamb's avatar
James Lamb committed
501

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

504
        if (length(info) > 0L) {
James Lamb's avatar
James Lamb committed
505

506
507
          .Call(
            LGBM_DatasetSetField_R
508
            , private$handle
509
            , name
510
511
512
            , info
            , length(info)
          )
James Lamb's avatar
James Lamb committed
513

514
515
          private$version <- private$version + 1L

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

Guolin Ke's avatar
Guolin Ke committed
518
      }
James Lamb's avatar
James Lamb committed
519

520
      return(invisible(self))
James Lamb's avatar
James Lamb committed
521

Guolin Ke's avatar
Guolin Ke committed
522
    },
James Lamb's avatar
James Lamb committed
523

524
    # Slice dataset
Guolin Ke's avatar
Guolin Ke committed
525
    slice = function(idxset, ...) {
James Lamb's avatar
James Lamb committed
526

527
      # Perform slicing
528
529
530
531
532
533
534
535
536
537
538
539
540
      return(
        Dataset$new(
          data = NULL
          , params = private$params
          , reference = self
          , colnames = private$colnames
          , categorical_feature = private$categorical_feature
          , predictor = private$predictor
          , free_raw_data = private$free_raw_data
          , used_indices = sort(idxset, decreasing = FALSE)
          , info = NULL
          , ...
        )
541
      )
James Lamb's avatar
James Lamb committed
542

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

545
546
547
    # [description] Update Dataset parameters. If it has not been constructed yet,
    #               this operation just happens on the R side (updating private$params).
    #               If it has been constructed, parameters will be updated on the C++ side.
548
    update_params = function(params) {
549
550
551
      if (length(params) == 0L) {
        return(invisible(self))
      }
552
      if (lgb.is.null.handle(x = private$handle)) {
553
554
        private$params <- modifyList(private$params, params)
      } else {
555
556
        tryCatch({
          .Call(
557
            LGBM_DatasetUpdateParamChecking_R
558
559
560
561
562
563
            , lgb.params2str(params = private$params)
            , lgb.params2str(params = params)
          )
        }, error = function(e) {
          # If updating failed but raw data is not available, raise an error because
          # achieving what the user asked for is not possible
564
          if (is.null(private$raw_data)) {
565
            stop(e)
566
567
          }

568
569
          # If updating failed but raw data is available, modify the params
          # on the R side and re-set ("deconstruct") the Dataset
570
571
          private$params <- modifyList(private$params, params)
          self$finalize()
572
        })
573
      }
574
      return(invisible(self))
James Lamb's avatar
James Lamb committed
575

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

578
579
580
581
582
583
584
585
586
587
588
    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)
    },

589
    # Set categorical feature parameter
590
    set_categorical_feature = function(categorical_feature) {
James Lamb's avatar
James Lamb committed
591

592
593
      # Check for identical input
      if (identical(private$categorical_feature, categorical_feature)) {
594
        return(invisible(self))
595
      }
James Lamb's avatar
James Lamb committed
596

597
      # Check for empty data
598
      if (is.null(private$raw_data)) {
599
600
        stop("set_categorical_feature: cannot set categorical feature after freeing raw data,
          please set ", sQuote("free_raw_data = FALSE"), " when you construct lgb.Dataset")
601
      }
James Lamb's avatar
James Lamb committed
602

603
      # Overwrite categorical features
604
      private$categorical_feature <- categorical_feature
James Lamb's avatar
James Lamb committed
605

606
      # Finalize and return self
607
      self$finalize()
608
      return(invisible(self))
James Lamb's avatar
James Lamb committed
609

610
    },
James Lamb's avatar
James Lamb committed
611

612
    # Set reference
Guolin Ke's avatar
Guolin Ke committed
613
    set_reference = function(reference) {
James Lamb's avatar
James Lamb committed
614

615
      # Set known references
616
617
618
      self$set_categorical_feature(categorical_feature = reference$.__enclos_env__$private$categorical_feature)
      self$set_colnames(colnames = reference$get_colnames())
      private$set_predictor(predictor = reference$.__enclos_env__$private$predictor)
James Lamb's avatar
James Lamb committed
619

620
621
      # Check for identical references
      if (identical(private$reference, reference)) {
622
        return(invisible(self))
623
      }
James Lamb's avatar
James Lamb committed
624

625
      # Check for empty data
Guolin Ke's avatar
Guolin Ke committed
626
      if (is.null(private$raw_data)) {
James Lamb's avatar
James Lamb committed
627

628
629
        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
630

Guolin Ke's avatar
Guolin Ke committed
631
      }
James Lamb's avatar
James Lamb committed
632

633
      # Check for non-existing reference
Guolin Ke's avatar
Guolin Ke committed
634
      if (!is.null(reference)) {
James Lamb's avatar
James Lamb committed
635

636
        # Reference is unknown
637
        if (!lgb.check.r6.class(object = reference, name = "lgb.Dataset")) {
638
          stop("set_reference: Can only use lgb.Dataset as a reference")
Guolin Ke's avatar
Guolin Ke committed
639
        }
James Lamb's avatar
James Lamb committed
640

Guolin Ke's avatar
Guolin Ke committed
641
      }
James Lamb's avatar
James Lamb committed
642

643
      # Store reference
Guolin Ke's avatar
Guolin Ke committed
644
      private$reference <- reference
James Lamb's avatar
James Lamb committed
645

646
      # Finalize and return self
Guolin Ke's avatar
Guolin Ke committed
647
      self$finalize()
648
      return(invisible(self))
James Lamb's avatar
James Lamb committed
649

Guolin Ke's avatar
Guolin Ke committed
650
    },
James Lamb's avatar
James Lamb committed
651

652
    # Save binary model
Guolin Ke's avatar
Guolin Ke committed
653
    save_binary = function(fname) {
James Lamb's avatar
James Lamb committed
654

655
      # Store binary data
Guolin Ke's avatar
Guolin Ke committed
656
      self$construct()
657
658
      .Call(
        LGBM_DatasetSaveBinary_R
659
        , private$handle
660
        , fname
661
      )
662
      return(invisible(self))
Guolin Ke's avatar
Guolin Ke committed
663
    }
James Lamb's avatar
James Lamb committed
664

Guolin Ke's avatar
Guolin Ke committed
665
666
  ),
  private = list(
667
668
669
670
671
    handle = NULL,
    raw_data = NULL,
    params = list(),
    reference = NULL,
    colnames = NULL,
672
    categorical_feature = NULL,
673
674
675
676
    predictor = NULL,
    free_raw_data = TRUE,
    used_indices = NULL,
    info = NULL,
677
    version = 0L,
James Lamb's avatar
James Lamb committed
678

679
680
    # Get handle
    get_handle = function() {
James Lamb's avatar
James Lamb committed
681

682
      # Get handle and construct if needed
683
      if (lgb.is.null.handle(x = private$handle)) {
684
685
        self$construct()
      }
686
      return(private$handle)
James Lamb's avatar
James Lamb committed
687

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

690
    # Set predictor
Guolin Ke's avatar
Guolin Ke committed
691
    set_predictor = function(predictor) {
James Lamb's avatar
James Lamb committed
692

693
      if (identical(private$predictor, predictor)) {
694
        return(invisible(self))
695
      }
James Lamb's avatar
James Lamb committed
696

697
      # Check for empty data
Guolin Ke's avatar
Guolin Ke committed
698
      if (is.null(private$raw_data)) {
699
700
        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
701
      }
James Lamb's avatar
James Lamb committed
702

703
      # Check for empty predictor
Guolin Ke's avatar
Guolin Ke committed
704
      if (!is.null(predictor)) {
James Lamb's avatar
James Lamb committed
705

706
        # Predictor is unknown
707
        if (!lgb.check.r6.class(object = predictor, name = "lgb.Predictor")) {
708
          stop("set_predictor: Can only use lgb.Predictor as predictor")
Guolin Ke's avatar
Guolin Ke committed
709
        }
James Lamb's avatar
James Lamb committed
710

Guolin Ke's avatar
Guolin Ke committed
711
      }
James Lamb's avatar
James Lamb committed
712

713
      # Store predictor
Guolin Ke's avatar
Guolin Ke committed
714
      private$predictor <- predictor
James Lamb's avatar
James Lamb committed
715

716
      # Finalize and return self
Guolin Ke's avatar
Guolin Ke committed
717
      self$finalize()
718
      return(invisible(self))
James Lamb's avatar
James Lamb committed
719

Guolin Ke's avatar
Guolin Ke committed
720
    }
James Lamb's avatar
James Lamb committed
721

Guolin Ke's avatar
Guolin Ke committed
722
723
724
  )
)

725
726
727
#' @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
728
#' @param data a \code{matrix} object, a \code{dgCMatrix} object or a character representing a filename
729
730
731
732
733
734
735
#' @param params a list of parameters. See
#'               \href{https://lightgbm.readthedocs.io/en/latest/Parameters.html#dataset-parameters}{
#'               The "Dataset Parameters" section of the documentation} for a list of parameters
#'               and valid values.
#' @param reference reference dataset. When LightGBM creates a Dataset, it does some preprocessing like binning
#'                  continuous features into histograms. If you want to apply the same bin boundaries from an existing
#'                  dataset to new \code{data}, pass that existing Dataset to this argument.
Guolin Ke's avatar
Guolin Ke committed
736
#' @param colnames names of columns
737
738
739
740
741
742
743
744
#' @param categorical_feature categorical features. This can either be a character vector of feature
#'                            names or an integer vector with the indices of the features (e.g.
#'                            \code{c(1L, 10L)} to say "the first and tenth columns").
#' @param free_raw_data LightGBM constructs its data format, called a "Dataset", from tabular data.
#'                      By default, that Dataset object on the R side does not keep a copy of the raw data.
#'                      This reduces LightGBM's memory consumption, but it means that the Dataset object
#'                      cannot be changed after it has been constructed. If you'd prefer to be able to
#'                      change the Dataset object after construction, set \code{free_raw_data = FALSE}.
Nikita Titov's avatar
Nikita Titov committed
745
#' @param info a list of information of the \code{lgb.Dataset} object
Guolin Ke's avatar
Guolin Ke committed
746
#' @param ... other information to pass to \code{info} or parameters pass to \code{params}
James Lamb's avatar
James Lamb committed
747
#'
Guolin Ke's avatar
Guolin Ke committed
748
#' @return constructed dataset
James Lamb's avatar
James Lamb committed
749
#'
Guolin Ke's avatar
Guolin Ke committed
750
#' @examples
751
#' \donttest{
752
753
754
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
755
756
757
#' data_file <- tempfile(fileext = ".data")
#' lgb.Dataset.save(dtrain, data_file)
#' dtrain <- lgb.Dataset(data_file)
758
#' lgb.Dataset.construct(dtrain)
759
#' }
Guolin Ke's avatar
Guolin Ke committed
760
761
#' @export
lgb.Dataset <- function(data,
762
763
764
                        params = list(),
                        reference = NULL,
                        colnames = NULL,
765
                        categorical_feature = NULL,
766
767
                        free_raw_data = TRUE,
                        info = list(),
Guolin Ke's avatar
Guolin Ke committed
768
                        ...) {
James Lamb's avatar
James Lamb committed
769

770
  # Create new dataset
771
772
773
774
775
776
777
778
779
780
781
782
783
784
  return(
    invisible(Dataset$new(
      data = data
      , params = params
      , reference = reference
      , colnames = colnames
      , categorical_feature = categorical_feature
      , predictor = NULL
      , free_raw_data = free_raw_data
      , used_indices = NULL
      , info = info
      , ...
    ))
  )
James Lamb's avatar
James Lamb committed
785

Guolin Ke's avatar
Guolin Ke committed
786
787
}

788
789
790
#' @name lgb.Dataset.create.valid
#' @title Construct validation data
#' @description Construct validation data according to training data
Guolin Ke's avatar
Guolin Ke committed
791
792
#' @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
793
#' @param info a list of information of the \code{lgb.Dataset} object
Guolin Ke's avatar
Guolin Ke committed
794
#' @param ... other information to pass to \code{info}.
James Lamb's avatar
James Lamb committed
795
#'
Guolin Ke's avatar
Guolin Ke committed
796
#' @return constructed dataset
James Lamb's avatar
James Lamb committed
797
#'
Guolin Ke's avatar
Guolin Ke committed
798
#' @examples
799
#' \donttest{
800
801
802
803
804
805
#' 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)
806
#' }
Guolin Ke's avatar
Guolin Ke committed
807
#' @export
808
lgb.Dataset.create.valid <- function(dataset, data, info = list(), ...) {
James Lamb's avatar
James Lamb committed
809

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

815
  # Create validation dataset
816
  return(invisible(dataset$create_valid(data = data, info = info, ...)))
James Lamb's avatar
James Lamb committed
817

818
}
Guolin Ke's avatar
Guolin Ke committed
819

820
821
822
#' @name lgb.Dataset.construct
#' @title Construct Dataset explicitly
#' @description Construct Dataset explicitly
Guolin Ke's avatar
Guolin Ke committed
823
#' @param dataset Object of class \code{lgb.Dataset}
James Lamb's avatar
James Lamb committed
824
#'
Guolin Ke's avatar
Guolin Ke committed
825
#' @examples
826
#' \donttest{
827
828
829
830
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
831
#' }
832
#' @return constructed dataset
Guolin Ke's avatar
Guolin Ke committed
833
834
#' @export
lgb.Dataset.construct <- function(dataset) {
James Lamb's avatar
James Lamb committed
835

836
  # Check if dataset is not a dataset
837
  if (!lgb.is.Dataset(x = dataset)) {
838
    stop("lgb.Dataset.construct: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
839
  }
James Lamb's avatar
James Lamb committed
840

841
  # Construct the dataset
842
  return(invisible(dataset$construct()))
James Lamb's avatar
James Lamb committed
843

Guolin Ke's avatar
Guolin Ke committed
844
845
}

846
847
#' @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
848
849
#' @param x Object of class \code{lgb.Dataset}
#' @param ... other parameters
James Lamb's avatar
James Lamb committed
850
#'
Guolin Ke's avatar
Guolin Ke committed
851
#' @return a vector of numbers of rows and of columns
James Lamb's avatar
James Lamb committed
852
#'
Guolin Ke's avatar
Guolin Ke committed
853
854
855
#' @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
856
#'
Guolin Ke's avatar
Guolin Ke committed
857
#' @examples
858
#' \donttest{
859
860
861
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
James Lamb's avatar
James Lamb committed
862
#'
863
864
865
#' stopifnot(nrow(dtrain) == nrow(train$data))
#' stopifnot(ncol(dtrain) == ncol(train$data))
#' stopifnot(all(dim(dtrain) == dim(train$data)))
866
#' }
Guolin Ke's avatar
Guolin Ke committed
867
868
869
#' @rdname dim
#' @export
dim.lgb.Dataset <- function(x, ...) {
James Lamb's avatar
James Lamb committed
870

871
  # Check if dataset is not a dataset
872
  if (!lgb.is.Dataset(x = x)) {
873
    stop("dim.lgb.Dataset: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
874
  }
James Lamb's avatar
James Lamb committed
875

876
  return(x$dim())
James Lamb's avatar
James Lamb committed
877

Guolin Ke's avatar
Guolin Ke committed
878
879
}

880
881
882
#' @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
883
884
#' @param x object of class \code{lgb.Dataset}
#' @param value a list of two elements: the first one is ignored
885
#'              and the second one is column names
Guolin Ke's avatar
Guolin Ke committed
886
887
888
889
890
891
#'
#' @details
#' Generic \code{dimnames} methods are used by \code{colnames}.
#' Since row names are irrelevant, it is recommended to use \code{colnames} directly.
#'
#' @examples
892
#' \donttest{
893
894
895
896
897
898
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
#' dimnames(dtrain)
#' colnames(dtrain)
899
#' colnames(dtrain) <- make.names(seq_len(ncol(train$data)))
900
#' print(dtrain, verbose = TRUE)
901
#' }
Guolin Ke's avatar
Guolin Ke committed
902
#' @rdname dimnames.lgb.Dataset
903
#' @return A list with the dimension names of the dataset
Guolin Ke's avatar
Guolin Ke committed
904
905
#' @export
dimnames.lgb.Dataset <- function(x) {
James Lamb's avatar
James Lamb committed
906

907
  # Check if dataset is not a dataset
908
  if (!lgb.is.Dataset(x = x)) {
909
    stop("dimnames.lgb.Dataset: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
910
  }
James Lamb's avatar
James Lamb committed
911

912
  # Return dimension names
913
  return(list(NULL, x$get_colnames()))
James Lamb's avatar
James Lamb committed
914

Guolin Ke's avatar
Guolin Ke committed
915
916
917
918
919
}

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

921
  # Check if invalid element list
922
  if (!identical(class(value), "list") || length(value) != 2L) {
923
    stop("invalid ", sQuote("value"), " given: must be a list of two elements")
924
  }
James Lamb's avatar
James Lamb committed
925

926
927
928
929
  # Check for unknown row names
  if (!is.null(value[[1L]])) {
    stop("lgb.Dataset does not have rownames")
  }
James Lamb's avatar
James Lamb committed
930

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

933
    x$set_colnames(colnames = NULL)
Guolin Ke's avatar
Guolin Ke committed
934
    return(x)
James Lamb's avatar
James Lamb committed
935

936
  }
James Lamb's avatar
James Lamb committed
937

938
  # Check for unmatching column size
939
  if (ncol(x) != length(value[[2L]])) {
940
941
    stop(
      "can't assign "
942
      , sQuote(length(value[[2L]]))
943
944
945
946
      , " colnames to an lgb.Dataset with "
      , sQuote(ncol(x))
      , " columns"
    )
Guolin Ke's avatar
Guolin Ke committed
947
  }
James Lamb's avatar
James Lamb committed
948

949
  # Set column names properly, and return
950
  x$set_colnames(colnames = value[[2L]])
951
  return(x)
James Lamb's avatar
James Lamb committed
952

Guolin Ke's avatar
Guolin Ke committed
953
954
}

955
956
957
#' @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
958
#' @param dataset Object of class \code{lgb.Dataset}
959
#' @param idxset an integer vector of indices of rows needed
Guolin Ke's avatar
Guolin Ke committed
960
961
#' @param ... other parameters (currently not used)
#' @return constructed sub dataset
James Lamb's avatar
James Lamb committed
962
#'
Guolin Ke's avatar
Guolin Ke committed
963
#' @examples
964
#' \donttest{
965
966
967
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
James Lamb's avatar
James Lamb committed
968
#'
969
#' dsub <- lightgbm::slice(dtrain, seq_len(42L))
970
#' lgb.Dataset.construct(dsub)
971
#' labels <- lightgbm::getinfo(dsub, "label")
972
#' }
Guolin Ke's avatar
Guolin Ke committed
973
#' @export
974
975
976
slice <- function(dataset, ...) {
  UseMethod("slice")
}
Guolin Ke's avatar
Guolin Ke committed
977
978
979
980

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

982
  # Check if dataset is not a dataset
983
  if (!lgb.is.Dataset(x = dataset)) {
984
    stop("slice.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
985
  }
James Lamb's avatar
James Lamb committed
986

987
  # Return sliced set
988
  return(invisible(dataset$slice(idxset = idxset, ...)))
James Lamb's avatar
James Lamb committed
989

Guolin Ke's avatar
Guolin Ke committed
990
991
}

992
993
994
#' @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
995
996
997
998
#' @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
999
#'
Guolin Ke's avatar
Guolin Ke committed
1000
1001
#' @details
#' The \code{name} field can be one of the following:
James Lamb's avatar
James Lamb committed
1002
#'
Guolin Ke's avatar
Guolin Ke committed
1003
1004
1005
#' \itemize{
#'     \item \code{label}: label lightgbm learn from ;
#'     \item \code{weight}: to do a weight rescale ;
1006
1007
1008
1009
1010
#'     \item{\code{group}: used for learning-to-rank tasks. An integer vector describing how to
#'         group rows together as ordered results from the same set of candidate results to be ranked.
#'         For example, if you have a 100-document dataset with \code{group = c(10, 20, 40, 10, 10, 10)},
#'         that means that you have 6 groups, where the first 10 records are in the first group,
#'         records 11-30 are in the second group, etc.}
Nikita Titov's avatar
Nikita Titov committed
1011
#'     \item \code{init_score}: initial score is the base prediction lightgbm will boost from.
Guolin Ke's avatar
Guolin Ke committed
1012
#' }
James Lamb's avatar
James Lamb committed
1013
#'
Guolin Ke's avatar
Guolin Ke committed
1014
#' @examples
1015
#' \donttest{
1016
1017
1018
1019
#' 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
1020
#'
1021
1022
#' labels <- lightgbm::getinfo(dtrain, "label")
#' lightgbm::setinfo(dtrain, "label", 1 - labels)
James Lamb's avatar
James Lamb committed
1023
#'
1024
1025
#' labels2 <- lightgbm::getinfo(dtrain, "label")
#' stopifnot(all(labels2 == 1 - labels))
1026
#' }
Guolin Ke's avatar
Guolin Ke committed
1027
#' @export
1028
1029
1030
getinfo <- function(dataset, ...) {
  UseMethod("getinfo")
}
Guolin Ke's avatar
Guolin Ke committed
1031
1032
1033
1034

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

1036
  # Check if dataset is not a dataset
1037
  if (!lgb.is.Dataset(x = dataset)) {
1038
    stop("getinfo.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1039
  }
James Lamb's avatar
James Lamb committed
1040

1041
  return(dataset$getinfo(name = name))
James Lamb's avatar
James Lamb committed
1042

Guolin Ke's avatar
Guolin Ke committed
1043
1044
}

1045
1046
1047
#' @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
1048
#' @param dataset Object of class \code{lgb.Dataset}
Guolin Ke's avatar
Guolin Ke committed
1049
1050
1051
#' @param name the name of the field to get
#' @param info the specific field of information to set
#' @param ... other parameters
1052
#' @return the dataset you passed in
James Lamb's avatar
James Lamb committed
1053
#'
Guolin Ke's avatar
Guolin Ke committed
1054
1055
#' @details
#' The \code{name} field can be one of the following:
James Lamb's avatar
James Lamb committed
1056
#'
Guolin Ke's avatar
Guolin Ke committed
1057
#' \itemize{
1058
1059
1060
1061
1062
#'     \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.
1063
1064
1065
#'         For example, if you have a 100-document dataset with \code{group = c(10, 20, 40, 10, 10, 10)},
#'         that means that you have 6 groups, where the first 10 records are in the first group,
#'         records 11-30 are in the second group, etc.}
Guolin Ke's avatar
Guolin Ke committed
1066
#' }
James Lamb's avatar
James Lamb committed
1067
#'
Guolin Ke's avatar
Guolin Ke committed
1068
#' @examples
1069
#' \donttest{
1070
1071
1072
1073
#' 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
1074
#'
1075
1076
#' labels <- lightgbm::getinfo(dtrain, "label")
#' lightgbm::setinfo(dtrain, "label", 1 - labels)
James Lamb's avatar
James Lamb committed
1077
#'
1078
1079
#' labels2 <- lightgbm::getinfo(dtrain, "label")
#' stopifnot(all.equal(labels2, 1 - labels))
1080
#' }
Guolin Ke's avatar
Guolin Ke committed
1081
#' @export
1082
1083
1084
setinfo <- function(dataset, ...) {
  UseMethod("setinfo")
}
Guolin Ke's avatar
Guolin Ke committed
1085
1086
1087
1088

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

1090
  if (!lgb.is.Dataset(x = dataset)) {
1091
    stop("setinfo.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1092
  }
James Lamb's avatar
James Lamb committed
1093

1094
  # Set information
1095
  return(invisible(dataset$setinfo(name = name, info = info)))
Guolin Ke's avatar
Guolin Ke committed
1096
1097
}

1098
1099
1100
1101
#' @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.
1102
#' @param dataset object of class \code{lgb.Dataset}
1103
1104
1105
#' @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").
1106
#' @return the dataset you passed in
James Lamb's avatar
James Lamb committed
1107
#'
1108
#' @examples
1109
#' \donttest{
1110
1111
1112
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
1113
1114
1115
#' data_file <- tempfile(fileext = ".data")
#' lgb.Dataset.save(dtrain, data_file)
#' dtrain <- lgb.Dataset(data_file)
1116
#' lgb.Dataset.set.categorical(dtrain, 1L:2L)
1117
#' }
1118
1119
1120
#' @rdname lgb.Dataset.set.categorical
#' @export
lgb.Dataset.set.categorical <- function(dataset, categorical_feature) {
James Lamb's avatar
James Lamb committed
1121

1122
  if (!lgb.is.Dataset(x = dataset)) {
1123
1124
    stop("lgb.Dataset.set.categorical: input dataset should be an lgb.Dataset object")
  }
James Lamb's avatar
James Lamb committed
1125

1126
  # Set categoricals
1127
  return(invisible(dataset$set_categorical_feature(categorical_feature = categorical_feature)))
James Lamb's avatar
James Lamb committed
1128

1129
1130
}

1131
1132
1133
#' @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
1134
1135
#' @param dataset object of class \code{lgb.Dataset}
#' @param reference object of class \code{lgb.Dataset}
James Lamb's avatar
James Lamb committed
1136
#'
1137
#' @return the dataset you passed in
James Lamb's avatar
James Lamb committed
1138
#'
Guolin Ke's avatar
Guolin Ke committed
1139
#' @examples
1140
#' \donttest{
1141
1142
1143
1144
1145
1146
1147
#' 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)
1148
#' }
Guolin Ke's avatar
Guolin Ke committed
1149
1150
1151
#' @rdname lgb.Dataset.set.reference
#' @export
lgb.Dataset.set.reference <- function(dataset, reference) {
James Lamb's avatar
James Lamb committed
1152

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

1158
  # Set reference
1159
  return(invisible(dataset$set_reference(reference = reference)))
Guolin Ke's avatar
Guolin Ke committed
1160
1161
}

1162
1163
1164
1165
#' @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
1166
1167
#' @param dataset object of class \code{lgb.Dataset}
#' @param fname object filename of output file
James Lamb's avatar
James Lamb committed
1168
#'
1169
#' @return the dataset you passed in
James Lamb's avatar
James Lamb committed
1170
#'
Guolin Ke's avatar
Guolin Ke committed
1171
#' @examples
1172
#' \donttest{
1173
1174
1175
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
1176
#' lgb.Dataset.save(dtrain, tempfile(fileext = ".bin"))
1177
#' }
Guolin Ke's avatar
Guolin Ke committed
1178
1179
#' @export
lgb.Dataset.save <- function(dataset, fname) {
James Lamb's avatar
James Lamb committed
1180

1181
  # Check if dataset is not a dataset
1182
  if (!lgb.is.Dataset(x = dataset)) {
1183
    stop("lgb.Dataset.set: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1184
  }
James Lamb's avatar
James Lamb committed
1185

1186
  # File-type is not matching
1187
1188
  if (!is.character(fname)) {
    stop("lgb.Dataset.set: fname should be a character or a file connection")
Guolin Ke's avatar
Guolin Ke committed
1189
  }
James Lamb's avatar
James Lamb committed
1190

1191
  # Store binary
1192
  return(invisible(dataset$save_binary(fname = fname)))
Guolin Ke's avatar
Guolin Ke committed
1193
}