Lefteris Lefteris - 9 months ago 54
Java Question

Weka - How to use classifier in Java

I have created a model in Weka Explorer, and i saved it as a .model file

First, i load the saved model from my Java code

Classifier cls = null;
try {
cls = (Classifier) weka.core.SerializationHelper.read("Model.model");
} catch (Exception e1) {

Then, i read the Instance which i want to classify, from an .arff file

BufferedReader reader = new BufferedReader(new FileReader(file));
ArffReader arff = new ArffReader(reader);
Instances data = arff.getData();

The file, contains only one instance. The value of the class attribute is '?'.
With the code below, i try to make the classification of the instance.

try {

double value=cls.classifyInstance(data.firstInstance());

String prediction=data.classAttribute().value((int)value);

System.out.println("The predicted value of instance "+
": "+prediction);
} catch (Exception e) {

Is this the right way;


That's a correct sample of code that does what you wanted it to do. Another useful method is:


that returns a double[] with the probabilities of your instance for avery class label. It's useful for not-so-clear problems, where class membership could be a fuzzy concept.