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

15
        # Freeing up handle
16
        lgb.call(fun_name = "LGBM_DatasetFree_R", ret = NULL, private$handle)
Guolin Ke's avatar
Guolin Ke committed
17
        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

21
22
      return(invisible(NULL))

Guolin Ke's avatar
Guolin Ke committed
23
    },
James Lamb's avatar
James Lamb committed
24

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

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

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

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

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

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

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

Guolin Ke's avatar
Guolin Ke committed
60
        } else {
James Lamb's avatar
James Lamb committed
61

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

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

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

69
70
71
72
73
74
75
      # 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
76

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

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

90
91
      return(invisible(NULL))

Guolin Ke's avatar
Guolin Ke committed
92
    },
James Lamb's avatar
James Lamb committed
93

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

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

112
      return(invisible(ret))
James Lamb's avatar
James Lamb committed
113

Guolin Ke's avatar
Guolin Ke committed
114
    },
James Lamb's avatar
James Lamb committed
115

116
    # Dataset constructor
Guolin Ke's avatar
Guolin Ke committed
117
    construct = function() {
James Lamb's avatar
James Lamb committed
118

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

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

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

135
136
      # Get categorical feature index
      if (!is.null(private$categorical_feature)) {
James Lamb's avatar
James Lamb committed
137

138
        # Check for character name
139
        if (is.character(private$categorical_feature)) {
James Lamb's avatar
James Lamb committed
140

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

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

151
          } else {
James Lamb's avatar
James Lamb committed
152

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

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

167
          }
James Lamb's avatar
James Lamb committed
168

169
        # Store indices for categorical features
170
        private$params$categorical_feature <- cate_indices
James Lamb's avatar
James Lamb committed
171

172
      }
James Lamb's avatar
James Lamb committed
173

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

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

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

194
      # Not subsetting
Guolin Ke's avatar
Guolin Ke committed
195
      if (is.null(private$used_indices)) {
James Lamb's avatar
James Lamb committed
196

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

200
          handle <- lgb.call(
201
            fun_name = "LGBM_DatasetCreateFromFile_R"
202
            , ret = handle
203
            , lgb.c_str(x = private$raw_data)
204
205
206
            , params_str
            , ref_handle
          )
James Lamb's avatar
James Lamb committed
207

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

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

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

Guolin Ke's avatar
Guolin Ke committed
239
        } else {
James Lamb's avatar
James Lamb committed
240

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

Guolin Ke's avatar
Guolin Ke committed
247
        }
James Lamb's avatar
James Lamb committed
248

Guolin Ke's avatar
Guolin Ke committed
249
      } else {
James Lamb's avatar
James Lamb committed
250

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

256
        # Construct subset
257
        handle <- lgb.call(
258
          fun_name = "LGBM_DatasetGetSubset_R"
259
260
261
262
263
264
          , 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
265

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

274
275
      # Set feature names
      if (!is.null(private$colnames)) {
276
        self$set_colnames(colnames = private$colnames)
277
      }
278

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

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

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

293
      }
James Lamb's avatar
James Lamb committed
294

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

300
      # Get private information
301
      if (length(private$info) > 0L) {
James Lamb's avatar
James Lamb committed
302

303
        # Set infos
304
        for (i in seq_along(private$info)) {
James Lamb's avatar
James Lamb committed
305

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

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

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

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

318
      return(invisible(self))
James Lamb's avatar
James Lamb committed
319

Guolin Ke's avatar
Guolin Ke committed
320
    },
James Lamb's avatar
James Lamb committed
321

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

325
      # Check for handle
326
      if (!lgb.is.null.handle(x = private$handle)) {
James Lamb's avatar
James Lamb committed
327

328
329
        num_row <- 0L
        num_col <- 0L
James Lamb's avatar
James Lamb committed
330

331
        # Get numeric data and numeric features
332
333
334
335
336
337
338
339
340
341
342
343
        return(
          c(
            lgb.call(
              fun_name = "LGBM_DatasetGetNumData_R"
              , ret = num_row
              , private$handle
            ),
            lgb.call(
              fun_name = "LGBM_DatasetGetNumFeature_R"
              , ret = num_col
              , private$handle
            )
344
345
          )
        )
James Lamb's avatar
James Lamb committed
346
347
348

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

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

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

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

Guolin Ke's avatar
Guolin Ke committed
361
      }
James Lamb's avatar
James Lamb committed
362

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

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

368
      # Check for handle
369
      if (!lgb.is.null.handle(x = private$handle)) {
James Lamb's avatar
James Lamb committed
370

371
        # Get feature names and write them
372
373
374
375
        cnames <- lgb.call.return.str(
            fun_name = "LGBM_DatasetGetFeatureNames_R"
            , private$handle
        )
376
        private$colnames <- as.character(base::strsplit(cnames, "\t")[[1L]])
377
        return(private$colnames)
James Lamb's avatar
James Lamb committed
378
379
380

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

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

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

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

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

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

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

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

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

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

414
        # Merge names with tab separation
Guolin Ke's avatar
Guolin Ke committed
415
        merged_name <- paste0(as.list(private$colnames), collapse = "\t")
416
        lgb.call(
417
          fun_name = "LGBM_DatasetSetFeatureNames_R"
418
419
          , ret = NULL
          , private$handle
420
          , lgb.c_str(x = merged_name)
421
        )
James Lamb's avatar
James Lamb committed
422

Guolin Ke's avatar
Guolin Ke committed
423
      }
James Lamb's avatar
James Lamb committed
424

425
      return(invisible(self))
James Lamb's avatar
James Lamb committed
426

Guolin Ke's avatar
Guolin Ke committed
427
    },
James Lamb's avatar
James Lamb committed
428

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

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

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

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

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

447
        # Get field size of info
448
        info_len <- 0L
449
        info_len <- lgb.call(
450
          fun_name = "LGBM_DatasetGetFieldSize_R"
451
452
          , ret = info_len
          , private$handle
453
          , lgb.c_str(x = name)
454
        )
James Lamb's avatar
James Lamb committed
455

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

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

467
          ret <- lgb.call(
468
            fun_name = "LGBM_DatasetGetField_R"
469
470
            , ret = ret
            , private$handle
471
            , lgb.c_str(x = name)
472
          )
James Lamb's avatar
James Lamb committed
473

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

Guolin Ke's avatar
Guolin Ke committed
476
477
        }
      }
