Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Using Weka in Java

  Asked By: Jody    Date: May 24    Category: Java    Views: 4016

I'd be very thankful if anyone has got a working sample of java code using Weka API; but not the usual simple applet codes over the Internet!
I'm trying to study classification and clustering using Weka APIs. So it'd be cool if some DB (or even domestic arff dataset file) is attached to the reply too.



1 Answer Found

Answer #1    Answered By: Bellona Lopez     Answered On: May 24

below is a code  snippet for loading a decision tree and classifying some new instances using it.

//this file is a decision tree model file, created using the weka software
String model_file = "./tree.model";

// input new instances which we want to label
String descriptors_file = "./Not_Labeled.arff";

//instances labeled using the decision tree. this file will
//hold the classified category for each instance
String output_file = "./labeled.txt";

//loads the classifier
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream(model_file));
Classifier cls = (Classifier) ois.readObject();

//loads the input instances
Instances unlabeled = new Instances(
new BufferedReader(
new FileReader(descriptors_file)));

// set class attribute
unlabeled.setClassIndex(unlabeled.numAttributes() - 1);

// create copy
Instances labeled = new Instances(unlabeled);

// label instances
for (int i = 0; i < unlabeled.numInstances(); i++) {
clsLabel = cls.classifyInstance(unlabeled.instance(i));
String className=labeled.classAttribute().value((int)clsLabel);

BufferedWriter writer = new BufferedWriter(
new FileWriter(output_file));

for (int i = 0; i < unlabeled.numInstances(); i++) {
clsLabel = labeled.instance(i).classValue();

writer.write(labeled.classAttribute().value((int)clsLabel) + "\n");

Didn't find what you were looking for? Find more on Using Weka in Java Or get search suggestion and latest updates.