lgb.Dataset.R 21.4 KB
Newer Older
Guolin Ke's avatar
Guolin Ke committed
1
2
Dataset <- R6Class(
  "lgb.Dataset",
3
  cloneable = FALSE,
Guolin Ke's avatar
Guolin Ke committed
4
5
6
7
8
9
10
11
  public = list(
    finalize = function() {
      if (!lgb.is.null.handle(private$handle)) {
        lgb.call("LGBM_DatasetFree_R", ret = NULL, private$handle)
        private$handle <- NULL
      }
    },
    initialize = function(data,
12
13
14
15
16
17
18
                          params              = list(),
                          reference           = NULL,
                          colnames            = NULL,
                          predictor           = NULL,
                          free_raw_data       = TRUE,
                          used_indices        = NULL,
                          info                = list(),
Guolin Ke's avatar
Guolin Ke committed
19
                          ...) {
20
21
22
23
24
      additional_params <- list(...)
      INFO_KEYS <- c('label', 'weight', 'init_score', 'group')
      for (key in names(additional_params)) {
        if (key %in% INFO_KEYS) {
          info[[key]] <- additional_params[[key]]
Guolin Ke's avatar
Guolin Ke committed
25
        } else {
26
          params[[key]] <- additional_params[[key]]
Guolin Ke's avatar
Guolin Ke committed
27
28
29
30
        }
      }
      if (!is.null(reference)) {
        if (!lgb.check.r6.class(reference, "lgb.Dataset")) {
31
          stop("lgb.Dataset: Can only use ", sQuote("lgb.Dataset"), " as reference")
Guolin Ke's avatar
Guolin Ke committed
32
33
34
35
        }
      }
      if (!is.null(predictor)) {
        if (!lgb.check.r6.class(predictor, "lgb.Predictor")) {
36
          stop("lgb.Dataset: Only can use ", sQuote("lgb.Predictor"), " as predictor")
Guolin Ke's avatar
Guolin Ke committed
37
38
        }
      }
39
40
      private$raw_data  <- data
      private$params    <- params
Guolin Ke's avatar
Guolin Ke committed
41
      private$reference <- reference
42
43
44
45
46
47
      private$colnames  <- colnames

      private$predictor           <- predictor
      private$free_raw_data       <- free_raw_data
      private$used_indices        <- used_indices
      private$info                <- info
Guolin Ke's avatar
Guolin Ke committed
48
49
50
51
52
53
54
55
56
57
58
59
60
    },
    create_valid = function(data, info = list(),  ...) {
      ret <- Dataset$new(
        data,
        private$params,
        self,
        private$colnames,
        private$predictor,
        private$free_raw_data,
        NULL,
        info,
        ...
      )
61
      ret
Guolin Ke's avatar
Guolin Ke committed
62
63
64
65
66
67
68
    },
    construct = function() {
      if (!lgb.is.null.handle(private$handle)) {
        return(self)
      }
      # Get feature names
      cnames <- NULL
69
      if (is.matrix(private$raw_data) || is(private$raw_data, "dgCMatrix")) {
Guolin Ke's avatar
Guolin Ke committed
70
71
72
        cnames <- colnames(private$raw_data)
      }
      # set feature names if not exist
73
      if (is.null(private$colnames) && !is.null(cnames)) {
Guolin Ke's avatar
Guolin Ke committed
74
75
76
77
        private$colnames <- as.character(cnames)
      }
      # Check has header or not
      has_header <- FALSE
78
      if (!is.null(private$params$has_header) ||
Guolin Ke's avatar
Guolin Ke committed
79
80
          !is.null(private$params$header)) {
        if (tolower(as.character(private$params$has_header)) == "true"
81
            ||
Guolin Ke's avatar
Guolin Ke committed
82
83
84
85
86
87
88
89
90
91
92
93
94
95
            tolower(as.character(private$params$header)) == "true") {
          has_header <- TRUE
        }
      }
      # Generate parameter str
      params_str <- lgb.params2str(private$params)
      # get handle of reference dataset
      ref_handle <- NULL
      if (!is.null(private$reference)) {
        ref_handle <- private$reference$.__enclos_env__$private$get_handle()
      }
      handle <- lgb.new.handle()
      # not subset
      if (is.null(private$used_indices)) {
96
97
        if (is.character(private$raw_data)) {
          handle <- lgb.call(
Guolin Ke's avatar
Guolin Ke committed
98
99
100
101
102
103
104
              "LGBM_DatasetCreateFromFile_R",
              ret = handle,
              lgb.c_str(private$raw_data),
              params_str,
              ref_handle
            )
        } else if (is.matrix(private$raw_data)) {
105
          handle <- lgb.call(
Guolin Ke's avatar
Guolin Ke committed
106
107
108
109
110
111
112
113
              "LGBM_DatasetCreateFromMat_R",
              ret = handle,
              private$raw_data,
              nrow(private$raw_data),
              ncol(private$raw_data),
              params_str,
              ref_handle
            )
114
        } else if (is(private$raw_data, "dgCMatrix")) {
Guolin Ke's avatar
Guolin Ke committed
115
116
117
118
119
120
121
122
123
124
125
126
127
          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
          )
        } else {
128
129
130
          stop(
            "lgb.Dataset.construct: does not support constructing from ", sQuote(class(private$raw_data))
          )
Guolin Ke's avatar
Guolin Ke committed
131
132
133
134
        }
      } else {
        # construct subset
        if (is.null(private$reference)) {
135
          stop("lgb.Dataset.construct: reference cannot be NULL for constructing data subset")
Guolin Ke's avatar
Guolin Ke committed
136
        }
137
        handle <- lgb.call(
Guolin Ke's avatar
Guolin Ke committed
138
139
140
141
142
143
144
145
146
147
148
            "LGBM_DatasetGetSubset_R",
            ret = handle,
            ref_handle,
            private$used_indices,
            length(private$used_indices),
            params_str
          )
      }
      class(handle) <- "lgb.Dataset.handle"
      private$handle <- handle
      # set feature names
149
150
      if (!is.null(private$colnames)) { self$set_colnames(private$colnames) }

Guolin Ke's avatar
Guolin Ke committed
151
      # load init score
152
      if (!is.null(private$predictor) &&
Guolin Ke's avatar
Guolin Ke committed
153
          is.null(private$used_indices)) {
154
155
        init_score <- private$predictor$predict(private$raw_data, rawscore = TRUE, reshape = TRUE)
        # do not need to transpose, for is col_marjor
Guolin Ke's avatar
Guolin Ke committed
156
157
158
        init_score <- as.vector(init_score)
        private$info$init_score <- init_score
      }
159
      if (isTRUE(private$free_raw_data)) { private$raw_data <- NULL }
Guolin Ke's avatar
Guolin Ke committed
160
161
      if (length(private$info) > 0) {
        # set infos
162
        for (i in seq_along(private$info)) {
Guolin Ke's avatar
Guolin Ke committed
163
164
165
166
167
168
169
          p <- private$info[i]
          self$setinfo(names(p), p[[1]])
        }
      }
      if (is.null(self$getinfo("label"))) {
        stop("lgb.Dataset.construct: label should be set")
      }
170
      self
Guolin Ke's avatar
Guolin Ke committed
171
172
173
    },
    dim = function() {
      if (!lgb.is.null.handle(private$handle)) {
174
175
        num_row <- 0L
        num_col <- 0L
176
177
178

        c(
          lgb.call("LGBM_DatasetGetNumData_R",    ret = num_row, private$handle),
Guolin Ke's avatar
Guolin Ke committed
179
          lgb.call("LGBM_DatasetGetNumFeature_R", ret = num_col, private$handle)
180
181
182
        )
      } else if (is.matrix(private$raw_data) || is(private$raw_data, "dgCMatrix")) {
        dim(private$raw_data)
Guolin Ke's avatar
Guolin Ke committed
183
184
      } else {
        stop(
185
          "dim: cannot get dimensions before dataset has been constructed, please call lgb.Dataset.construct explicitly"
Guolin Ke's avatar
Guolin Ke committed
186
187
188
189
190
        )
      }
    },
    get_colnames = function() {
      if (!lgb.is.null.handle(private$handle)) {
191
192
193
194
195
        cnames <- lgb.call.return.str("LGBM_DatasetGetFeatureNames_R", private$handle)
        private$colnames <- as.character(base::strsplit(cnames, "\t")[[1]])
        private$colnames
      } else if (is.matrix(private$raw_data) || is(private$raw_data, "dgCMatrix")) {
        colnames(private$raw_data)
Guolin Ke's avatar
Guolin Ke committed
196
197
      } else {
        stop(
198
          "dim: cannot get dimensions before dataset has been constructed, please call lgb.Dataset.construct explicitly"
Guolin Ke's avatar
Guolin Ke committed
199
200
201
202
        )
      }
    },
    set_colnames = function(colnames) {
203
      if (is.null(colnames)) { return(self) }
Guolin Ke's avatar
Guolin Ke committed
204
      colnames <- as.character(colnames)
205
      if (length(colnames) == 0) { return(self) }
Guolin Ke's avatar
Guolin Ke committed
206
207
208
209
210
211
212
213
      private$colnames <- colnames
      if (!lgb.is.null.handle(private$handle)) {
        merged_name <- paste0(as.list(private$colnames), collapse = "\t")
        lgb.call("LGBM_DatasetSetFeatureNames_R",
                 ret = NULL,
                 private$handle,
                 lgb.c_str(merged_name))
      }
214
      self
Guolin Ke's avatar
Guolin Ke committed
215
216
    },
    getinfo = function(name) {
217
218
219
220
      INFONAMES <- c("label", "weight", "init_score", "group")
      if (!is.character(name) ||
          length(name) != 1   ||
          !name %in% INFONAMES) {
Guolin Ke's avatar
Guolin Ke committed
221
        stop(
222
          "getinfo: name must one of the following: ", paste0(sQuote(INFONAMES), collapse = ", ")
Guolin Ke's avatar
Guolin Ke committed
223
224
        )
      }
225
      if (is.null(private$info[[name]]) && !lgb.is.null.handle(private$handle)) {
226
        info_len <- 0L
227
228
229
230
        info_len <- lgb.call("LGBM_DatasetGetFieldSize_R",
                             ret = info_len,
                             private$handle,
                             lgb.c_str(name))
Guolin Ke's avatar
Guolin Ke committed
231
232
        if (info_len > 0) {
          ret <- NULL
233
234
235
236
237
          ret <- if (name == "group") { integer(info_len) } else { rep(0.0, info_len) }
          ret <- lgb.call("LGBM_DatasetGetField_R",
                          ret = ret,
                          private$handle,
                          lgb.c_str(name))
Guolin Ke's avatar
Guolin Ke committed
238
239
240
          private$info[[name]] <- ret
        }
      }
241
      private$info[[name]]
Guolin Ke's avatar
Guolin Ke committed
242
243
    },
    setinfo = function(name, info) {
244
245
246
247
      INFONAMES <- c("label", "weight", "init_score", "group")
      if (!is.character(name) ||
          length(name) != 1   ||
          !name %in% INFONAMES) {
Guolin Ke's avatar
Guolin Ke committed
248
        stop(
249
          "setinfo: name must one of the following: ", paste0(sQuote(INFONAMES), collapse = ", ")
Guolin Ke's avatar
Guolin Ke committed
250
251
        )
      }
252
      info <- if (name == "group") { as.integer(info) } else { as.numeric(info) }
Guolin Ke's avatar
Guolin Ke committed
253
      private$info[[name]] <- info
254
      if (!lgb.is.null.handle(private$handle) && !is.null(info)) {
Guolin Ke's avatar
Guolin Ke committed
255
256
257
258
259
260
261
262
263
264
265
        if (length(info) > 0) {
          lgb.call(
            "LGBM_DatasetSetField_R",
            ret = NULL,
            private$handle,
            lgb.c_str(name),
            info,
            length(info)
          )
        }
      }
266
      self
Guolin Ke's avatar
Guolin Ke committed
267
268
    },
    slice = function(idxset, ...) {
269
      Dataset$new(
Guolin Ke's avatar
Guolin Ke committed
270
271
272
273
274
275
276
277
278
279
280
        NULL,
        private$params,
        self,
        private$colnames,
        private$predictor,
        private$free_raw_data,
        idxset,
        NULL,
        ...
      )
    },
281
    update_params = function(params) {
Guolin Ke's avatar
Guolin Ke committed
282
      private$params <- modifyList(private$params, params)
283
      self
Guolin Ke's avatar
Guolin Ke committed
284
285
286
287
    },
    set_reference = function(reference) {
      self$set_colnames(reference$get_colnames())
      private$set_predictor(reference$.__enclos_env__$private$predictor)
288
      if (identical(private$reference, reference)) { return(self) }
Guolin Ke's avatar
Guolin Ke committed
289
290
      if (is.null(private$raw_data)) {
        stop(
291
292
          "set_reference: cannot set reference after freeing raw data,
          please set ", sQuote("free_raw_data = FALSE"), " when you construct lgb.Dataset"
Guolin Ke's avatar
Guolin Ke committed
293
294
295
296
        )
      }
      if (!is.null(reference)) {
        if (!lgb.check.r6.class(reference, "lgb.Dataset")) {
297
          stop("set_reference: Can only use lgb.Dataset as a reference")
Guolin Ke's avatar
Guolin Ke committed
298
299
300
301
        }
      }
      private$reference <- reference
      self$finalize()
302
      self
Guolin Ke's avatar
Guolin Ke committed
303
304
305
306
307
308
309
    },
    save_binary = function(fname) {
      self$construct()
      lgb.call("LGBM_DatasetSaveBinary_R",
               ret = NULL,
               private$handle,
               lgb.c_str(fname))
310
      self
Guolin Ke's avatar
Guolin Ke committed
311
312
313
    }
  ),
  private = list(
314
315
316
317
318
319
320
321
322
323
324
325
    handle              = NULL,
    raw_data            = NULL,
    params              = list(),
    reference           = NULL,
    colnames            = NULL,
    predictor           = NULL,
    free_raw_data       = TRUE,
    used_indices        = NULL,
    info                = NULL,
    get_handle          = function() {
      if (lgb.is.null.handle(private$handle)) { self$construct() }
      private$handle
Guolin Ke's avatar
Guolin Ke committed
326
327
    },
    set_predictor = function(predictor) {
328
      if (identical(private$predictor, predictor)) { return(self) }
Guolin Ke's avatar
Guolin Ke committed
329
330
331
      if (is.null(private$raw_data)) {
        stop(
          "set_predictor: cannot set predictor after free raw data,
332
          please set ", sQuote("free_raw_data = FALSE"), " when you construct lgb.Dataset"
Guolin Ke's avatar
Guolin Ke committed
333
334
335
336
        )
      }
      if (!is.null(predictor)) {
        if (!lgb.check.r6.class(predictor, "lgb.Predictor")) {
337
          stop("set_predictor: Can only use lgb.Predictor as predictor")
Guolin Ke's avatar
Guolin Ke committed
338
339
340
341
        }
      }
      private$predictor <- predictor
      self$finalize()
342
      self
Guolin Ke's avatar
Guolin Ke committed
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
    }
  )
)

