| 1 |
#' Load XGBoost model from binary file |
| 2 |
#' |
| 3 |
#' Load XGBoost model from binary model file. |
| 4 |
#' |
| 5 |
#' @param modelfile The name of the binary input file. |
| 6 |
#' |
| 7 |
#' @details |
| 8 |
#' The input file is expected to contain a model saved in an XGBoost model format |
| 9 |
#' using either [xgb.save()] in R, or using some |
| 10 |
#' appropriate methods from other XGBoost interfaces. E.g., a model trained in Python and |
| 11 |
#' saved from there in XGBoost format, could be loaded from R. |
| 12 |
#' |
| 13 |
#' Note: a model saved as an R object has to be loaded using corresponding R-methods, |
| 14 |
#' not by [xgb.load()]. |
| 15 |
#' |
| 16 |
#' @return |
| 17 |
#' An object of `xgb.Booster` class. |
| 18 |
#' |
| 19 |
#' @seealso [xgb.save()] |
| 20 |
#' |
| 21 |
#' @examples |
| 22 |
#' \dontshow{RhpcBLASctl::omp_set_num_threads(1)} |
| 23 |
#' data(agaricus.train, package = "xgboost") |
| 24 |
#' data(agaricus.test, package = "xgboost") |
| 25 |
#' |
| 26 |
#' ## Keep the number of threads to 1 for examples |
| 27 |
#' nthread <- 1 |
| 28 |
#' data.table::setDTthreads(nthread) |
| 29 |
#' |
| 30 |
#' train <- agaricus.train |
| 31 |
#' test <- agaricus.test |
| 32 |
#' |
| 33 |
#' bst <- xgb.train( |
| 34 |
#' data = xgb.DMatrix(train$data, label = train$label, nthread = 1), |
| 35 |
#' nrounds = 2, |
| 36 |
#' params = xgb.params( |
| 37 |
#' max_depth = 2, |
| 38 |
#' nthread = nthread, |
| 39 |
#' objective = "binary:logistic" |
| 40 |
#' ) |
| 41 |
#' ) |
| 42 |
#' |
| 43 |
#' fname <- file.path(tempdir(), "xgb.ubj") |
| 44 |
#' xgb.save(bst, fname) |
| 45 |
#' bst <- xgb.load(fname) |
| 46 |
#' @export |
| 47 |
xgb.load <- function(modelfile) { |
| 48 |
if (is.null(modelfile)) |
| 49 |
stop("xgb.load: modelfile cannot be NULL") |
| 50 |
|
| 51 |
bst <- xgb.Booster( |
| 52 |
params = list(), |
| 53 |
cachelist = list(), |
| 54 |
modelfile = modelfile |
| 55 |
) |
| 56 |
bst <- bst$bst |
| 57 |
# re-use modelfile if it is raw so we do not need to serialize |
| 58 |
if (typeof(modelfile) == "raw") { |
| 59 |
warning( |
| 60 |
paste( |
| 61 |
"The support for loading raw booster with `xgb.load` will be ", |
| 62 |
"discontinued in upcoming release. Use `xgb.load.raw` instead. " |
| 63 |
) |
| 64 |
) |
| 65 |
} |
| 66 |
return(bst) |
| 67 |
} |