isotree (version 0.1.28)

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`.

But due to R's environments system (as opposed to other systems such as Python which can use pass-by-reference), they will only be re-constructed in the environment that is calling `predict`, `print`, etc. and not in higher-up environments (i.e. if calling `predict` on the object from inside different functions, each function will have to reconstruct the C++ objects independently and they will only live within the function that called `predict`).

This function serves as an environment-level unpacker that will reconstruct the C++ object in the environment in which it is called (i.e. if it's desired to call `predict` from inside multiple functions, use this function before passing the freshly-loaded model object to those other functions, and then they will not need to reconstruct the C++ objects anymore), in the same way as `predict` or `print`, but without producing any outputs or messages.

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.

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)

### will de-serialize inside, but object is short-lived
wrap_predict <- function(model, data) {
    pred <- predict(model, data)
    cat("pointer inside function is this: ")
    print(model$cpp_obj$ptr)
    return(pred)
}
temp <- wrap_predict(iso2, X)
cat("pointer outside function is this: \n")
print(iso2$cpp_obj$ptr) ### pointer to the C++ object

### now unpack the C++ object beforehand
unpack.isolation.forest(iso2)
print("after unpacking beforehand")
temp <- wrap_predict(iso2, X)
cat("pointer outside function is this: \n")
print(iso2$cpp_obj$ptr)
# }

Run the code above in your browser using DataLab