Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {
        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;

like image 602
Lefteris Avatar asked Mar 14 '26 20:03

Lefteris


1 Answers

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.

like image 102
shirowww Avatar answered Mar 16 '26 10:03

shirowww



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!