#' Contruct lgb.Dataset object
#'
#' Contruct lgb.Dataset object from dense matrix, sparse matrix
#' 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
#' @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}
#' @return constructed dataset
#' @examples
361
362
363
364
365
366
367
368
#' \dontrun{
#'   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)
#' }
Guolin Ke's avatar
Guolin Ke committed
369
370
#' @export
lgb.Dataset <- function(data,
371
372
373
374
375
                        params              = list(),
                        reference           = NULL,
                        colnames            = NULL,
                        free_raw_data       = TRUE,
                        info                = list(),
Guolin Ke's avatar
Guolin Ke committed
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
                        ...) {
  Dataset$new(
    data,
    params,
    reference,
    colnames,
    NULL,
    free_raw_data,
    NULL,
    info,
    ...
  )
}


391
#' Contruct validation data
Guolin Ke's avatar
Guolin Ke committed
392
#'
393
#' Contruct validation data according to training data
Guolin Ke's avatar
Guolin Ke committed
394
395
396
397
398
399
400
#'
#' @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}.
#' @return constructed dataset
#' @examples
401
402
403
404
405
406
407
408
#' \dontrun{
#'   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)
#' }
Guolin Ke's avatar
Guolin Ke committed
409
#' @export
410
411
412
lgb.Dataset.create.valid <- function(dataset, data, info = list(),  ...) {
  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
413
  }
