【问题标题】:Passing Parameter to Rserve using terminal使用终端将参数传递给 Rserve
【发布时间】:2017-01-11 06:48:29
【问题描述】:

我有一个 R 代码,其中包含经过训练的机器学习模型。现在我想对新数据进行预测。

当前方法:

Script code.R '[{"x1" : "1011", "x2" : "1031", "x4" : "0.65"}]'

我会得到答案,问题是加载和设置环境花费了太多时间

代码:

# Loading the library

suppressPackageStartupMessages(library(C50))
suppressPackageStartupMessages(library(jsonlite))
suppressPackageStartupMessages(library(plyr))

# Loading the trained model

model1 <- readRDS("model1.RDA")

 x <- (args[1])

# Function which wraps prediction and son handling

output <- function(x) {

df <- fromJSON(x)

df[is.na(df)] <- 0

prediction <- predict.C5.0(model1, newdata = df, type = "class")

json_df <- toJSON(prediction)

return(json_df)
}

 output(x)

问题:

  • 我想使用 Rserve 并将参数传递给它,我不能 如何弄清楚?我应该做什么修改?

  • 我知道添加 library(Rserve) 然后执行 run.Rserve() 但超出 我不知道怎么做?

【问题讨论】:

  • 您的代码似乎不完整(缺少输出函数的右括号并且没有调用输出函数,您能否编辑您的问题。谢谢 :-)
  • @RYoda 已添加,谢谢!
  • 我认为您基本上必须将代码拆分为客户端和服务器端脚本。服务器端:从您的源代码中删除x 分配和output 函数调用行,并将此脚本与model1.RDA 一起部署到服务器上的文件夹中。客户端:set x variable, RSconnect, RSserversource, RSassign x, RSeval...(详见RSclient package:cran.r-project.org/web/packages/RSclient/RSclient.pdf的文档)
  • @RYoda 谢谢你,会去看看
  • Rserve 是基于 TCP/IP 的,而不是 HTTP (AFAIK),因此您需要一个客户端库(抱歉,我没有使用 Rserve w/o R 的经验)。请修改您的问题,因为您似乎想使用 R 客户端。

标签: r rserve


【解决方案1】:

所以我正在使用 NodeJS 与 Rserve 对话。

首先从终端安装 node 和 npm。

npm install --save rserve-client

javascript文件中的代码是:

var r = require('rserve-client');
r.connect('localhost', 6311, function(err, client) {
    client.evaluate('a<-2.7+2', function(err, ans) {
        console.log(ans);
        client.end();
    });
});
  • 观察节点正在使用端口“6311”(Rserve 的默认值)

  • 'a部分是发送给R的,修改这部分

【讨论】:

【解决方案2】:

如果你想使用Java客户端,你需要下载REngine jars,下面的代码会有所帮助(我使用的是Java):

import org.rosuda.REngine.*;
import org.rosuda.REngine.Rserve.*;
import java.util.Arrays;

public class RServeCommunication {

    public static void main(String[] args) {
      try {
        // Setup the connection with RServer through RServe
        RConnection rConnection = new RConnection("127.0.0.1", 6311); 
        // Call R function 
        REXP retValues = rConnection.eval("rnorm(10)");
        // print the values returned to console
        System.out.println(Arrays.toString(retValues.asDoubles()));
        // [1.4280800442888217, -0.11989685521338722, 0.6836180891125788, 0.7913069852336285, -0.8968664915403061, 0.0681405000990237, -0.08726481416189025, -0.5322959519563994, -0.3302662744787598, 0.45030516965234024]

      }
      catch (REngineException e) {
        System.out.println("Error: " + e.toString());
      }
      catch (REXPMismatchException e) {
        System.out.println("Error: " + e.toString());
      }
    } 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    • 2016-01-14
    • 2012-09-17
    • 2011-10-20
    • 1970-01-01
    • 2019-03-16
    • 1970-01-01
    相关资源
    最近更新 更多