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) {
e1.printStackTrace();
}
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.
data.setClassIndex(data.numAttributes()-1);
try {
double value=cls.classifyInstance(data.firstInstance());
String prediction=data.classAttribute().value((int)value);
System.out.println("The predicted value of instance "+
Integer.toString(s1)+
": "+prediction);
} catch (Exception e) {
e.printStackTrace();
}
Is this the right way;
That's a correct sample of code that does what you wanted it to do. Another useful method is:
yourClassifier.distributionForInstance(yourInstance);
that returns a double[] with the probabilities of your instance for every class label. It's useful for not-so-clear problems, where class membership could be a fuzzy concept.