[R] How to save/load RWeka models into/from a file?

Kurt Hornik Kurt.Hornik at wu-wien.ac.at
Sun Oct 19 21:16:29 CEST 2008


>>>>> Paulo Cortez writes:

> Achim Zeileis wrote:
>> On Thu, 16 Oct 2008, Paulo Cortez wrote:
>> 
>>> Hi,
>>> 
>>> I want to save a RWeka model into a file, in order to retrive it 
>>> latter with a load function.
>>> 
>>> See this example:
>>> 
>>> library(RWeka)
>>> 
>>> NB <- make_Weka_classifier("weka/classifiers/bayes/NaiveBayes")
>>> model<-NB(formula,data=data,...) # does not run but you get the idea
>>> 
>>> save(model,file="model.dat") # simple save R command
>>> # ...
>>> load("model.dat") # load the model from the previously saved file...
>>> model # should work but I get instead this error:
>>> Error in .jcall(x$classifier, "S", "toString") :
>>> RcallMethod: attempt to call a method of a NULL object.
>>> 
>>> What is wrong and how can I solve this problem?
>> 
>> The R object is just a reference to the corresponding object on the Java 
>> side (in Weka). When you close R, the Java/Weka session is also closed 
>> and the model is gone. Thus, when you load the object again in a new 
>> session, you only have a reference to a Java object that does not live 
>> anymore.
>> Z

> Thanks, I understand now what is happening.

> Yet, I still need to save/load a RWeka model to/from a file.
> Thus, how can I do this? Is it impossible in R? Any help?

Using a current version of rJava, you can register the Java side objects
for serialization using .jcache().

E.g.,

  m1 <- J48(Species ~ ., data = iris)
  .jcache(m1$classifier)

then save/load will work as expected.

Eventually, the above may happen automagically.

-k



More information about the R-help mailing list