James Lamb's avatar
James Lamb committed
478

479
      return(private$info[[name]])
James Lamb's avatar
James Lamb committed
480

Guolin Ke's avatar
Guolin Ke committed
481
    },
James Lamb's avatar
James Lamb committed
482

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

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

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

494
495
496
497
498
499
      # 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
500

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

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

506
        if (length(info) > 0L) {
James Lamb's avatar
James Lamb committed
507

508
          lgb.call(
509
            fun_name = "LGBM_DatasetSetField_R"
510
511
            , ret = NULL
            , private$handle
512
            , lgb.c_str(x = name)
513
514
515
            , info
            , length(info)
          )
James Lamb's avatar
James Lamb committed
516

517
518
          private$version <- private$version + 1L

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

Guolin Ke's avatar
Guolin Ke committed
521
      }
James Lamb's avatar
James Lamb committed
522

523
      return(invisible(self))
James Lamb's avatar
James Lamb committed
524

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

527
    # Slice dataset
Guolin Ke's avatar
Guolin Ke committed
528
    slice = function(idxset, ...) {
James Lamb's avatar
James Lamb committed
529

530
      # Perform slicing
531
532
533
534
535
536
537
538
539
540
541
542
543
      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
          , ...
        )
544
      )
James Lamb's avatar
James Lamb committed
545

Guolin Ke's avatar
Guolin Ke committed
546
    },
James Lamb's avatar
James Lamb committed
547

548
549
550
    # [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.
