如何使用命令行从Weka计算最近邻居?

9
我有一个csv文件,其中每一行都是代表数据点的数字向量。我想要使用weka命令行计算csv文件中每个数据点的最近邻居。我知道如何从命令行执行k最近邻分类,但那不是我想要的。我需要实际的邻居。如何做到这一点?
我希望使用weka而不是其他工具来完成这个任务。
1个回答

6

Weka没有一行代码可以实现您所想的内容(即导入文件,将其转换为实例,然后找到每个实例的所有N近邻)

但是您可以通过以下方式利用Weka和几行Java设置命令行样式的一行代码:

编译以下代码。我使用了Eclipse,但您也可以轻松地在命令行中使用javac - 只需确保在类路径中有weka.jar即可。我在下面的代码中展示了如何从命令行调用此代码。

import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
import weka.core.neighboursearch.LinearNNSearch;

public class WekaCLFindNN {
     public static void main(String[] args) throws Exception {

            //report that the code is running
            System.out.println("Weka Command Line Find Nearest " + args[0] + " Neighbors for each Instance in "  + args[1]); // Display the string.

            //setup datasources, grab instances, and calculate the nearest neighbors
            DataSource source = new DataSource(""+args[1]);
            Instances instances = source.getDataSet();  
            weka.core.neighboursearch.LinearNNSearch knn = new LinearNNSearch(instances);

            //cycle through the dataset and get instances for the nearestneighbors
            for(int j=0;j<instances.numInstances();j++){
            Instances nearestInstances= knn.kNearestNeighbours(instances.instance(j), Integer.parseInt(args[0]));

            //cycle through the instances and printout the nearestneighbors
            System.out.println("\n\n" + instances.instance(j));
            for(int i =0;i<Integer.parseInt(args[0]);i++) 
            {
                System.out.println("\n\t" + nearestInstances.instance(i));

            }

            }

            //close the code
            System.out.println("\n"+"Nearest Neighbors found"); // Display the string.

     }
}

现在只需使用以下命令从命令行运行它。
java -cp weka.jar;。WekaCLFindNN numNN csvfile 这是它在我的机器上的运行截图。请注意,当我运行java时,我将weka.jar文件和WekaCLFindNN文件放在目录中。还要注意,我在Windows下运行此程序,类路径分隔符是分号(;), 如果您在Linux下运行,则必须使用冒号(:)。
如果您想让数据保存在日志文件中,请按以下方式执行:
java -cp weka.jar;。WekaCLFindNN> outputlog
日志文件将如下所示,并且不会有关于数据库的错误信息:
虽然希望能够同时得到最近邻居和它们在原始实例数据集中的索引,但我检查了kNearestNeighbours方法并发现索引数据在报告之前被丢弃了。如果您需要它,那么您就必须继承LinearNNSearch类并编写一个新方法,可以输出实例和索引。
所以我希望这可以帮助你。不幸的是,Weka不会直接提供此功能,但您可以只用几行代码就可以实现。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接