How to get k nearest neighbors using weka kdtree

I am trying to get k nearest neighbors using the weka implementation KDTreeas follows:

    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 calls the NullPointerExceptionin call kNearestNeighbours:

An exception is thrown in the main thread java.lang.NullPointerException at weka.core.neighboursearch.KDTree.findNearestNeighbours (KDTree.java:308) in weka.core.neighboursearch.KDTree.kNearestNeighbours (KDTree.javaApp90). main (App.java:60)

I could not find the hints in the docs and the exception message is useless. Any idea what could be the problem here?

+4
source share
1 answer

, . ,

    KDTree knn = new KDTree(ds);

    KDTree knn = new KDTree();
    knn.setInstances(ds);

. , , !

+2

All Articles