简体   繁体   中英

Error when serializing an mgcv gam model with jsonlite

I want to "serialize" in a robust way an mgcv gam model with jsonlite in order to use it later with rpy2.

(What I mean by robust: When using python, I consider that Pickle is not robust because after every Python update, the serialization pipeline breaks. That is why I prefer to use a json format with jsonlite, which seems to me more robust (but I may be wrong).)

jsonlite does a pretty good job in comparison to RJSONIO: every detail of the mgcv model is being serialized correctly except a sub-variable called Environnement:

inspection of the initial model b

inspection of the deserialized model new_b

You can see in the previous two images that: Environnement: namespace:stats becomes Environnement: R_GlobalEnv

I am not sure how to deal with that. Every advise is welcome.

Here is a minimum reproducible example:


> library(mgcv)
> n = 40
> x <- 1:n/n  # data between [0, 1]
> x2 <- 1:n/n  # data between [0, 1]
> x3 <- 1:n/n  # data between [0, 1]
> mu <- exp(-400*(x-.6)^2)+5*exp(-500*(x-.75)^2)/3+2*exp(-500*(x-.9)^2)
> y <- mu+0.5*rnorm(n)
> b <- gam(y~s(x)+te(x2, x3))
> 
> library(jsonlite)
> json_str = serializeJSON(b)
> new_b = unserializeJSON(json_str)
> mat     <- predict.gam(b    , type = "terms")
> new_mat <- predict.gam(new_b, type = "terms")
Error in if (object$by != "NA") { : 
  valeur manquante là où TRUE / FALSE est requis
> 

There is an issue in jsonlite: "NA" was serialized to NA. (the issue was not caused by the changing environnement variable)

Quick fix:

new_b$smooth[[2]]$by = "NA"
new_b$smooth[[1]]$by = "NA"
new_mat <- predict.gam(new_b, type = "terms")


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM