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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

164
          }
James Lamb's avatar
James Lamb committed
165

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

169
      }
James Lamb's avatar
James Lamb committed
170

Guolin Ke's avatar
Guolin Ke committed
171
172
      # Check has header or not
      has_header <- FALSE
173
      if (!is.null(private$params$has_header) || !is.null(private$params$header)) {
174
175
176
        params_has_header <- tolower(as.character(private$params$has_header)) == "true"
        params_header <- tolower(as.character(private$params$header)) == "true"
        if (params_has_header || params_header) {
Guolin Ke's avatar
Guolin Ke committed
177
178
179
          has_header <- TRUE
        }
      }
James Lamb's avatar
James Lamb committed
180

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

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

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

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

197
198
199
200
201
202
203
          handle <- lgb.call(
            "LGBM_DatasetCreateFromFile_R"
            , ret = handle
            , lgb.c_str(private$raw_data)
            , params_str
            , ref_handle
          )
James Lamb's avatar
James Lamb committed
204

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

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

        } else if (methods::is(private$raw_data, "dgCMatrix")) {
219
          if (length(private$raw_data@p) > 2147483647L) {
220
221
            stop("Cannot support large CSC matrix")
          }
222
          # Are we using a dgCMatrix (sparsed matrix column compressed)
223
224
225
226
227
228
229
230
231
232
233
234
          handle <- lgb.call(
            "LGBM_DatasetCreateFromCSC_R"
            , ret = handle
            , private$raw_data@p
            , private$raw_data@i
            , private$raw_data@x
            , length(private$raw_data@p)
            , length(private$raw_data@x)
            , nrow(private$raw_data)
            , params_str
            , ref_handle
          )
James Lamb's avatar
James Lamb committed
235

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

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

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

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

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

253
        # Construct subset
254
255
256
257
258
259
260
261
        handle <- lgb.call(
          "LGBM_DatasetGetSubset_R"
          , ret = handle
          , ref_handle
          , c(private$used_indices) # Adding c() fixes issue in R v3.5
          , length(private$used_indices)
          , params_str
        )
James Lamb's avatar
James Lamb committed
262

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

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

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

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

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

290
      }
James Lamb's avatar
James Lamb committed
291

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

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

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

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

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

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

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

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

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

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

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

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

329
330
331
        # Get numeric data and numeric features
        c(lgb.call("LGBM_DatasetGetNumData_R", ret = num_row, private$handle),
          lgb.call("LGBM_DatasetGetNumFeature_R", ret = num_col, private$handle))
James Lamb's avatar
James Lamb committed
332
333
334

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

478
479
480
481
482
483
      # Check for type of information
      info <- if (name == "group") {
        as.integer(info) # Integer
      } else {
        as.numeric(info) # Numeric
      }
James Lamb's avatar
James Lamb committed
484

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

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

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

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

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

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

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

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

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

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

515
      # Perform slicing
516
517
518
519
520
521
522
523
524
525
526
527
      Dataset$new(
        data = NULL
        , params = private$params
        , reference = self
        , colnames = private$colnames
        , categorical_feature = private$categorical_feature
        , predictor = private$predictor
        , free_raw_data = private$free_raw_data
        , used_indices = sort(idxset, decreasing = FALSE)
        , info = NULL
        , ...
      )
James Lamb's avatar
James Lamb committed
528

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

531
    # Update parameters
