Search code examples
javaapimachine-learningwekaj48

How do I test a single Instance in Weka using a model that I have built?


I am trying to test a single instance using weka API in Java. My aim is to predict the class value of the single instance in the test.arff file.

My java code looks like this,

import weka.core.Instances;
import weka.classifiers.Evaluation;
import weka.classifiers.trees.J48;
import weka.classifiers.*;

import java.io.*;
import java.util.Random;

public class WekaNew {

    public static void main(String[] args) throws Exception{
        // TODO Auto-generated method stub
        System.out.println("Weka Tool");

        BufferedReader breader = new BufferedReader(new FileReader("train.arff"));
        Instances train = new Instances(breader);
        train.setClassIndex(train.numAttributes() -1);
        breader.close();    //loading training data

        BufferedReader treader = new BufferedReader(new FileReader("test.arff"));
        Instances test = new Instances(treader);
        test.setClassIndex(test.numAttributes() -1);
        treader.close();        //loading testing data

        Classifier cls = new J48();
        cls.buildClassifier(train);

        Evaluation eval = new Evaluation(train);
        eval.evaluateModelOnce(cls,test);

        System.out.println(eval.toMatrixString("\nConfusion Matrix\n========\n"));

    }

}

The train.arff has 7(attributes)+1(class label) along with 132 instances of data. The test.arff has 7 attributes + 1 class label=? with ONE instance.

I want to predict the class label of the single instance in the test.arff. How do I go about predicting the label and what changes are needed to be made in the dataset and the code?

I tried compiling the java file by "javac -cp "/classpath" WekaNew.java" , it gives the following error "No suitable method found for evaluateModelOnce()"

New to the Weka API and Java in general. Apologies in advance if the question seems repeated.

I have also referred the following questions in Stackoverflow, 1. Test single instance in weka which has no class label 2. Test a single instance in Weka but it does not seem to solve my problem.


Solution

  • This is the signature of evaluateModelOnce:

    public double evaluateModelOnce(Classifier classifier,
                                    Instance instance)
    

    (see http://weka.sourceforge.net/doc.stable/weka/classifiers/Evaluation.html#evaluateModelOnce-weka.classifiers.Classifier-weka.core.Instance-)

    However, you pass in "Instances" instead of "Instance", which are different classes. Thus, this is a syntax error.

    To evaluate a single Weka Instance, you might want to try

        eval.evaluateModelOnce(cls,instances.firstInstance());