如何使用weka kdtree

时间:2015-06-20 07:08:28

标签: java nullpointerexception weka nearest-neighbor

我正在尝试使用像这样的weka KDTree实现来获得k个最近的邻居:

    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));
    }

但它会在NullPointerException电话中抛出kNearestNeighbours

  

线程“main”中的异常java.lang.NullPointerException at   weka.core.neighboursearch.KDTree.findNearestNeighbours(KDTree.java:308)     在   weka.core.neighboursearch.KDTree.kNearestNeighbours(KDTree.java:390)     在blah.App.main(App.java:60)

我在文档中找不到任何提示,并且异常消息没有用。知道这里可能出现什么问题吗?

1 个答案:

答案 0 :(得分:2)

好吧,使用没有参数的构造函数并在下一步中设置param解决了这个问题。我的意思是我改变了

    KDTree knn = new KDTree(ds);

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

它有效。我不知道该说什么,只是祝贺韦卡!