Weka Classifying Instance - Java Machine Learning AI

Java examples for Machine Learning AI:weka

Description

Weka Classifying Instance

Demo Code



import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;

import weka.classifiers.trees.J48;
import weka.core.Instances;
import weka.core.Utils;
import weka.core.converters.ConverterUtils.DataSource;


public class WekaClassifyingInstance {
    public static void main(String[] args) throws Exception {
        DataSource source = new DataSource(
                "bank-train.arff");
        Instances instancesTrain = source.getDataSet();
        instancesTrain.setClassIndex(instancesTrain.numAttributes() - 1);

        Instances unlabeled = new Instances(
                new BufferedReader(
                        new FileReader(
                                "bank-test-unlabeled.arff")));
        unlabeled.setClassIndex(unlabeled.numAttributes() - 1);

        Instances labeled = new Instances(unlabeled);

        J48 classifier = new J48();

        String[] options = Utils.splitOptions("-C 0.25 -M 2");
        classifier.setOptions(options);/*ww  w . j  av a 2  s  .  co m*/

        classifier.buildClassifier(instancesTrain);

        for (int i = 0; i < unlabeled.numInstances(); i++) {
            double clsLabel = classifier.classifyInstance(unlabeled
                    .instance(i));
            labeled.instance(i).setClassValue(clsLabel);
            System.out.println(unlabeled.classAttribute().value(
                    (int) clsLabel));

            double[] allLabel = classifier
                    .distributionForInstance(unlabeled.instance(i));

            for (double d : allLabel) {
                System.out.print(d);
            }
            System.out.println();
        }

        BufferedWriter writer = new BufferedWriter(new FileWriter(
                "bank-result-labeled.arff"));
        writer.write(labeled.toString());
        writer.newLine();
        writer.flush();
        writer.close();
    }
}

Related Tutorials