I'm trying to get k nearest neighbors using weka KDTree
implementation like this:
ArrayList<ArrayList<Double>> ar = new ArrayList<ArrayList<Double>>();
ArrayList<Double> d1 = new ArrayList<Double>();
d1.add(1.1);
d1.add(1.1);
ArrayList<Double> d2 = new ArrayList<Double>();
d2.add(2.2);
d2.add(2.2);
ArrayList<Double> d3 = new ArrayList<Double>();
d3.add(3.3);
d3.add(3.3);
ar.add(d1);
ar.add(d2);
ar.add(d3);
Attribute a1 = new Attribute("attr1", 0);
Attribute a2 = new Attribute("attr2", 0);
FastVector attrs = new FastVector();
attrs.addElement(a1);
attrs.addElement(a2);
Instances ds = new Instances("ds", attrs, 10);
for (ArrayList<Double> d : ar) {
Instance i = new Instance(2);
i.setValue(a1, d.get(0));
i.setValue(a2, d.get(1));
ds.add(i);
}
Instance target = new Instance(2);
target.setValue(a1, 7);
target.setValue(a2, 7);
KDTree knn = new KDTree(ds);
Instances targetDs = new Instances("target", attrs, 1);
targetDs.add(target);
Instances nearestInstances = knn.kNearestNeighbours(targetDs.firstInstance(), 2);
for (int i = 0; i < nearestInstances.numInstances(); i++) {
System.out.println(nearestInstances.instance(i).value(a1) + ", "
+ nearestInstances.instance(i).value(a2));
}
But it throws a NullPointerException
in kNearestNeighbours
call:
Exception in thread "main" java.lang.NullPointerException at weka.core.neighboursearch.KDTree.findNearestNeighbours(KDTree.java:308) at weka.core.neighboursearch.KDTree.kNearestNeighbours(KDTree.java:390) at blah.App.main(App.java:60)
I couldn't find any hint in docs and the exception message is of no use. Any idea what might be the problem here?
Well, using constructor without parameter and setting the param in next step solved the issue here. I mean I changed
to
and it works. I don't know what to tell, just congrats weka!