Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to save model and apply it on a test dataset on java

Tags:

java

weka

I have the following code in which I applied a classifier on training data set , I want to save it (with the cross-validation ) as a model . and apply it again on a test data set.

import weka.core.Instances;
import weka.classifiers.trees.J48;
import weka.classifiers.Evaluation;
import java.util.Random;
import java.io.BufferedReader;
import java.io.FileReader ;

public class EECS_738
{
   public static void main(String[] args) throws Exception {
   // training
      BufferedReader reader = null;
      reader=new BufferedReader(new FileReader("/Users/Sumiah/Desktop/ProjectTraining&TestingData/project/EECS738_Train_Project.arff"));
      Instances train =new Instances (reader);
      train.setClassIndex(0);     
      reader.close();

      J48 j48 = new J48();
      j48.buildClassifier(train);
      Evaluation eval = new Evaluation(train);
      eval.crossValidateModel(j48, train, 10 , new Random(1));

      System.out.println(eval.toSummaryString("\n Results \n=====\n",true));
      System.out.println(eval.fMeasure(1)+" "+eval.precision(1)+" "+eval.recall(1)+" ");           
   }   
}
like image 334
may Avatar asked Mar 15 '23 06:03

may


1 Answers

For versions greater than 3.5.5 it's as simple as:

J48 j48 = new J48();
j48.buildClassifier(train);
weka.core.SerializationHelper.write("/some/where/j48.model", j48);

And loading is just:

Classifier cls = (Classifier) weka.core.SerializationHelper.read("/some/where/j48.model");

See here for more info and how to do it in legacy versions!

like image 72
SJB Avatar answered Mar 25 '23 06:03

SJB