lgb.Dataset.R 29.7 KB
Newer Older
James Lamb's avatar
James Lamb committed
1
2

#' @importFrom methods is
Guolin Ke's avatar
Guolin Ke committed
3
Dataset <- R6Class(
4
  classname = "lgb.Dataset",
5
  cloneable = FALSE,
Guolin Ke's avatar
Guolin Ke committed
6
  public = list(
James Lamb's avatar
James Lamb committed
7

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

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

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

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

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

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

34
      # Check for additional parameters
35
      additional_params <- list(...)
James Lamb's avatar
James Lamb committed
36

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

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

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

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

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

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

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

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

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

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

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

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

86
      private$categorical_feature <- categorical_feature
87
88
89
90
      private$predictor <- predictor
      private$free_raw_data <- free_raw_data
      private$used_indices <- used_indices
      private$info <- info
James Lamb's avatar
James Lamb committed
91

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
99
100
101
102
103
104
105
106
107
108
      # Create new dataset
      ret <- Dataset$new(data,
                         private$params,
                         self,
                         private$colnames,
                         private$categorical_feature,
                         private$predictor,
                         private$free_raw_data,
                         NULL,
                         info,
                         ...)
James Lamb's avatar
James Lamb committed
109

110
      # Return ret
111
      return(invisible(ret))
James Lamb's avatar
James Lamb committed
112

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

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

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

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

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

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

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

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

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

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

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

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

157
          }
James Lamb's avatar
James Lamb committed
158

159
        # Store indices for categorical features
160
        private$params$categorical_feature <- cate_indices
James Lamb's avatar
James Lamb committed
161

162
      }
James Lamb's avatar
James Lamb committed
163

Guolin Ke's avatar
Guolin Ke committed
164
165
      # Check has header or not
      has_header <- FALSE
166
167
      if (!is.null(private$params$has_header) || !is.null(private$params$header)) {
        if (tolower(as.character(private$params$has_header)) == "true" || tolower(as.character(private$params$header)) == "true") {
Guolin Ke's avatar
Guolin Ke committed
168
169
170
          has_header <- TRUE
        }
      }
James Lamb's avatar
James Lamb committed
171

Guolin Ke's avatar
Guolin Ke committed
172
173
      # Generate parameter str
      params_str <- lgb.params2str(private$params)
James Lamb's avatar
James Lamb committed
174

175
      # Get handle of reference dataset
Guolin Ke's avatar
Guolin Ke committed
176
177
178
179
      ref_handle <- NULL
      if (!is.null(private$reference)) {
        ref_handle <- private$reference$.__enclos_env__$private$get_handle()
      }
180
      handle <- NA_real_
James Lamb's avatar
James Lamb committed
181

182
      # Not subsetting
Guolin Ke's avatar
Guolin Ke committed
183
      if (is.null(private$used_indices)) {
James Lamb's avatar
James Lamb committed
184

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

188
189
190
191
192
          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
193

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

196
197
198
199
200
201
202
203
          # Are we using a matrix?
          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
204
205

        } else if (methods::is(private$raw_data, "dgCMatrix")) {
206
207
208
          if (length(private$raw_data@p) > 2147483647) {
            stop("Cannot support large CSC matrix")
          }
209
210
211
212
213
214
215
216
217
218
219
          # Are we using a dgCMatrix (sparsed matrix column compressed)
          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
220

Guolin Ke's avatar
Guolin Ke committed
221
        } else {
James Lamb's avatar
James Lamb committed
222

223
224
          # Unknown data type
          stop("lgb.Dataset.construct: does not support constructing from ", sQuote(class(private$raw_data)))
James Lamb's avatar
James Lamb committed
225

Guolin Ke's avatar
Guolin Ke committed
226
        }
James Lamb's avatar
James Lamb committed
227

Guolin Ke's avatar
Guolin Ke committed
228
      } else {
James Lamb's avatar
James Lamb committed
229

230
        # Reference is empty
Guolin Ke's avatar
Guolin Ke committed
231
        if (is.null(private$reference)) {
232
          stop("lgb.Dataset.construct: reference cannot be NULL for constructing data subset")
Guolin Ke's avatar
Guolin Ke committed
233
        }
James Lamb's avatar
James Lamb committed
234

235
236
237
238
        # Construct subset
        handle <- lgb.call("LGBM_DatasetGetSubset_R",
                           ret = handle,
                           ref_handle,
239
                           c(private$used_indices), # Adding c() fixes issue in R v3.5
240
241
                           length(private$used_indices),
                           params_str)
James Lamb's avatar
James Lamb committed
242

Guolin Ke's avatar
Guolin Ke committed
243
      }
