Reputation: 11
I trained a xgb model using the caret package with traincontrol. I serialized and converted to character before saving the model to local SQLite database. I was able to save it. But while retrieving it from database and unserializing it, it throws an error unserialize(charToRaw(xgbModel))
Error in unserialize(charToRaw(selected_model$Model)) : ReadItem: unknown type 57, perhaps written by later version of R
Upvotes: 0
Views: 1135
Reputation: 19716
To save the xgboost model trained by caret you need to save to raw. Here is an example:
library(mlbench) #for the data set
library(caret)
library(xgboost)
data(Sonar)
caret_model <- train(x = Sonar[,1:60],
y = Sonar$Class,
method = "xgbTree",
trControl = trainControl(method = "cv", number = 2),
tuneLength = 2)
save the raw model:
raw_model <- xgb.save.raw(caret_model$finalModel)
serialize that and save it to the local db. When you unserialise:
caret_model2 <- xgb.load(raw_model)
preds <- predict(caret_model2, as.matrix(Sonar[,1:60]))
head(preds)
#output
0.08729284 0.04738589 0.05628103 0.04275921 0.02574497 0.00655277
then you can use caret_model2
to predict.
This is mentioned here under "save and load models".
Upvotes: 0