【问题标题】:How do you convert R models to raw binary or string buffer?如何将 R 模型转换为原始二进制或字符串缓冲区?
【发布时间】:2021-12-02 09:03:35
【问题描述】:

我在第三方环境 (IBM Watson Studio) 中使用 R 3.6 工作,需要能够将模型对象转换为原始二进制或字符串缓冲区,以便按照 here 所示保存模型。简而言之,我必须使用一个函数发出一个 API 请求,该请求通过原始二进制/字符串缓冲区数据发送以保存文件。与this question 类似,我选择使用jsonlite::serializeJSON() 将模型转换为JSON(然后转换为raw)。它似乎有效,但与该帖子中的人相似,我遇到了serializeJSON() 无法正确转换模型对象中的复杂列表的问题。当我尝试预测时,它会遇到“找不到函数“列表””错误。由于我有 GLM,即使在实施建议的修复后,我现在也会遇到错误“找不到对象'C_logit_linkinv'”。显然,这种方法不能很好地推广到不同的模型。

我将作为一个新问题发布,因为在我的情况下没有任何解决方案有效,并且因为我想看看是否有更强大的方法将模型对象转换为原始字节或字符串缓冲区。我没有在 IBM 板上发帖,因为我觉得这是关于模型对象和转换的更普遍的问题,但如果社区认为这更合适,我会这样做。这是一个可重现的示例:

require(jsonlite)

# Generate some data
data <- data.frame(x1=rnorm(100),
                   y=rbinom(100,1,.6))

# Fit and convert model->JSON->Raw
fitted_model <- glm(y ~ 0 + ., 
                   data = data, 
                   family = binomial)
model_as_json <- jsonlite::serializeJSON(fitted_model)
model_as_raw <- charToRaw(model_as_json)

# Convert back to model
back_to_json <- rawToChar(model_as_raw)
back_to_model <- jsonlite::unserializeJSON(back_to_json)

# Score
scoring_data <- data.frame(x1=rnorm(5))
predict(object=back_to_model,
        newdata = scoring_data,
        type='response')

规格:

  • R 版本 3.6.1 (2019-07-05)
  • 平台:x86_64-conda_cos6-linux-gnu(64 位)
  • 运行于:Red Hat Enterprise Linux 8.2 (Ootpa)
  • jsonlite_1.7.1

【问题讨论】:

  • 您应该使用基本函数saveRDS 进行二进制保存。对于文本保存,dputcontrol = "exact" 将接近。要阅读它们,请分别使用readRDSdget
  • 但是saveRDS 不需要保存到实际文件吗?我需要一个二进制流来序列化内存。我希望我是有道理的......我会给dput看看。谢谢@user2554330!
  • @RitchieSacramento 它有效!非常感谢。你想回答这个问题,以便我可以接受吗?如果我没有收到回复,我会自己回答并给你信用。 :)

标签: r jsonlite


【解决方案1】:

您可以将serialize() 与设置为NULLconnection 参数一起使用,这将返回一个原始向量并使用unserialize() 进行恢复。

重要的是,根据文档:

引用对象的共享保留在对象中

set.seed(9)
data <- data.frame(x1=rnorm(100),
                   y=rbinom(100,1,.6))

# Fit and convert model -> Raw
fitted_model <- glm(y ~ 0 + ., 
                    data = data, 
                    family = binomial)

model_as_raw <- serialize(fitted_model, connection = NULL)

# Convert back to model
back_to_model <- unserialize(model_as_raw)

# Check that predict works
scoring_data <- data.frame(x1=rnorm(5))

predict(object=back_to_model,
        newdata = scoring_data,
        type='response')

        1         2         3         4         5 
0.4908404 0.4871576 0.4955416 0.4978725 0.5065067 

【讨论】:

    猜你喜欢
    • 2014-02-21
    • 1970-01-01
    • 2016-09-16
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 2016-07-26
    • 1970-01-01
    相关资源
    最近更新 更多