551
    update_params = function(params) {
552
553
554
      if (length(params) == 0L) {
        return(invisible(self))
      }
555
      if (lgb.is.null.handle(x = private$handle)) {
556
557
        private$params <- modifyList(private$params, params)
      } else {
558
559
560
561
562
563
564
565
566
567
568
569
        tryCatch({
          call_state <- 0L
          .Call(
            "LGBM_DatasetUpdateParamChecking_R"
            , lgb.params2str(params = private$params)
            , lgb.params2str(params = params)
            , call_state
            , PACKAGE = "lib_lightgbm"
          )
        }, 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
570
          if (is.null(private$raw_data)) {
571
            stop(e)
572
573
          }

574
575
          # If updating failed but raw data is available, modify the params
          # on the R side and re-set ("deconstruct") the Dataset
576
577
          private$params <- modifyList(private$params, params)
          self$finalize()
578
        })
579
      }
580
      return(invisible(self))
James Lamb's avatar
James Lamb committed
581

Guolin Ke's avatar
Guolin Ke committed
582
    },
James Lamb's avatar
James Lamb committed
583

584
585
586
587
588
589
590
591
592
593
594
    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)
    },

595
    # Set categorical feature parameter
596
    set_categorical_feature = function(categorical_feature) {
James Lamb's avatar
James Lamb committed
597

598
599
      # Check for identical input
      if (identical(private$categorical_feature, categorical_feature)) {
600
        return(invisible(self))
601
      }
James Lamb's avatar
James Lamb committed
602

603
      # Check for empty data
604
      if (is.null(private$raw_data)) {
605
606
        stop("set_categorical_feature: cannot set categorical feature after freeing raw data,
          please set ", sQuote("free_raw_data = FALSE"), " when you construct lgb.Dataset")
607
      }
James Lamb's avatar
James Lamb committed
608

609
      # Overwrite categorical features
610
      private$categorical_feature <- categorical_feature
James Lamb's avatar
James Lamb committed
611

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

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

618
    # Set reference
Guolin Ke's avatar
Guolin Ke committed
619
    set_reference = function(reference) {
James Lamb's avatar
James Lamb committed
620

621
      # Set known references
622
623
624
      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
625

626
627
      # Check for identical references
      if (identical(private$reference, reference)) {
628
        return(invisible(self))
629
      }
James Lamb's avatar
James Lamb committed
630

631
      # Check for empty data
Guolin Ke's avatar
Guolin Ke committed
632
      if (is.null(private$raw_data)) {
James Lamb's avatar
James Lamb committed
633

634
635
        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
636

Guolin Ke's avatar
Guolin Ke committed
637
      }
James Lamb's avatar
James Lamb committed
638

639
      # Check for non-existing reference
Guolin Ke's avatar
Guolin Ke committed
640
      if (!is.null(reference)) {
James Lamb's avatar
James Lamb committed
641

642
        # Reference is unknown
643
        if (!lgb.check.r6.class(object = reference, name = "lgb.Dataset")) {
644
          stop("set_reference: Can only use lgb.Dataset as a reference")
Guolin Ke's avatar
Guolin Ke committed
645
        }
James Lamb's avatar
James Lamb committed
646

Guolin Ke's avatar
Guolin Ke committed
647
      }
James Lamb's avatar
James Lamb committed
648

649
      # Store reference
Guolin Ke's avatar
Guolin Ke committed
650
      private$reference <- reference
James Lamb's avatar
James Lamb committed
651

652
      # Finalize and return self
Guolin Ke's avatar
Guolin Ke committed
653
      self$finalize()
654
      return(invisible(self))
James Lamb's avatar
James Lamb committed
655

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

658
    # Save binary model
Guolin Ke's avatar
Guolin Ke committed
659
    save_binary = function(fname) {
James Lamb's avatar
James Lamb committed
660

661
      # Store binary data
Guolin Ke's avatar
Guolin Ke committed
662
      self$construct()
663
      lgb.call(
664
        fun_name = "LGBM_DatasetSaveBinary_R"
665
666
        , ret = NULL
        , private$handle
667
        , lgb.c_str(x = fname)
668
      )
669
      return(invisible(self))
Guolin Ke's avatar
Guolin Ke committed
670
    }
James Lamb's avatar
James Lamb committed
671

Guolin Ke's avatar
Guolin Ke committed
672
673
  ),
  private = list(
674
675
676
677
678
    handle = NULL,
    raw_data = NULL,
    params = list(),
    reference = NULL,
    colnames = NULL,
679
    categorical_feature = NULL,
680
681
682
683
    predictor = NULL,
    free_raw_data = TRUE,
    used_indices = NULL,
    info = NULL,
684
    version = 0L,
James Lamb's avatar
James Lamb committed
685

686
687
    # Get handle
    get_handle = function() {
James Lamb's avatar
James Lamb committed
688

689
      # Get handle and construct if needed
690
      if (lgb.is.null.handle(x = private$handle)) {
691
692
        self$construct()
      }
693
      return(private$handle)
James Lamb's avatar
James Lamb committed
694

Guolin Ke's avatar
Guolin Ke committed
695
    },
James Lamb's avatar
James Lamb committed
696

697
    # Set predictor
Guolin Ke's avatar
Guolin Ke committed
698
    set_predictor = function(predictor) {
James Lamb's avatar
James Lamb committed
699

700
      if (identical(private$predictor, predictor)) {
701
        return(invisible(self))
702
      }
James Lamb's avatar
James Lamb committed
703

704
      # Check for empty data
Guolin Ke's avatar
Guolin Ke committed
705
      if (is.null(private$raw_data)) {
706
707
        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
708
      }
James Lamb's avatar
James Lamb committed
709

710
      # Check for empty predictor
Guolin Ke's avatar
Guolin Ke committed
711
      if (!is.null(predictor)) {
James Lamb's avatar
James Lamb committed
712

713
        # Predictor is unknown
714
        if (!lgb.check.r6.class(object = predictor, name = "lgb.Predictor")) {
715
          stop("set_predictor: Can only use lgb.Predictor as predictor")
Guolin Ke's avatar
Guolin Ke committed
716
        }
James Lamb's avatar
James Lamb committed
717

Guolin Ke's avatar
Guolin Ke committed
718
      }
James Lamb's avatar
James Lamb committed
719

720
      # Store predictor
Guolin Ke's avatar
Guolin Ke committed
721
      private$predictor <- predictor
James Lamb's avatar
James Lamb committed
722

723
      # Finalize and return self
Guolin Ke's avatar
Guolin Ke committed
724
      self$finalize()
725
      return(invisible(self))
James Lamb's avatar
James Lamb committed
726

Guolin Ke's avatar
Guolin Ke committed
727
    }
James Lamb's avatar
James Lamb committed
728

Guolin Ke's avatar
Guolin Ke committed
729
730
731
  )
)

732
733
734
#' @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
735
#' @param data a \code{matrix} object, a \code{dgCMatrix} object or a character representing a filename
736
737
738
739
740
741
742
#' @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
743
#' @param colnames names of columns
744
745
746
747
748
749
750
751
#' @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
752
#' @param info a list of information of the \code{lgb.Dataset} object
Guolin Ke's avatar
Guolin Ke committed
753
#' @param ... other information to pass to \code{info} or parameters pass to \code{params}
James Lamb's avatar
James Lamb committed
754
#'
Guolin Ke's avatar
Guolin Ke committed
755
#' @return constructed dataset
James Lamb's avatar
James Lamb committed
756
#'
Guolin Ke's avatar
Guolin Ke committed
757
#' @examples
758
#' \donttest{
759
760
761
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
762
763
764
#' data_file <- tempfile(fileext = ".data")
#' lgb.Dataset.save(dtrain, data_file)
#' dtrain <- lgb.Dataset(data_file)
765
#' lgb.Dataset.construct(dtrain)
766
#' }
Guolin Ke's avatar
Guolin Ke committed
767
768
#' @export
lgb.Dataset <- function(data,
769
770
771
                        params = list(),
                        reference = NULL,
                        colnames = NULL,
772
                        categorical_feature = NULL,
773
774
                        free_raw_data = TRUE,
                        info = list(),
Guolin Ke's avatar
Guolin Ke committed
775
                        ...) {
James Lamb's avatar
James Lamb committed
776

777
  # Create new dataset
778
779
780
781
782
783
784
785
786
787
788
789
790
791
  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
792

Guolin Ke's avatar
Guolin Ke committed
793
794
}

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

817
  # Check if dataset is not a dataset
818
  if (!lgb.is.Dataset(x = dataset)) {
819
    stop("lgb.Dataset.create.valid: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
820
  }
James Lamb's avatar
James Lamb committed
821

822
  # Create validation dataset
823
  return(invisible(dataset$create_valid(data = data, info = info, ...)))
James Lamb's avatar
James Lamb committed
824

825
}
Guolin Ke's avatar
Guolin Ke committed
826

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

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

848
  # Construct the dataset
849
  return(invisible(dataset$construct()))
James Lamb's avatar
James Lamb committed
850

Guolin Ke's avatar
Guolin Ke committed
851
852
}

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

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

