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