3
votes

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;

2
Have you checked example on weka site? weka.wikispaces.com/Use+WEKA+in+your+Java+code - milos.ai

2 Answers

1
votes

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.

0
votes

See here Java code with slides and textual dataset. It trains a machine, loads the model and classify real time unseen textual data. Very easy to follow https://github.com/drelhaj/MachineLearning