lgb.unloader.R 2.26 KB
Newer Older
1
2
3
#' LightGBM unloading error fix
#'
#' 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.
4
#'
James Lamb's avatar
James Lamb committed
5
#' @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.
6
7
#' @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.
8
#'
9
#' @return NULL invisibly.
10
#'
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#' @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)
#' model <- lgb.train(params,
#'                    dtrain,
#'                    100,
#'                    valids,
#'                    min_data = 1,
#'                    learning_rate = 1,
#'                    early_stopping_rounds = 10)
#' lgb.unloader(restore = FALSE, wipe = FALSE, envir = .GlobalEnv)
#' rm(model, dtrain, dtest) # Not needed if wipe = TRUE
#' gc() # Not needed if wipe = TRUE
31
#'
32
33
#' library(lightgbm)
#' # Do whatever you want again with LightGBM without object clashing
34
#'
35
36
#' @export
lgb.unloader <- function(restore = TRUE, wipe = FALSE, envir = .GlobalEnv) {
37

38
39
  # Unload package
  try(detach("package:lightgbm", unload = TRUE), silent = TRUE)
40

41
42
  # Should we wipe variables? (lgb.Booster, lgb.Dataset)
  if (wipe) {
43
44
45
    boosters <- Filter(function(x) inherits(get(x, envir = envir), "lgb.Booster"), ls(envir = envir))
    datasets <- Filter(function(x) inherits(get(x, envir = envir), "lgb.Dataset"), ls(envir = envir))
    rm(list = c(boosters, datasets), envir = envir)
46
47
    gc(verbose = FALSE)
  }
48

49
50
51
52
  # Load package back?
  if (restore) {
    library(lightgbm)
  }
53

54
  invisible()
55

56
}