Dima
Dima

Reputation: 8662

How to use R model in java to predict with multiple models?

I have this constructor:

public Revaluator(File model,PrintStream ps) {
    modelFile=model;
    rsession=Rsession.newInstanceTry(ps, null);
    rsession.eval("library(e1071)");
    rsession.load(modelFile);

}

i want to load a model and predict with it. the problem that Rsession.newInstanceTry(ps, null); is always the same session, so if i load another model, like:

Revaluator re1=new Revaluator(new File("model1.RData"),System.out);
Revaluator re2=new Revaluator(new File("model2.RData"),System.out);

Both re1 and re2 using the same model, since the var name is model, so only the last one loaded.

the evaluate function:

public REXP evaluate(Object[] arr){
    String expression=String.format("predict(model, c(%s))", J2Rarray(arr));
    REXP ans=rsession.eval(expression);
    return ans;
}
//J2Rarray just creates a string from the array like "1,2,true,'hello',false"

i need to load about 250 predictors, is there a way to get every instance of Rsession as a new separated R Session?

Upvotes: 3

Views: 1129

Answers (1)

Stefan Winkler
Stefan Winkler

Reputation: 3966

You haven't pasted all of your code in your question, so before trying the (complicated) way below, please rule out the simple causes and make sure that your fields modelFile and rsession are not declared static :-)

If they are not:

It seems that the way R sessions are created is OS dependent.

On Unix it relies on the multi-session ability of R itself, on Windows it starts with Port 6311 and checks if it is still free. If it's not, then the port is incremented and it checks again, if it's free and so on.

Maybe something goes wrong with checking free ports (which OS are you working on?).

You could try to configure the ports manually and explicitly start different local R servers like this:

Logger simpleLogger = new Logger() {

        public void println(String string, Level level) {
            if (level == Level.WARNING) {
                p.print("! ");
            } else if (level == Level.ERROR) {
                p.print("!! ");
            }
            p.println(string);
        }

        public void close() {
            p.close();
        }
    };

RserverConf serverConf = new RserverConf(null, staticPortCounter++, null, null, null);
Rdaemon server = new Rdaemon(serverConf, this);
server.start(null);
rsession = Rsession.newInstanceTry(serverConf);

If that does not work, please show more code of your Revaluator class and give details about which OS you are running on. Also, there should be several log outputs (at least if the log level is configured accordingly). Please paste the logged messages as well.

Maybe it could also help to get the source code of rsession from Google Code and use a debugger to set a breakpoint in Rsession.begin(). Maybe this can help figuring out what goes wrong.

Upvotes: 2

Related Questions