532
    update_params = function(params) {
James Lamb's avatar
James Lamb committed
533

534
      # Parameter updating
535
      if (!lgb.is.null.handle(private$handle)) {
536
537
538
539
540
541
        lgb.call(
          "LGBM_DatasetUpdateParam_R"
          , ret = NULL
          , private$handle
          , lgb.params2str(params)
        )
542
543
        return(invisible(self))
      }
Guolin Ke's avatar
Guolin Ke committed
544
      private$params <- modifyList(private$params, params)
545
      return(invisible(self))
James Lamb's avatar
James Lamb committed
546

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

549
    # Set categorical feature parameter
550
    set_categorical_feature = function(categorical_feature) {
James Lamb's avatar
James Lamb committed
551

552
553
      # Check for identical input
      if (identical(private$categorical_feature, categorical_feature)) {
554
        return(invisible(self))
555
      }
James Lamb's avatar
James Lamb committed
556

557
      # Check for empty data
558
      if (is.null(private$raw_data)) {
559
560
        stop("set_categorical_feature: cannot set categorical feature after freeing raw data,
          please set ", sQuote("free_raw_data = FALSE"), " when you construct lgb.Dataset")
561
      }
James Lamb's avatar
James Lamb committed
562

563
      # Overwrite categorical features
564
      private$categorical_feature <- categorical_feature
James Lamb's avatar
James Lamb committed
565

566
      # Finalize and return self
567
      self$finalize()
568
      return(invisible(self))
James Lamb's avatar
James Lamb committed
569

570
    },
James Lamb's avatar
James Lamb committed
571

572
    # Set reference
Guolin Ke's avatar
Guolin Ke committed
573
    set_reference = function(reference) {
James Lamb's avatar
James Lamb committed
574

575
      # Set known references
576
      self$set_categorical_feature(reference$.__enclos_env__$private$categorical_feature)
Guolin Ke's avatar
Guolin Ke committed
577
578
      self$set_colnames(reference$get_colnames())
      private$set_predictor(reference$.__enclos_env__$private$predictor)
James Lamb's avatar
James Lamb committed
579

580
581
      # Check for identical references
      if (identical(private$reference, reference)) {
582
        return(invisible(self))
583
      }
James Lamb's avatar
James Lamb committed
584

585
      # Check for empty data
Guolin Ke's avatar
Guolin Ke committed
586
      if (is.null(private$raw_data)) {
James Lamb's avatar
James Lamb committed
587

588
589
        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
590

Guolin Ke's avatar
Guolin Ke committed
591
      }
James Lamb's avatar
James Lamb committed
592

593
      # Check for non-existing reference
Guolin Ke's avatar
Guolin Ke committed
594
      if (!is.null(reference)) {
James Lamb's avatar
James Lamb committed
595

596
        # Reference is unknown
Guolin Ke's avatar
Guolin Ke committed
597
        if (!lgb.check.r6.class(reference, "lgb.Dataset")) {
598
          stop("set_reference: Can only use lgb.Dataset as a reference")
Guolin Ke's avatar
Guolin Ke committed
599
        }
James Lamb's avatar
James Lamb committed
600

Guolin Ke's avatar
Guolin Ke committed
601
      }
James Lamb's avatar
James Lamb committed
602

603
      # Store reference
Guolin Ke's avatar
Guolin Ke committed
604
      private$reference <- reference
James Lamb's avatar
James Lamb committed
605

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

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

612
    # Save binary model
Guolin Ke's avatar
Guolin Ke committed
613
    save_binary = function(fname) {
James Lamb's avatar
James Lamb committed
614

615
      # Store binary data
Guolin Ke's avatar
Guolin Ke committed
616
      self$construct()
617
618
619
620
621
622
      lgb.call(
        "LGBM_DatasetSaveBinary_R"
        , ret = NULL
        , private$handle
        , lgb.c_str(fname)
      )
623
      return(invisible(self))
Guolin Ke's avatar
Guolin Ke committed
624
    }
James Lamb's avatar
James Lamb committed
625

Guolin Ke's avatar
Guolin Ke committed
626
627
  ),
  private = list(
628
629
630
631
632
    handle = NULL,
    raw_data = NULL,
    params = list(),
    reference = NULL,
    colnames = NULL,
633
    categorical_feature = NULL,
634
635
636
637
    predictor = NULL,
    free_raw_data = TRUE,
    used_indices = NULL,
    info = NULL,
638
    version = 0L,
James Lamb's avatar
James Lamb committed
639

640
641
    # Get handle
    get_handle = function() {
James Lamb's avatar
James Lamb committed
642

643
644
645
646
      # Get handle and construct if needed
      if (lgb.is.null.handle(private$handle)) {
        self$construct()
      }
647
      private$handle
James Lamb's avatar
James Lamb committed
648

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

651
    # Set predictor
Guolin Ke's avatar
Guolin Ke committed
652
    set_predictor = function(predictor) {
James Lamb's avatar
James Lamb committed
653

654
655
      # Return self is identical predictor
      if (identical(private$predictor, predictor)) {
656
        return(invisible(self))
657
      }
James Lamb's avatar
James Lamb committed
658

659
      # Check for empty data
Guolin Ke's avatar
Guolin Ke committed
660
      if (is.null(private$raw_data)) {
661
662
        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
663
      }
James Lamb's avatar
James Lamb committed
664

665
      # Check for empty predictor
Guolin Ke's avatar
Guolin Ke committed
666
      if (!is.null(predictor)) {
James Lamb's avatar
James Lamb committed
667

668
        # Predictor is unknown
Guolin Ke's avatar
Guolin Ke committed
669
        if (!lgb.check.r6.class(predictor, "lgb.Predictor")) {
670
          stop("set_predictor: Can only use lgb.Predictor as predictor")
Guolin Ke's avatar
Guolin Ke committed
671
        }
James Lamb's avatar
James Lamb committed
672

Guolin Ke's avatar
Guolin Ke committed
673
      }
James Lamb's avatar
James Lamb committed
674

675
      # Store predictor
Guolin Ke's avatar
Guolin Ke committed
676
      private$predictor <- predictor
James Lamb's avatar
James Lamb committed
677

678
      # Finalize and return self
Guolin Ke's avatar
Guolin Ke committed
679
      self$finalize()
680
      return(invisible(self))
James Lamb's avatar
James Lamb committed
681

Guolin Ke's avatar
Guolin Ke committed
682
    }
James Lamb's avatar
James Lamb committed
683

Guolin Ke's avatar
Guolin Ke committed
684
685
686
  )
)

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

720
  # Create new dataset
721
722
723
724
725
726
727
728
729
730
731
732
  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
733

Guolin Ke's avatar
Guolin Ke committed
734
735
}

736
737
738
#' @name lgb.Dataset.create.valid
#' @title Construct validation data
#' @description Construct validation data according to training data
Guolin Ke's avatar
Guolin Ke committed
739
740
#' @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
741
#' @param info a list of information of the \code{lgb.Dataset} object
Guolin Ke's avatar
Guolin Ke committed
742
#' @param ... other information to pass to \code{info}.
James Lamb's avatar
James Lamb committed
743
#'
Guolin Ke's avatar
Guolin Ke committed
744
#' @return constructed dataset
James Lamb's avatar
James Lamb committed
745
#'
Guolin Ke's avatar
Guolin Ke committed
746
#' @examples
747
748
749
750
751
752
753
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' data(agaricus.test, package = "lightgbm")
#' test <- agaricus.test
#' dtest <- lgb.Dataset.create.valid(dtrain, test$data, label = test$label)
James Lamb's avatar
James Lamb committed
754
#'
Guolin Ke's avatar
Guolin Ke committed
755
#' @export
756
lgb.Dataset.create.valid <- function(dataset, data, info = list(), ...) {
James Lamb's avatar
James Lamb committed
757

758
  # Check if dataset is not a dataset
759
760
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.create.valid: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
761
  }
James Lamb's avatar
James Lamb committed
762

763
  # Create validation dataset
764
  invisible(dataset$create_valid(data, info, ...))
James Lamb's avatar
James Lamb committed
765

766
}
Guolin Ke's avatar
Guolin Ke committed
767

