How to classify a new instance using a serialized classifier in a Java application

I want to classify a new instance using a serialized classifier. I found this class, but I do not understand this.

arg[2]= class attribute name and index arg[3]= 1 instance to predict from the source dataset

Here is the code for this class:

import weka.core.*;
import weka.classifiers.*;

import java.io.*;

/**
 * A little class for testing deserialization and prediction.
 * 
 * @author FracPete (fracpet at waikat dot ac dot nz)
 */
public class Blah {

   /**
    * Takes 4 arguments:
    * <ol>
    *   <li>serialized model</li>
    *   <li>ARFF file</li>
    *   <li>class attribute name</li>
    *   <li>1-based index of an instance to predict from original dataset</li>
    * </ol>
    */
   public static void main(String[] args) throws Exception {
      // read the arff training file
      BufferedReader reader = new BufferedReader(new FileReader(args[1]));
      Instances in = new Instances(reader);
      in.setClass(in.attribute(args[2]));

      // instance to classify
      int index = Integer.parseInt(args[3]) - 1;
      Instance toClassifyInstance = (Instance) in.instance(index).copy();
      toClassifyInstance.setClassValue(Instance.missingValue());

      // deserialize model
      Classifier cls = null;
      ObjectInputStream ois = new ObjectInputStream(new FileInputStream(args[0]));
      cls = (Classifier) ois.readObject();
      ois.close();

      // PREDICTION
      double clsLabel = cls.classifyInstance(toClassifyInstance);
      String classLabel = in.classAttribute().value((int) clsLabel);

      System.out.println(classLabel + " =?= " + in.instance(index).stringValue(in.classIndex()));
   }
}

Thanks in advance.

+3
source share
2 answers

args [0] - , . - , arff. , , , (, ). args [2] - , arff args [3], , , .

"" , . , . , setDataset () . , checkInstance () .

+4

. , . , , , , , , . , , ObjectOutputStream (http://download.oracle.com/javase/6/docs/api/java/io/ObjectOutputStream.html) , .

, , , , .

0

All Articles