sheldonzy
sheldonzy

Reputation: 5941

Java Weka get all Instances with given attribute value

I have an attribute (Using Weka!)

@attribute age {10-19,20-29,30-39,40-49,50-59,60-69,70-79,80-89,90-99}

How can I get an Instances object of all the data that their value in the attribute age is 20-29?

For example, I have Instances data of size 100, and only 10 of those, their value in the attribute age is 20-29, then I want to get an Instances object of those 10 instances.

I couldn't find a descent way to do this. Any help would be appreciated.

Upvotes: 0

Views: 1661

Answers (2)

Vivraan
Vivraan

Reputation: 163

You could also use streams and type deduction, although it'll look a bit unwieldy:

int index = training.attribute("age").index();
String nominalToFilter = "20-29";

var filteredInstances = new Instances(training, 0); // Empty Instances with same header
training.parallelStream()
        .filter(instance -> instance.stringValue(index).equals(nominalToFilter))
        .forEachOrdered(filteredInstances::add);

Upvotes: 1

sheldonzy
sheldonzy

Reputation: 5941

Found one answer.

  1. Find the index of the desired attribute value.

  2. loop through dataset and count number of appearances.

code:

Instances training = loadData("...");
for(Instance instance: training){
    counter += (int)instance.value(i) == index ? 1 : 0;
}

Upvotes: 0

Related Questions