lgb.unloader.R 2.4 KB
Newer Older
1
2
#' LightGBM unloading error fix
#'
3
4
5
#' Attempts to unload LightGBM packages so you can remove objects cleanly without having to restart R.
#' This is useful for instance if an object becomes stuck for no apparent reason and you do not want
#' to restart R to fix the lost object.
6
#'
7
8
9
10
11
12
13
#' @param restore Whether to reload \code{LightGBM} immediately after detaching from R.
#'                Defaults to \code{TRUE} which means automatically reload \code{LightGBM} once
#'                unloading is performed.
#' @param wipe Whether to wipe all \code{lgb.Dataset} and \code{lgb.Booster} from the global
#'             environment. Defaults to \code{FALSE} which means to not remove them.
#' @param envir The environment to perform wiping on if \code{wipe == TRUE}. Defaults to
#'              \code{.GlobalEnv} which is the global environment.
14
#'
15
#' @return NULL invisibly.
16
#'
17
18
19
20
21
22
23
24
25
26
#' @examples
#' 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)
27
28
29
#' model <- lgb.train(
#'   params = params
#'   , data = dtrain
30
#'   , nrounds = 10L
31
#'   , valids = valids
32
33
34
#'   , min_data = 1L
#'   , learning_rate = 1.0
#'   , early_stopping_rounds = 5L
35
#' )
36
37
#'
#' \dontrun{
38
39
40
#' lgb.unloader(restore = FALSE, wipe = FALSE, envir = .GlobalEnv)
#' rm(model, dtrain, dtest) # Not needed if wipe = TRUE
#' gc() # Not needed if wipe = TRUE
41
#'
42
43
#' library(lightgbm)
#' # Do whatever you want again with LightGBM without object clashing
44
#' }
45
#'
46
47
#' @export
lgb.unloader <- function(restore = TRUE, wipe = FALSE, envir = .GlobalEnv) {
48

49
50
  # Unload package
  try(detach("package:lightgbm", unload = TRUE), silent = TRUE)
51

52
53
  # Should we wipe variables? (lgb.Booster, lgb.Dataset)
  if (wipe) {
54
    boosters <- Filter(
55
      f = function(x) {
56
57
58
59
60
        inherits(get(x, envir = envir), "lgb.Booster")
      }
      , x = ls(envir = envir)
    )
    datasets <- Filter(
61
      f = function(x) {
62
63
64
65
        inherits(get(x, envir = envir), "lgb.Dataset")
      }
      , x = ls(envir = envir)
    )
66
    rm(list = c(boosters, datasets), envir = envir)
67
68
    gc(verbose = FALSE)
  }
69

70
71
72
73
  # Load package back?
  if (restore) {
    library(lightgbm)
  }
74

75
  invisible()
76

77
}