Search code examples
javaweka

Weka classify an instance


I try to classify an instance having an arff file as trained data. The problem is that when I try to create the new Instance I get the exception:

java.lang.ArrayIndexOutOfBoundsException: -1

Here is the simple code for creating the new Instance:

Instance instance = new Instance(2);
instance.setValue(new Attribute("attr1"), 1);
instance.setValue(new Attribute("attr2"), 1);

The exception occurs when I call the setValue method.

Any help please?

Update after Marcin's response

I use weka 3.6.11. If I use the attributes from the training data, I get another exception when I try to classify the new Instance. For example, if I use

 Instance newInstance = new Instance(instances.numAttributes());
 for (int i = 0; i < instances.numAttributes(); i++) {

    Attribute attr = instances.attribute(i);
    newInstance.setValue(attr, 0);
 }

 classifier.classifyInstance(newInstance));

I get the exception java.lang.IllegalArgumentException: Instance has no dataset assigned!! at the last line


Solution

  • Which version of weka do you use? I think you can't instantiate Instance, because it is an interface. Moreover, when you create new Attribute with: new Attribute("attr1") it gets -1 as an attribute index. If you have your training Instances from arff file, use attribute from them when you create a new Instance.

    Create a new weka Instance

    http://weka.wikispaces.com/Programmatic+Use