R使用Rserve与Java集成

时间:2017-02-27 10:20:22

标签: java r rserve

我已经构建了一个使用RServe包连接R和java的应用程序。在这个项目中,我使用神经网络来预测输出。我使用的源代码在哪里如下:

myneuralnetscript=function(){   
    trainingData = read.csv("D:\\Kuliah\\Semester V\\TA\\Implementasi\\training.csv")
    testingData = read.csv("D:\\Kuliah\\Semester V\\TA\\Implementasi\\testing.csv")

    X1training <- trainingData$open
    X2training <- trainingData$high
    X3training <- trainingData$low
    X4training <- trainingData$close
    X5training <- trainingData$volume
    targetTraining <- trainingData$target

    X1testing <- testingData$open
    X2testing <- testingData$high
    X3testing <- testingData$low
    X4testing <- testingData$close
    X5testing <- testingData$volume
    targetTesting <- testingData$target

    xTraining <- cbind(X1training,X2training,X3training,X4training,X5training)

    sum.trainingData <- data.frame(xTraining,targetTraining)

    net.sum <- neuralnet(targetTraining~X1training+X2training+X3training+X4training+X5training, sum.trainingData, hidden=5,act.fct="logistic")

    xTesting <- cbind(X1testing,X2testing,X3testing,X4testing,X5testing)

    sum.testingData <- data.frame(xTesting,targetTesting)

    result <- compute(net.sum,sum.testingData[,1:5])

    return(result)
}

输出生成如下:

enter image description here

这里的程序从Java访问R的结果。

public static void main(String[] args) {

    RConnection connection = null;

    try {
        /* Create a connection to Rserve instance running on default port
         * 6311
         */
        connection = new RConnection();

  //Directory of R script
        connection.eval("source('D:\\\\Kuliah\\\\Semester V\\\\TA\\\\Implementasi\\\\R\\\\neuralNet.R')");

 //Call method
        double output = connection.eval("myneuralnetscript()").asDouble();

        System.out.println(output);   
} catch (RserveException | REXPMismatchException e) {
        System.out.println("There is some problem indeed...");
    }
}

然而,出现的输出是&#34;确实存在一些问题......&#34;。

1 个答案:

答案 0 :(得分:0)

请不要仅仅为了打印无用的消息而捕获异常。删除你的try catch并声明main以抛出异常。这样你就会看到实际的错误。

Rserve没有在6311上本地运行,或者它没有评估,或者第二次评估的结果不能被强制转换成一个双。

运行eval时执行

tryCatch({CODE},e=function ()e)
而是

并检查return是否继承自try-error并获取消息