### Warning: this example will generate a temporary .Rds
### file in your temp folder, and will then delete it
### First, create a model from random data
library(isotree)
set.seed(1)
X <- matrix(rnorm(100), nrow = 20)
iso <- isolation.forest(X, ntrees=10, nthreads=1, lazy_serialization=FALSE)
### Now serialize the model
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_objects$model$ptr)
### now unpack it
isotree.restore.handle(iso2)
cat("Model pointer after unpacking is this: \n")
print(iso2$cpp_objects$model$ptr)
### Note that this function is not needed when using lazy_serialization=TRUE
iso_lazy <- isolation.forest(X, ntrees=10, nthreads=1, lazy_serialization=TRUE)
temp_file_lazy <- file.path(tempdir(), "iso_lazy.Rds")
saveRDS(iso_lazy, temp_file_lazy)
iso_lazy2 <- readRDS(temp_file_lazy)
file.remove(temp_file_lazy)
cat("Model pointer after unpacking lazy-serialized: \n")
print(iso_lazy2$cpp_objects$model$ptr)
Run the code above in your browser using DataLab