768
769
770
#' @name lgb.Dataset.construct
#' @title Construct Dataset explicitly
#' @description Construct Dataset explicitly
Guolin Ke's avatar
Guolin Ke committed
771
#' @param dataset Object of class \code{lgb.Dataset}
James Lamb's avatar
James Lamb committed
772
#'
Guolin Ke's avatar
Guolin Ke committed
773
#' @examples
774
775
776
777
778
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
James Lamb's avatar
James Lamb committed
779
#'
Guolin Ke's avatar
Guolin Ke committed
780
781
#' @export
lgb.Dataset.construct <- function(dataset) {
James Lamb's avatar
James Lamb committed
782

783
  # Check if dataset is not a dataset
784
785
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.construct: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
786
  }
James Lamb's avatar
James Lamb committed
787

788
  # Construct the dataset
789
  invisible(dataset$construct())
James Lamb's avatar
James Lamb committed
790

Guolin Ke's avatar
Guolin Ke committed
791
792
}

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

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

823
  # Return dimensions
824
  x$dim()
James Lamb's avatar
James Lamb committed
825

Guolin Ke's avatar
Guolin Ke committed
826
827
}

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

854
  # Check if dataset is not a dataset
855
856
  if (!lgb.is.Dataset(x)) {
    stop("dimnames.lgb.Dataset: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
857
  }
James Lamb's avatar
James Lamb committed
858

859
  # Return dimension names
860
  list(NULL, x$get_colnames())
James Lamb's avatar
James Lamb committed
861

Guolin Ke's avatar
Guolin Ke committed
862
863
864
865
866
}

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