883
  return(x$dim())
James Lamb's avatar
James Lamb committed
884

Guolin Ke's avatar
Guolin Ke committed
885
886
}

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

914
  # Check if dataset is not a dataset
915
  if (!lgb.is.Dataset(x = x)) {
916
    stop("dimnames.lgb.Dataset: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
917
  }
James Lamb's avatar
James Lamb committed
918

919
  # Return dimension names
920
  return(list(NULL, x$get_colnames()))
James Lamb's avatar
James Lamb committed
921

Guolin Ke's avatar
Guolin Ke committed
922
923
924
925
926
}

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

928
  # Check if invalid element list
929
  if (!identical(class(value), "list") || length(value) != 2L) {
930
    stop("invalid ", sQuote("value"), " given: must be a list of two elements")
931
  }
James Lamb's avatar
James Lamb committed
932

933
934
935
936
  # Check for unknown row names
  if (!is.null(value[[1L]])) {
    stop("lgb.Dataset does not have rownames")
  }
James Lamb's avatar
James Lamb committed
937

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

940
    x$set_colnames(colnames = NULL)
Guolin Ke's avatar
Guolin Ke committed
941
    return(x)
James Lamb's avatar
James Lamb committed
942

943
  }
James Lamb's avatar
James Lamb committed
944