414
415
  dataset$create_valid(data, info, ...)
}
Guolin Ke's avatar
Guolin Ke committed
416

417
#' Construct Dataset explicitly
Guolin Ke's avatar
Guolin Ke committed
418
419
420
#'
#' @param dataset Object of class \code{lgb.Dataset}
#' @examples
421
422
423
424
425
426
#' \dontrun{
#'   data(agaricus.train, package='lightgbm')
#'   train <- agaricus.train
#'   dtrain <- lgb.Dataset(train$data, label=train$label)
#'   lgb.Dataset.construct(dtrain)
#' }
Guolin Ke's avatar
Guolin Ke committed
427
428
#' @export
lgb.Dataset.construct <- function(dataset) {
429
430
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.construct: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
431
  }
432
  dataset$construct()
Guolin Ke's avatar
Guolin Ke committed
433
434
}

435
#' Dimensions of an lgb.Dataset
Guolin Ke's avatar
Guolin Ke committed
436
437
438
439
440
441
442
443
444
445
446
#'
#' 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
#' @return a vector of numbers of rows and of columns
#'
#' @details
#' Note: since \code{nrow} and \code{ncol} internally use \code{dim}, they can also
#' be directly used with an \code{lgb.Dataset} object.
#'
#' @examples
447
448
449
450
451
452
453
454
455
#' dontrun{
#'   data(agaricus.train, package='lightgbm')
#'   train <- agaricus.train
#'   dtrain <- lgb.Dataset(train$data, label=train$label)
#'
#'   stopifnot(nrow(dtrain) == nrow(train$data))
#'   stopifnot(ncol(dtrain) == ncol(train$data))
#'   stopifnot(all(dim(dtrain) == dim(train$data)))
#' }
Guolin Ke's avatar
Guolin Ke committed
456
457
458
#' @rdname dim
#' @export
dim.lgb.Dataset <- function(x, ...) {
459
460
  if (!lgb.is.Dataset(x)) {
    stop("dim.lgb.Dataset: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
461
  }
462
  x$dim()
Guolin Ke's avatar
Guolin Ke committed
463
464
465
466
467
}

#' Handling of column names of \code{lgb.Dataset}
#'
#' Only column names are supported for \code{lgb.Dataset}, thus setting of
468
#' row names would have no effect and returned row names would be NULL.
Guolin Ke's avatar
Guolin Ke committed
469
470
471
472
473
474
475
476
477
478
#'
#' @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
479
480
481
482
483
484
485
486
487
488
#' dontrun{
#'   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)
#' }
Guolin Ke's avatar
Guolin Ke committed
489
490
491
#' @rdname dimnames.lgb.Dataset
#' @export
dimnames.lgb.Dataset <- function(x) {
492
493
  if (!lgb.is.Dataset(x)) {
    stop("dimnames.lgb.Dataset: input data should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
494
  }
495
  list(NULL, x$get_colnames())
Guolin Ke's avatar
Guolin Ke committed
496
497
498
499
500
501
}

#' @rdname dimnames.lgb.Dataset
#' @export
`dimnames<-.lgb.Dataset` <- function(x, value) {
  if (!is.list(value) || length(value) != 2L)
502
503
    stop("invalid ", sQuote("value"), " given: must be a list of two elements")
  if (!is.null(value[[1L]])) { stop("lgb.Dataset does not have rownames") }
Guolin Ke's avatar
Guolin Ke committed
504
505
506
507
508
509
  if (is.null(value[[2]])) {
    x$set_colnames(NULL)
    return(x)
  }
  if (ncol(x) != length(value[[2]]))
    stop("can't assign ",
510
511
512
         sQuote(length(value[[2]])),
         " colnames to an lgb.Dataset with ",
         sQuote(ncol(x)), " columns")
Guolin Ke's avatar
Guolin Ke committed
513
  x$set_colnames(value[[2]])
514
  x
Guolin Ke's avatar
Guolin Ke committed
515
516
}

517
#' Slice a dataset
Guolin Ke's avatar
Guolin Ke committed
518
#'
519
#' Get a new \code{lgb.Dataset} containing the specified rows of
Guolin Ke's avatar
Guolin Ke committed
520
521
522
523
524
525
526
527
#' orginal lgb.Dataset object
#'
#' @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
#'
#' @examples
528
529
530
531
#' \dontrun{
#'   data(agaricus.train, package='lightgbm')
#'   train <- agaricus.train
#'   dtrain <- lgb.Dataset(train$data, label=train$label)
Guolin Ke's avatar
Guolin Ke committed
532
#'
533
534
535
#'   dsub <- slice(dtrain, 1:42)
#'   labels1 <- getinfo(dsub, 'label')
#' }
Guolin Ke's avatar
Guolin Ke committed
536
#' @export
537
slice <- function(dataset, ...) { UseMethod("slice") }
Guolin Ke's avatar
Guolin Ke committed
538
539
540
541

#' @rdname slice
#' @export
slice.lgb.Dataset <- function(dataset, idxset, ...) {
542
543
  if (!lgb.is.Dataset(dataset)) {
    stop("slice.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
544
  }
545
  dataset$slice(idxset, ...)
Guolin Ke's avatar
Guolin Ke committed
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
}


#' Get information of an lgb.Dataset object
#'
#' @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
#'
#' @details
#' The \code{name} field can be one of the following:
#'
#' \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 ;
#' }
#'
#' @examples
567
568
569
570
571
572
573
574
575
576
577
#' \dontrun{
#'   data(agaricus.train, package='lightgbm')
#'   train <- agaricus.train
#'   dtrain <- lgb.Dataset(train$data, label=train$label)
#'   lgb.Dataset.construct(dtrain)
#'   labels <- getinfo(dtrain, 'label')
#'   setinfo(dtrain, 'label', 1-labels)
#'
#'   labels2 <- getinfo(dtrain, 'label')
#'   stopifnot(all(labels2 == 1-labels))
#' }
Guolin Ke's avatar
Guolin Ke committed
578
#' @export
579
getinfo <- function(dataset, ...) { UseMethod("getinfo") }
Guolin Ke's avatar
Guolin Ke committed
580
581
582
583

#' @rdname getinfo
#' @export
getinfo.lgb.Dataset <- function(dataset, name, ...) {
584
585
  if (!lgb.is.Dataset(dataset)) {
    stop("getinfo.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
586
  }
587
  dataset$getinfo(name)
Guolin Ke's avatar
Guolin Ke committed
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
}

#' Set information of an lgb.Dataset object
#'
#' @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
#'
#' @details
#' The \code{name} field can be one of the following:
#'
#' \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}.
#' }
#'
#' @examples
609
610
611
612
613
614
615
616
617
618
#' \dontrun{
#'   data(agaricus.train, package='lightgbm')
#'   train <- agaricus.train
#'   dtrain <- lgb.Dataset(train$data, label=train$label)
#'   lgb.Dataset.construct(dtrain)
#'   labels <- getinfo(dtrain, 'label')
#'   setinfo(dtrain, 'label', 1-labels)
#'   labels2 <- getinfo(dtrain, 'label')
#'   stopifnot(all.equal(labels2, 1-labels))
#' }
Guolin Ke's avatar
Guolin Ke committed
619
#' @export
620
setinfo <- function(dataset, ...) { UseMethod("setinfo") }
Guolin Ke's avatar
Guolin Ke committed
621
622
623
624

#' @rdname setinfo
#' @export
setinfo.lgb.Dataset <- function(dataset, name, info, ...) {
625
626
  if (!lgb.is.Dataset(dataset)) {
    stop("setinfo.lgb.Dataset: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
627
  }
628
  dataset$setinfo(name, info)
Guolin Ke's avatar
Guolin Ke committed
629
630
}

631
#' Set reference of \code{lgb.Dataset}
Guolin Ke's avatar
Guolin Ke committed
632
#'
633
#' If you want to use validation data, you should set reference to training data
Guolin Ke's avatar
Guolin Ke committed
634
635
636
637
638
#'
#' @param dataset object of class \code{lgb.Dataset}
#' @param reference object of class \code{lgb.Dataset}
#' @return passed dataset
#' @examples
639
640
641
642
643
644
645
646
647
#' \dontrun{
#'   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)
#' }
Guolin Ke's avatar
Guolin Ke committed
648
649
650
#' @rdname lgb.Dataset.set.reference
#' @export
lgb.Dataset.set.reference <- function(dataset, reference) {
651
652
  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
653
  }
654
  dataset$set_reference(reference)
Guolin Ke's avatar
Guolin Ke committed
655
656
}

657
658
#' Save \code{lgb.Dataset} to a binary file
#'
Guolin Ke's avatar
Guolin Ke committed
659
660
661
662
#' @param dataset object of class \code{lgb.Dataset}
#' @param fname object filename of output file
#' @return passed dataset
#' @examples
663
664
665
666
667
668
#' \dontrun{
#'   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
669
670
671
#' @rdname lgb.Dataset.save
#' @export
lgb.Dataset.save <- function(dataset, fname) {
672
673
  if (!lgb.is.Dataset(dataset)) {
    stop("lgb.Dataset.set: input dataset should be an lgb.Dataset object")
Guolin Ke's avatar
Guolin Ke committed
674
  }
675
676
  if (!is.character(fname)) {
    stop("lgb.Dataset.set: fname should be a character or a file connection")
Guolin Ke's avatar
Guolin Ke committed
677
  }
678
  dataset$save_binary(fname)
Guolin Ke's avatar
Guolin Ke committed
679
}