868
869
  # Check if invalid element list
  if (!is.list(value) || length(value) != 2L) {
870
    stop("invalid ", sQuote("value"), " given: must be a list of two elements")
871
  }
James Lamb's avatar
James Lamb committed
872

873
874
875
876
  # Check for unknown row names
  if (!is.null(value[[1L]])) {
    stop("lgb.Dataset does not have rownames")
  }
James Lamb's avatar
James Lamb committed
877

878
  # Check for second value missing
879
  if (is.null(value[[2L]])) {
James Lamb's avatar
James Lamb committed
880

881
    # No column names
Guolin Ke's avatar
Guolin Ke committed
882
883
    x$set_colnames(NULL)
    return(x)
James Lamb's avatar
James Lamb committed
884

885
  }
James Lamb's avatar
James Lamb committed
886

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

898
  # Set column names properly, and return
899
  x$set_colnames(value[[2L]])
900
  x
James Lamb's avatar
James Lamb committed
901

Guolin Ke's avatar
Guolin Ke committed
902
903
}

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

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

931
  # Check if dataset is not a dataset
932
933
  if (!lgb.is.Dataset(dataset)) {
    stop("slice.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
934
  }
James Lamb's avatar
James Lamb committed
935

936
  # Return sliced set
937
  invisible(dataset$slice(idxset, ...))
James Lamb's avatar
James Lamb committed
938

Guolin Ke's avatar
Guolin Ke committed
939
940
}

941
942
943
#' @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
944
945
946
947
#' @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
948
#'
Guolin Ke's avatar
Guolin Ke committed
949
950
#' @details
#' The \code{name} field can be one of the following:
James Lamb's avatar
James Lamb committed
951
#'
Guolin Ke's avatar
Guolin Ke committed
952
953
954
#' \itemize{
#'     \item \code{label}: label lightgbm learn from ;
#'     \item \code{weight}: to do a weight rescale ;
Nikita Titov's avatar
Nikita Titov committed
955
956
#'     \item \code{group}: group size ;
#'     \item \code{init_score}: initial score is the base prediction lightgbm will boost from.
Guolin Ke's avatar
Guolin Ke committed
957
#' }
James Lamb's avatar
James Lamb committed
958
#'
Guolin Ke's avatar
Guolin Ke committed
959
#' @examples
960
961
962
963
964
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
James Lamb's avatar
James Lamb committed
965
#'
966
967
#' labels <- lightgbm::getinfo(dtrain, "label")
#' lightgbm::setinfo(dtrain, "label", 1 - labels)
James Lamb's avatar
James Lamb committed
968
#'
969
970
#' labels2 <- lightgbm::getinfo(dtrain, "label")
#' stopifnot(all(labels2 == 1 - labels))
James Lamb's avatar
James Lamb committed
971
#'
Guolin Ke's avatar
Guolin Ke committed
972
#' @export
973
974
975
getinfo <- function(dataset, ...) {
  UseMethod("getinfo")
}
Guolin Ke's avatar
Guolin Ke committed
976
977
978
979

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

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

986
  # Return information
987
  dataset$getinfo(name)
James Lamb's avatar
James Lamb committed
988

Guolin Ke's avatar
Guolin Ke committed
989
990
}