Guolin Ke's avatar
Guolin Ke committed
244
245
246
      if (lgb.is.null.handle(handle)) {
        stop("lgb.Dataset.construct: cannot create Dataset handle")
      }
247
      # Setup class and private type
Guolin Ke's avatar
Guolin Ke committed
248
249
      class(handle) <- "lgb.Dataset.handle"
      private$handle <- handle
James Lamb's avatar
James Lamb committed
250

251
252
253
254
      # Set feature names
      if (!is.null(private$colnames)) {
        self$set_colnames(private$colnames)
      }
255

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

259
        # Setup initial scores
260
        init_score <- private$predictor$predict(private$raw_data, rawscore = TRUE, reshape = TRUE)
James Lamb's avatar
James Lamb committed
261

262
        # Not needed to transpose, for is col_marjor
Guolin Ke's avatar
Guolin Ke committed
263
264
        init_score <- as.vector(init_score)
        private$info$init_score <- init_score
James Lamb's avatar
James Lamb committed
265

266
      }
James Lamb's avatar
James Lamb committed
267

268
269
270
      # Should we free raw data?
      if (isTRUE(private$free_raw_data)) {
        private$raw_data <- NULL
Guolin Ke's avatar
Guolin Ke committed
271
      }
James Lamb's avatar
James Lamb committed
272

273
      # Get private information
Guolin Ke's avatar
Guolin Ke committed
274
      if (length(private$info) > 0) {
James Lamb's avatar
James Lamb committed
275

276
        # Set infos
277
        for (i in seq_along(private$info)) {
James Lamb's avatar
James Lamb committed
278

Guolin Ke's avatar
Guolin Ke committed
279
280
          p <- private$info[i]
          self$setinfo(names(p), p[[1]])
James Lamb's avatar
James Lamb committed
281

Guolin Ke's avatar
Guolin Ke committed
282
        }
James Lamb's avatar
James Lamb committed
283

Guolin Ke's avatar
Guolin Ke committed
284
      }
James Lamb's avatar
James Lamb committed
285

286
      # Get label information existence
Guolin Ke's avatar
Guolin Ke committed
287
288
289
      if (is.null(self$getinfo("label"))) {
        stop("lgb.Dataset.construct: label should be set")
      }
James Lamb's avatar
James Lamb committed
290

291
292
      # Return self
      return(invisible(self))
James Lamb's avatar
James Lamb committed
293

Guolin Ke's avatar
Guolin Ke committed
294
    },
James Lamb's avatar
James Lamb committed
295

296
    # Dimension function