945
  # Check for unmatching column size
946
  if (ncol(x) != length(value[[2L]])) {
947
948
    stop(
      "can't assign "
949
      , sQuote(length(value[[2L]]))
950
951
952
953
      , " colnames to an lgb.Dataset with "
      , sQuote(ncol(x))
      , " columns"
    )
Guolin Ke's avatar
Guolin Ke committed
954
  }
James Lamb's avatar
James Lamb committed
955

956
  # Set column names properly, and return
957
  x$set_colnames(colnames = value[[2L]])
958
  return(x)
James Lamb's avatar
James Lamb committed
959

Guolin Ke's avatar
Guolin Ke committed
960
961
}

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

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

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

994
  # Return sliced set
995
  return(invisible(dataset$slice(idxset = idxset, ...)))
James Lamb's avatar
James Lamb committed
996

Guolin Ke's avatar
Guolin Ke committed
997
998
}

999
1000
1001
#' @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
1002
1003
1004
1005
#' @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
1006
#'
Guolin Ke's avatar
Guolin Ke committed
1007
1008
#' @details
#' The \code{name} field can be one of the following:
James Lamb's avatar
James Lamb committed
1009
#'
Guolin Ke's avatar
Guolin Ke committed
1010
1011
1012
#' \itemize{
#'     \item \code{label}: label lightgbm learn from ;
#'     \item \code{weight}: to do a weight rescale ;
1013
1014
1015
1016
1017
#'     \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
1018
#'     \item \code{init_score}: initial score is the base prediction lightgbm will boost from.
Guolin Ke's avatar
Guolin Ke committed
1019
#' }
James Lamb's avatar
James Lamb committed
1020
#'
Guolin Ke's avatar
Guolin Ke committed
1021
#' @examples
1022
#' \donttest{
1023
1024
1025
1026
#' 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
1027
#'
1028
1029
#' labels <- lightgbm::getinfo(dtrain, "label")
#' lightgbm::setinfo(dtrain, "label", 1 - labels)
James Lamb's avatar
James Lamb committed
1030
#'
1031
1032
#' labels2 <- lightgbm::getinfo(dtrain, "label")
#' stopifnot(all(labels2 == 1 - labels))
1033
#' }
Guolin Ke's avatar
Guolin Ke committed
1034
#' @export
1035
1036
1037
getinfo <- function(dataset, ...) {
  UseMethod("getinfo")
}
Guolin Ke's avatar
Guolin Ke committed
1038
1039
1040
1041

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

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

