Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Serialize R models as JSON [closed]

Is there some good R package that can convert prediction models and other complex object to and from JSON? I have linear regression model from this example:

eruption.lm = lm(eruptions ~ waiting, data=faithful) 
newdata = data.frame(waiting=80)
predict(eruption.lm, newdata) 

I would like to serialize eruption.lm model as JSON store it somewhere or send it to some external system, and later deserialize it and do prediction. I have tried with jsonlite R package:

json<-serializeJSON(eruption.lm)
lin.model<-unserializeJSON(json)

predict(lin.model, newdata)

However, jsonlite cannot handle complex objects - deserialized model returns an error in prediction:

Error in eval(expr, envir, enclos) : could not find function "list"

Is there some better package that can serialize/deserialize objects.

like image 247
Jovan MSFT Avatar asked Oct 30 '22 03:10

Jovan MSFT


1 Answers

You just need to help it remember the environment for terms:

attr(lin.model$terms, ".Environment") <- .GlobalEnv

predict(lin.model, newdata)

##       1 
## 4.17622 

I'd file this as an enhancement request over at http://github.com/jeroenooms/jsonlite/issues

Alternatively, you can use native R binary serialization:

saveRDS(lin.model, "lin.model.rds")

predict(readRDS("lin.model.rds"), newdata)

##       1 
## 4.17622 

unless you absolutely need a text serialization method, in which case you can do:

saveRDS(lin.model, file="lin.model.txt", ascii=TRUE)

predict(readRDS("lin.model.txt"), newdata)

##       1 
## 4.17622 

The ascii=TRUE makes a text hex representation of the object:

1f8b 0800 0000 0000 0003 ed5d c992 1cb9
91bd e797 cc1c 9806 381c db51 36a6 c35c
e61f 4a64 5153 3645 b255 2cb6 749a 6f1f
5fb0 bcc8 ca62 4b1a 33f5 25da 8c6d 8848
04fc f9f6 b004 10f5 870b 5d62 afa9 964b
4cb1 71b8 d456 2f91 2e99 8afc f421 5e5b
e510 73ef 9770 0d35 17aa 3d5f 6290 5fe3
850a c59c 2ef9 f2f5 e1cb e3f7 4bd4 27c6
bd18 2fff f69f 5f5f 1f5f 3e3e fef2 faef
f36e bdfc f5e1 e9f5 e9eb 9f2f 94d9 4554
1112 ae39 84dc 63d7 2287 de7a b2bb a975
... (lots more)

that can be stored in places where binary blobs can't.

If you need a readable text serialization method, filing the above suggested enhancement request is prbly the way to go.

like image 133
hrbrmstr Avatar answered Nov 09 '22 15:11

hrbrmstr