991
992
993
#' @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
994
#' @param dataset Object of class \code{lgb.Dataset}
Guolin Ke's avatar
Guolin Ke committed
995
996
997
998
#' @param name the name of the field to get
#' @param info the specific field of information to set
#' @param ... other parameters
#' @return passed object
James Lamb's avatar
James Lamb committed
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
#' \itemize{
1004
1005
1006
1007
1008
1009
1010
#'     \item{\code{label}: vector of labels to use as the target variable}
#'     \item{\code{weight}: to do a weight rescale}
#'     \item{\code{init_score}: initial score is the base prediction lightgbm will boost from}
#'     \item{\code{group}: used for learning-to-rank tasks. An integer vector describing how to
#'         group rows together as ordered results from the same set of candidate results to be ranked.
#'         For example, if you have a 1000-row dataset that contains 250 4-document query results,
#'         set this to \code{rep(4L, 250L)}}
Guolin Ke's avatar
Guolin Ke committed
1011
#' }
James Lamb's avatar
James Lamb committed
1012
#'
Guolin Ke's avatar
Guolin Ke committed
1013
#' @examples
1014
1015
1016
1017
1018
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
James Lamb's avatar
James Lamb committed
1019
#'
1020
1021
#' labels <- lightgbm::getinfo(dtrain, "label")
#' lightgbm::setinfo(dtrain, "label", 1 - labels)
James Lamb's avatar
James Lamb committed
1022
#'
1023
1024
#' labels2 <- lightgbm::getinfo(dtrain, "label")
#' stopifnot(all.equal(labels2, 1 - labels))
James Lamb's avatar
James Lamb committed
1025
#'
Guolin Ke's avatar
Guolin Ke committed
1026
#' @export
1027
1028
1029
setinfo <- function(dataset, ...) {
  UseMethod("setinfo")
}
Guolin Ke's avatar
Guolin Ke committed
1030
1031
1032
1033

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

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

1040
  # Set information
1041
  invisible(dataset$setinfo(name, info))
Guolin Ke's avatar
Guolin Ke committed
1042
1043
}

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

1067
  # Check if dataset is not a dataset
1068
1069
1070
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.set.categorical: input dataset should be an lgb.Dataset object")
  }
James Lamb's avatar
James Lamb committed
1071

1072
  # Set categoricals
1073
  invisible(dataset$set_categorical_feature(categorical_feature))
James Lamb's avatar
James Lamb committed
1074

1075
1076
}

1077
1078
1079
#' @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
1080
1081
#' @param dataset object of class \code{lgb.Dataset}
#' @param reference object of class \code{lgb.Dataset}
James Lamb's avatar
James Lamb committed
1082
#'
Guolin Ke's avatar
Guolin Ke committed
1083
#' @return passed dataset
James Lamb's avatar
James Lamb committed
1084
#'
Guolin Ke's avatar
Guolin Ke committed
1085
#' @examples
1086
1087
1088
1089
1090
1091
1092
1093
#' library(lightgbm)
#' data(agaricus.train, package ="lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' data(agaricus.test, package = "lightgbm")
#' test <- agaricus.test
#' dtest <- lgb.Dataset(test$data, test = train$label)
#' lgb.Dataset.set.reference(dtest, dtrain)
James Lamb's avatar
James Lamb committed
1094
#'
Guolin Ke's avatar
Guolin Ke committed
1095
1096
1097
#' @rdname lgb.Dataset.set.reference
#' @export
lgb.Dataset.set.reference <- function(dataset, reference) {
James Lamb's avatar
James Lamb committed
1098

1099
  # Check if dataset is not a dataset
1100
1101
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.set.reference: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1102
  }
James Lamb's avatar
James Lamb committed
1103

1104
  # Set reference
1105
  invisible(dataset$set_reference(reference))
Guolin Ke's avatar
Guolin Ke committed
1106
1107
}

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

1126
  # Check if dataset is not a dataset
1127
1128
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.set: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1129
  }
James Lamb's avatar
James Lamb committed
1130

1131
  # File-type is not matching
1132
1133
  if (!is.character(fname)) {
    stop("lgb.Dataset.set: fname should be a character or a file connection")
Guolin Ke's avatar
Guolin Ke committed
1134
  }
James Lamb's avatar
James Lamb committed
1135

1136
  # Store binary
1137
  invisible(dataset$save_binary(fname))
Guolin Ke's avatar
Guolin Ke committed
1138
}