1048
  return(dataset$getinfo(name = name))
James Lamb's avatar
James Lamb committed
1049

Guolin Ke's avatar
Guolin Ke committed
1050
1051
}

1052
1053
1054
#' @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
1055
#' @param dataset Object of class \code{lgb.Dataset}
Guolin Ke's avatar
Guolin Ke committed
1056
1057
1058
#' @param name the name of the field to get
#' @param info the specific field of information to set
#' @param ... other parameters
1059
#' @return the dataset you passed in
James Lamb's avatar
James Lamb committed
1060
#'
Guolin Ke's avatar
Guolin Ke committed
1061
1062
#' @details
#' The \code{name} field can be one of the following:
James Lamb's avatar
James Lamb committed
1063
#'
Guolin Ke's avatar
Guolin Ke committed
1064
#' \itemize{
1065
1066
1067
1068
1069
#'     \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.
1070
1071
1072
#'         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
1073
#' }
James Lamb's avatar
James Lamb committed
1074
#'
Guolin Ke's avatar
Guolin Ke committed
1075
#' @examples
1076
#' \donttest{
1077
1078
1079
1080
#' 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
1081
#'
1082
1083
#' labels <- lightgbm::getinfo(dtrain, "label")
#' lightgbm::setinfo(dtrain, "label", 1 - labels)
James Lamb's avatar
James Lamb committed
1084
#'
1085
1086
#' labels2 <- lightgbm::getinfo(dtrain, "label")
#' stopifnot(all.equal(labels2, 1 - labels))
1087
#' }
Guolin Ke's avatar
Guolin Ke committed
1088
#' @export
1089
1090
1091
setinfo <- function(dataset, ...) {
  UseMethod("setinfo")
}
Guolin Ke's avatar
Guolin Ke committed
1092
1093
1094
1095

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

1097
  if (!lgb.is.Dataset(x = dataset)) {
1098
    stop("setinfo.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1099
  }
James Lamb's avatar
James Lamb committed
1100

1101
  # Set information
1102
  return(invisible(dataset$setinfo(name = name, info = info)))
Guolin Ke's avatar
Guolin Ke committed
1103
1104
}

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

1129
  if (!lgb.is.Dataset(x = dataset)) {
1130
1131
    stop("lgb.Dataset.set.categorical: input dataset should be an lgb.Dataset object")
  }
James Lamb's avatar
James Lamb committed
1132

1133
  # Set categoricals
1134
  return(invisible(dataset$set_categorical_feature(categorical_feature = categorical_feature)))
James Lamb's avatar
James Lamb committed
1135

1136
1137
}

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

1160
  # Check if dataset is not a dataset
1161
  if (!lgb.is.Dataset(x = dataset)) {
1162
    stop("lgb.Dataset.set.reference: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1163
  }
James Lamb's avatar
James Lamb committed
1164

1165
  # Set reference
1166
  return(invisible(dataset$set_reference(reference = reference)))
Guolin Ke's avatar
Guolin Ke committed
1167
1168
}

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

1188
  # Check if dataset is not a dataset
1189
  if (!lgb.is.Dataset(x = dataset)) {
1190
    stop("lgb.Dataset.set: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1191
  }
James Lamb's avatar
James Lamb committed
1192

1193
  # File-type is not matching
1194
1195
  if (!is.character(fname)) {
    stop("lgb.Dataset.set: fname should be a character or a file connection")
Guolin Ke's avatar
Guolin Ke committed
1196
  }
James Lamb's avatar
James Lamb committed
1197

1198
  # Store binary
1199
  return(invisible(dataset$save_binary(fname = fname)))
Guolin Ke's avatar
Guolin Ke committed
1200
}