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)+" ");
}
}
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With