Guolin Ke's avatar
Guolin Ke committed
297
    dim = function() {
James Lamb's avatar
James Lamb committed
298

299
      # Check for handle
Guolin Ke's avatar
Guolin Ke committed
300
      if (!lgb.is.null.handle(private$handle)) {
James Lamb's avatar
James Lamb committed
301

302
303
        num_row <- 0L
        num_col <- 0L
James Lamb's avatar
James Lamb committed
304

305
306
307
        # 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
308
309
310

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

311
        # Check if dgCMatrix (sparse matrix column compressed)
312
        dim(private$raw_data)
James Lamb's avatar
James Lamb committed
313

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

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

Guolin Ke's avatar
Guolin Ke committed
319
      }
James Lamb's avatar
James Lamb committed
320

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

323
    # Get column names
Guolin Ke's avatar
Guolin Ke committed
324
    get_colnames = function() {
James Lamb's avatar
James Lamb committed
325

326
      # Check for handle
Guolin Ke's avatar
Guolin Ke committed
327
      if (!lgb.is.null.handle(private$handle)) {
James Lamb's avatar
James Lamb committed
328

329
        # Get feature names and write them
330
331
332
        cnames <- lgb.call.return.str("LGBM_DatasetGetFeatureNames_R", private$handle)
        private$colnames <- as.character(base::strsplit(cnames, "\t")[[1]])
        private$colnames
James Lamb's avatar
James Lamb committed
333
334
335

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

336
        # Check if dgCMatrix (sparse matrix column compressed)
337
        colnames(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
342
        # Trying to work with unknown dimensions is not possible
        stop("dim: cannot get dimensions before dataset has been constructed, please call lgb.Dataset.construct explicitly")
James Lamb's avatar
James Lamb committed
343

Guolin Ke's avatar
Guolin Ke committed
344
      }
James Lamb's avatar
James Lamb committed
345

Guolin Ke's avatar
Guolin Ke committed
346
    },
James Lamb's avatar
James Lamb committed
347

348
    # Set column names
Guolin Ke's avatar
Guolin Ke committed
349
    set_colnames = function(colnames) {
James Lamb's avatar
James Lamb committed
350

351
352
      # Check column names non-existence
      if (is.null(colnames)) {
353
        return(invisible(self))
354
      }
James Lamb's avatar
James Lamb committed
355

356
      # Check empty column names
Guolin Ke's avatar
Guolin Ke committed
357
      colnames <- as.character(colnames)
358
      if (length(colnames) == 0) {
359
        return(invisible(self))
360
      }
James Lamb's avatar
James Lamb committed
361

362
      # Write column names
Guolin Ke's avatar
Guolin Ke committed
363
364
      private$colnames <- colnames
      if (!lgb.is.null.handle(private$handle)) {
James Lamb's avatar
James Lamb committed
365

366
        # Merge names with tab separation
Guolin Ke's avatar
Guolin Ke committed
367
368
369
370
371
        merged_name <- paste0(as.list(private$colnames), collapse = "\t")
        lgb.call("LGBM_DatasetSetFeatureNames_R",
                 ret = NULL,
                 private$handle,
                 lgb.c_str(merged_name))
James Lamb's avatar
James Lamb committed
372

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

375
      # Return self
376
      return(invisible(self))
James Lamb's avatar
James Lamb committed
377

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

380
    # Get information
Guolin Ke's avatar
Guolin Ke committed
381
    getinfo = function(name) {
James Lamb's avatar
James Lamb committed
382

383
      # Create known attributes list
384
      INFONAMES <- c("label", "weight", "init_score", "group")
James Lamb's avatar
James Lamb committed
385

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

391
      # Check for info name and handle
392
393
394
395
      if (is.null(private$info[[name]])) {
        if (lgb.is.null.handle(private$handle)){
          stop("Cannot perform getinfo before construct Dataset.")
        }
396
        # Get field size of info
397
        info_len <- 0L
398
399
400
401
        info_len <- lgb.call("LGBM_DatasetGetFieldSize_R",
                             ret = info_len,
                             private$handle,
                             lgb.c_str(name))
James Lamb's avatar
James Lamb committed
402

403
        # Check if info is not empty
Guolin Ke's avatar
Guolin Ke committed
404
        if (info_len > 0) {
James Lamb's avatar
James Lamb committed
405

406
          # Get back fields
Guolin Ke's avatar
Guolin Ke committed
407
          ret <- NULL
408
409
410
411
412
          ret <- if (name == "group") {
            integer(info_len) # Integer
          } else {
            numeric(info_len) # Numeric
          }
James Lamb's avatar
James Lamb committed
413

414
415
416
417
          ret <- lgb.call("LGBM_DatasetGetField_R",
                          ret = ret,
                          private$handle,
                          lgb.c_str(name))
James Lamb's avatar
James Lamb committed
418

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

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

424
      private$info[[name]]
James Lamb's avatar
James Lamb committed
425

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

428
    # Set information
Guolin Ke's avatar
Guolin Ke committed
429
    setinfo = function(name, info) {
James Lamb's avatar
James Lamb committed
430

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

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

439
440
441
442
443
444
      # 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
445

446
      # Store information privately
Guolin Ke's avatar
Guolin Ke committed
447
      private$info[[name]] <- info
James Lamb's avatar
James Lamb committed
448

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

Guolin Ke's avatar
Guolin Ke committed
451
        if (length(info) > 0) {
James Lamb's avatar
James Lamb committed
452

453
454
455
456
457
458
          lgb.call("LGBM_DatasetSetField_R",
                   ret = NULL,
                   private$handle,
                   lgb.c_str(name),
                   info,
                   length(info))
James Lamb's avatar
James Lamb committed
459

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

Guolin Ke's avatar
Guolin Ke committed
462
      }
James Lamb's avatar
James Lamb committed
463

464
      # Return self
465
      return(invisible(self))
James Lamb's avatar
James Lamb committed
466

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

469
    # Slice dataset
Guolin Ke's avatar
Guolin Ke committed
470
    slice = function(idxset, ...) {
James Lamb's avatar
James Lamb committed
471

472
473
474
475
476
477
478
479
480
481
482
      # Perform slicing
      Dataset$new(NULL,
                  private$params,
                  self,
                  private$colnames,
                  private$categorical_feature,
                  private$predictor,
                  private$free_raw_data,
                  idxset,
                  NULL,
                  ...)
James Lamb's avatar
James Lamb committed
483

Guolin Ke's avatar
Guolin Ke committed
484
    },
James Lamb's avatar
James Lamb committed
485

486
    # Update parameters
487
    update_params = function(params) {
James Lamb's avatar
James Lamb committed
488

489
      # Parameter updating
Guolin Ke's avatar
Guolin Ke committed
490
      private$params <- modifyList(private$params, params)
491
      return(invisible(self))
James Lamb's avatar
James Lamb committed
492

Guolin Ke's avatar
Guolin Ke committed
493
    },
James Lamb's avatar
James Lamb committed
494

495
    # Set categorical feature parameter
496
    set_categorical_feature = function(categorical_feature) {
James Lamb's avatar
James Lamb committed
497

498
499
      # Check for identical input
      if (identical(private$categorical_feature, categorical_feature)) {
500
        return(invisible(self))
501
      }
James Lamb's avatar
James Lamb committed
502

503
      # Check for empty data
504
      if (is.null(private$raw_data)) {
505
506
        stop("set_categorical_feature: cannot set categorical feature after freeing raw data,
          please set ", sQuote("free_raw_data = FALSE"), " when you construct lgb.Dataset")
507
      }
James Lamb's avatar
James Lamb committed
508

509
      # Overwrite categorical features
510
      private$categorical_feature <- categorical_feature
James Lamb's avatar
James Lamb committed
511

512
      # Finalize and return self
513
      self$finalize()
514
      return(invisible(self))
James Lamb's avatar
James Lamb committed
515

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

518
    # Set reference
Guolin Ke's avatar
Guolin Ke committed
519
    set_reference = function(reference) {
James Lamb's avatar
James Lamb committed
520

521
      # Set known references
522
      self$set_categorical_feature(reference$.__enclos_env__$private$categorical_feature)
Guolin Ke's avatar
Guolin Ke committed
523
524
      self$set_colnames(reference$get_colnames())
      private$set_predictor(reference$.__enclos_env__$private$predictor)
James Lamb's avatar
James Lamb committed
525

526
527
      # Check for identical references
      if (identical(private$reference, reference)) {
528
        return(invisible(self))
529
      }
James Lamb's avatar
James Lamb committed
530

531
      # Check for empty data
Guolin Ke's avatar
Guolin Ke committed
532
      if (is.null(private$raw_data)) {
James Lamb's avatar
James Lamb committed
533

534
535
        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
536

Guolin Ke's avatar
Guolin Ke committed
537
      }
James Lamb's avatar
James Lamb committed
538

539
      # Check for non-existing reference
Guolin Ke's avatar
Guolin Ke committed
540
      if (!is.null(reference)) {
James Lamb's avatar
James Lamb committed
541

542
        # Reference is unknown
Guolin Ke's avatar
Guolin Ke committed
543
        if (!lgb.check.r6.class(reference, "lgb.Dataset")) {
544
          stop("set_reference: Can only use lgb.Dataset as a reference")
Guolin Ke's avatar
Guolin Ke committed
545
        }
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
      # Store reference
Guolin Ke's avatar
Guolin Ke committed
550
      private$reference <- reference
James Lamb's avatar
James Lamb committed
551

552
      # Finalize and return self
Guolin Ke's avatar
Guolin Ke committed
553
      self$finalize()
554
      return(invisible(self))
James Lamb's avatar
James Lamb committed
555

Guolin Ke's avatar
Guolin Ke committed
556
    },
James Lamb's avatar
James Lamb committed
557

558
    # Save binary model
Guolin Ke's avatar
Guolin Ke committed
559
    save_binary = function(fname) {
James Lamb's avatar
James Lamb committed
560

561
      # Store binary data
Guolin Ke's avatar
Guolin Ke committed
562
563
564
565
566
      self$construct()
      lgb.call("LGBM_DatasetSaveBinary_R",
               ret = NULL,
               private$handle,
               lgb.c_str(fname))
567
      return(invisible(self))
Guolin Ke's avatar
Guolin Ke committed
568
    }
James Lamb's avatar
James Lamb committed
569

Guolin Ke's avatar
Guolin Ke committed
570
571
  ),
  private = list(
572
573
574
575
576
    handle = NULL,
    raw_data = NULL,
    params = list(),
    reference = NULL,
    colnames = NULL,
577
    categorical_feature = NULL,
578
579
580
581
    predictor = NULL,
    free_raw_data = TRUE,
    used_indices = NULL,
    info = NULL,
James Lamb's avatar
James Lamb committed
582

583
584
    # Get handle
    get_handle = function() {
James Lamb's avatar
James Lamb committed
585

586
587
588
589
      # Get handle and construct if needed
      if (lgb.is.null.handle(private$handle)) {
        self$construct()
      }
590
      private$handle
James Lamb's avatar
James Lamb committed
591

Guolin Ke's avatar
Guolin Ke committed
592
    },
James Lamb's avatar
James Lamb committed
593

594
    # Set predictor
Guolin Ke's avatar
Guolin Ke committed
595
    set_predictor = function(predictor) {
James Lamb's avatar
James Lamb committed
596

597
598
      # Return self is identical predictor
      if (identical(private$predictor, predictor)) {
599
        return(invisible(self))
600
      }
James Lamb's avatar
James Lamb committed
601

602
      # Check for empty data
Guolin Ke's avatar
Guolin Ke committed
603
      if (is.null(private$raw_data)) {
604
605
        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
606
      }
James Lamb's avatar
James Lamb committed
607

608
      # Check for empty predictor
Guolin Ke's avatar
Guolin Ke committed
609
      if (!is.null(predictor)) {
James Lamb's avatar
James Lamb committed
610

611
        # Predictor is unknown
Guolin Ke's avatar
Guolin Ke committed
612
        if (!lgb.check.r6.class(predictor, "lgb.Predictor")) {
613
          stop("set_predictor: Can only use lgb.Predictor as predictor")
Guolin Ke's avatar
Guolin Ke committed
614
        }
James Lamb's avatar
James Lamb committed
615

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

618
      # Store predictor
Guolin Ke's avatar
Guolin Ke committed
619
      private$predictor <- predictor
James Lamb's avatar
James Lamb committed
620

621
      # Finalize and return self
Guolin Ke's avatar
Guolin Ke committed
622
      self$finalize()
623
      return(invisible(self))
James Lamb's avatar
James Lamb committed
624

Guolin Ke's avatar
Guolin Ke committed
625
    }
James Lamb's avatar
James Lamb committed
626

Guolin Ke's avatar
Guolin Ke committed
627
628
629
  )
)

wxchan's avatar
wxchan committed
630
#' Construct lgb.Dataset object
Guolin Ke's avatar
Guolin Ke committed
631
#'
wxchan's avatar
wxchan committed
632
#' Construct lgb.Dataset object from dense matrix, sparse matrix
Guolin Ke's avatar
Guolin Ke committed
633
634
635
636
637
638
#' or local file (that was created previously by saving an \code{lgb.Dataset}).
#'
#' @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
639
#' @param categorical_feature categorical features
Guolin Ke's avatar
Guolin Ke committed
640
641
642
#' @param free_raw_data TRUE for need to free raw data after construct
#' @param info a list of information of the lgb.Dataset object
#' @param ... other information to pass to \code{info} or parameters pass to \code{params}
James Lamb's avatar
James Lamb committed
643
#'
Guolin Ke's avatar
Guolin Ke committed
644
#' @return constructed dataset
James Lamb's avatar
James Lamb committed
645
#'
Guolin Ke's avatar
Guolin Ke committed
646
#' @examples
647
#' \dontrun{
648
649
650
651
652
653
654
#' 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)
655
#' }
James Lamb's avatar
James Lamb committed
656
#'
Guolin Ke's avatar
Guolin Ke committed
657
658
#' @export
lgb.Dataset <- function(data,
659
660
661
                        params = list(),
                        reference = NULL,
                        colnames = NULL,
662
                        categorical_feature = NULL,
663
664
                        free_raw_data = TRUE,
                        info = list(),
Guolin Ke's avatar
Guolin Ke committed
665
                        ...) {
James Lamb's avatar
James Lamb committed
666

667
  # Create new dataset
668
  invisible(Dataset$new(data,
669
670
671
672
673
674
675
676
              params,
              reference,
              colnames,
              categorical_feature,
              NULL,
              free_raw_data,
              NULL,
              info,
677
              ...))
James Lamb's avatar
James Lamb committed
678

Guolin Ke's avatar
Guolin Ke committed
679
680
}

wxchan's avatar
wxchan committed
681
#' Construct validation data
James Lamb's avatar
James Lamb committed
682
#'
wxchan's avatar
wxchan committed
683
#' Construct validation data according to training data
James Lamb's avatar
James Lamb committed
684
#'
Guolin Ke's avatar
Guolin Ke committed
685
686
687
688
#' @param dataset \code{lgb.Dataset} object, training data
#' @param data a \code{matrix} object, a \code{dgCMatrix} object or a character representing a filename
#' @param info a list of information of the lgb.Dataset object
#' @param ... other information to pass to \code{info}.
James Lamb's avatar
James Lamb committed
689
#'
Guolin Ke's avatar
Guolin Ke committed
690
#' @return constructed dataset
James Lamb's avatar
James Lamb committed
691
#'
Guolin Ke's avatar
Guolin Ke committed
692
#' @examples
693
#' \dontrun{
694
695
696
697
698
699
700
#' 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)
701
#' }
James Lamb's avatar
James Lamb committed
702
#'
Guolin Ke's avatar
Guolin Ke committed
703
#' @export
704
lgb.Dataset.create.valid <- function(dataset, data, info = list(), ...) {
James Lamb's avatar
James Lamb committed
705

706
  # Check if dataset is not a dataset
707
708
  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
709
  }
James Lamb's avatar
James Lamb committed
710

711
  # Create validation dataset
712
  invisible(dataset$create_valid(data, info, ...))
James Lamb's avatar
James Lamb committed
713

714
}
Guolin Ke's avatar
Guolin Ke committed
715

716
#' Construct Dataset explicitly
James Lamb's avatar
James Lamb committed
717
#'
Guolin Ke's avatar
Guolin Ke committed
718
#' @param dataset Object of class \code{lgb.Dataset}
James Lamb's avatar
James Lamb committed
719
#'
Guolin Ke's avatar
Guolin Ke committed
720
#' @examples
721
#' \dontrun{
722
723
724
725
726
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.construct(dtrain)
727
#' }
James Lamb's avatar
James Lamb committed
728
#'
Guolin Ke's avatar
Guolin Ke committed
729
730
#' @export
lgb.Dataset.construct <- function(dataset) {
James Lamb's avatar
James Lamb committed
731

732
  # Check if dataset is not a dataset
733
734
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.construct: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
735
  }
James Lamb's avatar
James Lamb committed
736

737
  # Construct the dataset
738
  invisible(dataset$construct())
James Lamb's avatar
James Lamb committed
739

Guolin Ke's avatar
Guolin Ke committed
740
741
}

742
#' Dimensions of an lgb.Dataset
James Lamb's avatar
James Lamb committed
743
#'
Guolin Ke's avatar
Guolin Ke committed
744
745
746
#' Returns a vector of numbers of rows and of columns in an \code{lgb.Dataset}.
#' @param x Object of class \code{lgb.Dataset}
#' @param ... other parameters
James Lamb's avatar
James Lamb committed
747
#'
Guolin Ke's avatar
Guolin Ke committed
748
#' @return a vector of numbers of rows and of columns
James Lamb's avatar
James Lamb committed
749
#'
Guolin Ke's avatar
Guolin Ke committed
750
751
752
#' @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
753
#'
Guolin Ke's avatar
Guolin Ke committed
754
#' @examples
755
756
757
758
759
#' \dontrun{
#' 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
760
#'
761
762
763
#' stopifnot(nrow(dtrain) == nrow(train$data))
#' stopifnot(ncol(dtrain) == ncol(train$data))
#' stopifnot(all(dim(dtrain) == dim(train$data)))
764
#' }
James Lamb's avatar
James Lamb committed
765
#'
Guolin Ke's avatar
Guolin Ke committed
766
767
768
#' @rdname dim
#' @export
dim.lgb.Dataset <- function(x, ...) {
James Lamb's avatar
James Lamb committed
769

770
  # Check if dataset is not a dataset
771
772
  if (!lgb.is.Dataset(x)) {
    stop("dim.lgb.Dataset: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
773
  }
James Lamb's avatar
James Lamb committed
774

775
  # Return dimensions
776
  x$dim()
James Lamb's avatar
James Lamb committed
777

Guolin Ke's avatar
Guolin Ke committed
778
779
780
781
782
}

#' Handling of column names of \code{lgb.Dataset}
#'
#' Only column names are supported for \code{lgb.Dataset}, thus setting of
783
#' row names would have no effect and returned row names would be NULL.
Guolin Ke's avatar
Guolin Ke committed
784
785
786
787
788
789
790
791
792
793
#'
#' @param x object of class \code{lgb.Dataset}
#' @param value a list of two elements: the first one is ignored
#'        and the second one is column names
#'
#' @details
#' Generic \code{dimnames} methods are used by \code{colnames}.
#' Since row names are irrelevant, it is recommended to use \code{colnames} directly.
#'
#' @examples
794
795
796
797
798
799
800
801
802
803
#' \dontrun{
#' 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)
#' colnames(dtrain) <- make.names(1:ncol(train$data))
#' print(dtrain, verbose = TRUE)
804
#' }
James Lamb's avatar
James Lamb committed
805
#'
Guolin Ke's avatar
Guolin Ke committed
806
807
808
#' @rdname dimnames.lgb.Dataset
#' @export
dimnames.lgb.Dataset <- function(x) {
James Lamb's avatar
James Lamb committed
809

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

815
  # Return dimension names
816
  list(NULL, x$get_colnames())
James Lamb's avatar
James Lamb committed
817

Guolin Ke's avatar
Guolin Ke committed
818
819
820
821
822
}

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

824
825
  # Check if invalid element list
  if (!is.list(value) || length(value) != 2L) {
826
    stop("invalid ", sQuote("value"), " given: must be a list of two elements")
827
  }
James Lamb's avatar
James Lamb committed
828

829
830
831
832
  # Check for unknown row names
  if (!is.null(value[[1L]])) {
    stop("lgb.Dataset does not have rownames")
  }
James Lamb's avatar
James Lamb committed
833

834
  # Check for second value missing
Guolin Ke's avatar
Guolin Ke committed
835
  if (is.null(value[[2]])) {
James Lamb's avatar
James Lamb committed
836

837
    # No column names
Guolin Ke's avatar
Guolin Ke committed
838
839
    x$set_colnames(NULL)
    return(x)
James Lamb's avatar
James Lamb committed
840

841
  }
James Lamb's avatar
James Lamb committed
842

843
844
845
  # Check for unmatching column size
  if (ncol(x) != length(value[[2]])) {
    stop("can't assign ", sQuote(length(value[[2]])), " colnames to an lgb.Dataset with ", sQuote(ncol(x)), " columns")
Guolin Ke's avatar
Guolin Ke committed
846
  }
James Lamb's avatar
James Lamb committed
847

848
  # Set column names properly, and return
Guolin Ke's avatar
Guolin Ke committed
849
  x$set_colnames(value[[2]])
850
  x
James Lamb's avatar
James Lamb committed
851

Guolin Ke's avatar
Guolin Ke committed
852
853
}

854
#' Slice a dataset
James Lamb's avatar
James Lamb committed
855
#'
856
#' Get a new \code{lgb.Dataset} containing the specified rows of
Guolin Ke's avatar
Guolin Ke committed
857
#' orginal lgb.Dataset object
James Lamb's avatar
James Lamb committed
858
#'
Guolin Ke's avatar
Guolin Ke committed
859
860
861
862
#' @param dataset Object of class "lgb.Dataset"
#' @param idxset a integer vector of indices of rows needed
#' @param ... other parameters (currently not used)
#' @return constructed sub dataset
James Lamb's avatar
James Lamb committed
863
#'
Guolin Ke's avatar
Guolin Ke committed
864
#' @examples
865
#' \dontrun{
866
867
868
869
#' 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
870
#'
871
872
#' dsub <- lightgbm::slice(dtrain, 1:42)
#' labels <- lightgbm::getinfo(dsub, "label")
873
#' }
James Lamb's avatar
James Lamb committed
874
#'
Guolin Ke's avatar
Guolin Ke committed
875
#' @export
876
877
878
slice <- function(dataset, ...) {
  UseMethod("slice")
}
Guolin Ke's avatar
Guolin Ke committed
879
880
881
882

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

884
  # Check if dataset is not a dataset
885
886
  if (!lgb.is.Dataset(dataset)) {
    stop("slice.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
887
  }
James Lamb's avatar
James Lamb committed
888

889
  # Return sliced set
890
  invisible(dataset$slice(idxset, ...))
James Lamb's avatar
James Lamb committed
891

Guolin Ke's avatar
Guolin Ke committed
892
893
894
}

#' Get information of an lgb.Dataset object
James Lamb's avatar
James Lamb committed
895
#'
Guolin Ke's avatar
Guolin Ke committed
896
897
898
899
#' @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
900
#'
Guolin Ke's avatar
Guolin Ke committed
901
902
#' @details
#' The \code{name} field can be one of the following:
James Lamb's avatar
James Lamb committed
903
#'
Guolin Ke's avatar
Guolin Ke committed
904
905
906
907
908
909
#' \itemize{
#'     \item \code{label}: label lightgbm learn from ;
#'     \item \code{weight}: to do a weight rescale ;
#'     \item \code{group}: group size
#'     \item \code{init_score}: initial score is the base prediction lightgbm will boost from ;
#' }
James Lamb's avatar
James Lamb committed
910
#'
Guolin Ke's avatar
Guolin Ke committed
911
#' @examples
912
#' \dontrun{
913
914
915
916
917
#' 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
918
#'
919
920
#' labels <- lightgbm::getinfo(dtrain, "label")
#' lightgbm::setinfo(dtrain, "label", 1 - labels)
James Lamb's avatar
James Lamb committed
921
#'
922
923
#' labels2 <- lightgbm::getinfo(dtrain, "label")
#' stopifnot(all(labels2 == 1 - labels))
924
#' }
James Lamb's avatar
James Lamb committed
925
#'
Guolin Ke's avatar
Guolin Ke committed
926
#' @export
927
928
929
getinfo <- function(dataset, ...) {
  UseMethod("getinfo")
}
Guolin Ke's avatar
Guolin Ke committed
930
931
932
933

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

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

940
  # Return information
941
  dataset$getinfo(name)
James Lamb's avatar
James Lamb committed
942

Guolin Ke's avatar
Guolin Ke committed
943
944
945
}

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

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

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

992
  # Set information
993
  invisible(dataset$setinfo(name, info))
Guolin Ke's avatar
Guolin Ke committed
994
995
}

996
#' Set categorical feature of \code{lgb.Dataset}
James Lamb's avatar
James Lamb committed
997
#'
998
999
#' @param dataset object of class \code{lgb.Dataset}
#' @param categorical_feature categorical features
James Lamb's avatar
James Lamb committed
1000
#'
1001
#' @return passed dataset
James Lamb's avatar
James Lamb committed
1002
#'
1003
1004
#' @examples
#' \dontrun{
1005
1006
1007
1008
1009
1010
1011
#' 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.set.categorical(dtrain, 1:2)
1012
#' }
James Lamb's avatar
James Lamb committed
1013
#'
1014
1015
1016
#' @rdname lgb.Dataset.set.categorical
#' @export
lgb.Dataset.set.categorical <- function(dataset, categorical_feature) {
James Lamb's avatar
James Lamb committed
1017

1018
  # Check if dataset is not a dataset
1019
1020
1021
  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
1022

1023
  # Set categoricals
1024
  invisible(dataset$set_categorical_feature(categorical_feature))
James Lamb's avatar
James Lamb committed
1025

1026
1027
}

1028
#' Set reference of \code{lgb.Dataset}
James Lamb's avatar
James Lamb committed
1029
#'
1030
#' If you want to use validation data, you should set reference to training data
James Lamb's avatar
James Lamb committed
1031
#'
Guolin Ke's avatar
Guolin Ke committed
1032
1033
#' @param dataset object of class \code{lgb.Dataset}
#' @param reference object of class \code{lgb.Dataset}
James Lamb's avatar
James Lamb committed
1034
#'
Guolin Ke's avatar
Guolin Ke committed
1035
#' @return passed dataset
James Lamb's avatar
James Lamb committed
1036
#'
Guolin Ke's avatar
Guolin Ke committed
1037
#' @examples
1038
#' \dontrun{
1039
1040
1041
1042
1043
1044
1045
1046
#' 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)
1047
#' }
James Lamb's avatar
James Lamb committed
1048
#'
Guolin Ke's avatar
Guolin Ke committed
1049
1050
1051
#' @rdname lgb.Dataset.set.reference
#' @export
lgb.Dataset.set.reference <- function(dataset, reference) {
James Lamb's avatar
James Lamb committed
1052

1053
  # Check if dataset is not a dataset
1054
1055
  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
1056
  }
James Lamb's avatar
James Lamb committed
1057

1058
  # Set reference
1059
  invisible(dataset$set_reference(reference))
Guolin Ke's avatar
Guolin Ke committed
1060
1061
}

1062
#' Save \code{lgb.Dataset} to a binary file
James Lamb's avatar
James Lamb committed
1063
#'
Guolin Ke's avatar
Guolin Ke committed
1064
1065
#' @param dataset object of class \code{lgb.Dataset}
#' @param fname object filename of output file
James Lamb's avatar
James Lamb committed
1066
#'
Guolin Ke's avatar
Guolin Ke committed
1067
#' @return passed dataset
James Lamb's avatar
James Lamb committed
1068
#'
Guolin Ke's avatar
Guolin Ke committed
1069
#' @examples
James Lamb's avatar
James Lamb committed
1070
#'
1071
#' \dontrun{
1072
1073
1074
1075
1076
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' lgb.Dataset.save(dtrain, "data.bin")
1077
#' }
James Lamb's avatar
James Lamb committed
1078
#'
Guolin Ke's avatar
Guolin Ke committed
1079
1080
1081
#' @rdname lgb.Dataset.save
#' @export
lgb.Dataset.save <- function(dataset, fname) {
James Lamb's avatar
James Lamb committed
1082

1083
  # Check if dataset is not a dataset
1084
1085
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.set: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
1086
  }
James Lamb's avatar
James Lamb committed
1087

1088
  # File-type is not matching
1089
1090
  if (!is.character(fname)) {
    stop("lgb.Dataset.set: fname should be a character or a file connection")
Guolin Ke's avatar
Guolin Ke committed
1091
  }
James Lamb's avatar
James Lamb committed
1092

1093
  # Store binary
1094
  invisible(dataset$save_binary(fname))
Guolin Ke's avatar
Guolin Ke committed
1095
}