isotree (version 0.2.10)

unpack.isolation.forest: Unpack isolation forest model after de-serializing

Description

After persisting an isolation forest model object through `saveRDS`, `save`, or restarting a session, the underlying C++ objects that constitute the isolation forest model and which live only on the C++ heap memory are not saved along, thus not restored after loading a saved model through `readRDS` or `load`.

The model object however keeps serialized versions of the C++ objects as raw bytes, from which the C++ objects can be reconstructed, and are done so automatically after calling `predict`, `print`, `summary`, or `add.isolation.tree` on the freshly-loaded object from `readRDS` or `load`.

This function allows to automatically de-serialize the object ("complete" or "restore" the handle) without having to call any function that would do extra processing. It is an equivalent to XGBoost's `xgb.Booster.complete` and CatBoost's `catboost.restore_handle` functions.

Usage

unpack.isolation.forest(model)

Arguments

model

An Isolation Forest object as returned by `isolation.forest`, which has been just loaded from a disk file through `readRDS`, `load`, or a session restart.

Value

The same model object that was passed as input. Object is modified in-place however, so it does not need to be re-assigned.

Details

If using this function to de-serialize a model in a production system, one might want to delete the serialized bytes inside the object afterwards in order to free up memory. These are under `model$cpp_obj$serialized` (plus `model$cpp_obj$imp_ser` if building with imputer) - e.g.: `model$cpp_obj$serialized = NULL; model$cpp_obj$imp_ser = NULL; gc()`.

Examples

Run this code
# NOT RUN {
### Warning: this example will generate a temporary .Rds
### file in your temp folder, and will then delete it
library(isotree)
set.seed(1)
X <- matrix(rnorm(100), nrow = 20)
iso <- isolation.forest(X, ntrees=10, nthreads=1)
temp_file <- file.path(tempdir(), "iso.Rds")
saveRDS(iso, temp_file)
iso2 <- readRDS(temp_file)
file.remove(temp_file)

cat("Model pointer after loading is this: \n")
print(iso2$cpp_obj$ptr)

### now unpack it
unpack.isolation.forest(iso2)

cat("Model pointer after unpacking is this: \n")
print(iso2$cpp_obj$ptr)
# }

Run the code above in your browser using DataLab