readRDS.lgb.Booster.R 1.66 KB
Newer Older
1
2
3
#' @name readRDS.lgb.Booster
#' @title readRDS for \code{lgb.Booster} models
#' @description Attempts to load a model stored in a \code{.rds} file, using \code{\link[base]{readRDS}}
4
5
#' @param file a connection or the name of the file where the R object is saved to or read from.
#' @param refhook a hook function for handling reference objects.
6
#'
7
#' @return \code{lgb.Booster}
8
#'
9
#' @examples
10
#' \donttest{
11
12
13
14
15
16
17
18
19
#' 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)
#' params <- list(objective = "regression", metric = "l2")
#' valids <- list(test = dtest)
20
21
22
#' model <- lgb.train(
#'   params = params
#'   , data = dtrain
23
#'   , nrounds = 10L
24
#'   , valids = valids
25
26
27
#'   , min_data = 1L
#'   , learning_rate = 1.0
#'   , early_stopping_rounds = 5L
28
#' )
29
30
31
#' model_file <- tempfile(fileext = ".rds")
#' saveRDS.lgb.Booster(model, model_file)
#' new_model <- readRDS.lgb.Booster(model_file)
32
#' }
33
34
#' @export
readRDS.lgb.Booster <- function(file = "", refhook = NULL) {
35

36
  object <- readRDS(file = file, refhook = refhook)
37

38
  # Check if object has the model stored
39
  if (!is.na(object$raw)) {
40

41
42
    # Create temporary model for the model loading
    object2 <- lgb.load(model_str = object$raw)
43

44
    # Restore best iteration and recorded evaluations
45
46
    object2$best_iter <- object$best_iter
    object2$record_evals <- object$record_evals
47

48
    # Return newly loaded object
49
    return(object2)
50

51
  } else {
52

53
    # Return RDS loaded object
54
    return(object)
55

56
  }
57

58
}