R 和 Java + WEKA 之间计算最近邻的差异

A discrepancy in computing nearest neighbours between R and Java + WEKA

我正在调试一个库和另一个涉及计算 k 最近邻的实现。我用一个我很难理解的例子来提出问题。

首先我会用一个玩具示例来解释演示,然后显示导致问题的输出。

任务

此处的演示读取一个包含 10 个二维数据点的 csv 文件。任务是找到所有数据点到第一个数据点的距离,并以非递减顺序列出所有点和到第一个数据点的距离。

基本上,这是基于 kNN 的算法的一个组成部分,当我执行 Java 版本(库的组成部分)和用 R 编写它时,我发现了差异。为了证明差异,请考虑以下代码。

代码 1:Java + WEKA

下面的代码使用了Java并且WEKA. I have used LinearNNSearch to compute the nearest neighbours. The cause of using this is because the LinearNNSearch用于我正在调试的特定库and/or与R代码进行比较。

import weka.core.converters.CSVLoader;
import weka.core.Instances;
import weka.core.DistanceFunction;
import weka.core.EuclideanDistance;
import weka.core.Instances;
import weka.core.neighboursearch.LinearNNSearch;
import java.io.File;

class testnn
{
  public static void main (String args[]) throws Exception
  {
    // Load csv
    CSVLoader loader = new CSVLoader ();
    loader.setSource (new File (args[0]));

    Instances df = loader.getDataSet ();

    // Set the LinearNNSearch object
    EuclideanDistance dist_obj = new EuclideanDistance ();

    LinearNNSearch lnn = new LinearNNSearch ();
    lnn.setDistanceFunction(dist_obj);
    lnn.setInstances(df);
    lnn.setMeasurePerformance(false);

    // Compute the K-nearest neighbours of the first datapoint (index 0).
    Instances knn_pts = lnn.kNearestNeighbours (df.instance (0), df.numInstances ());

    // Get the distances.
    double [] dist_arr = lnn.getDistances ();

    // Print
    System.out.println ("Points sorted in increasing order from ");
    System.out.println (df.instance (0));
    System.out.println ("V1,\t" + "V2,\t" + "dist");
    for (int j = 0; j < knn_pts.numInstances (); j++)
    {
      System.out.println (knn_pts.instance (j) + "," + dist_arr[j]);
    }
  }
}

代码 2:R

为了计算距离,我使用 dist. Using daisy 也得到了相同的答案。

// Read file
df <- read.csv ("dat.csv", header = TRUE);

// All to all distances, and select distances of points from  first datapoint (index 1)
dist_mat <- as.matrix (dist (df, diag=TRUE, upper=TRUE, method="euclidean"));
first_pt_to_all <- dist_mat[,1];

// Sort the datapoints and also record the ordering
sorted_order <- sort (first_pt_to_all, index.return = TRUE, decreasing = FALSE);

// Prepare dataset with the datapoints ordered in the non-decreasing order of the distance from the first datapoint
df_sorted <- cbind (df[sorted_order$ix[-1],], dist = sorted_order$x[-1]);

// Print
print ("Points sorted in increasing order from ");
print (df[1,]);

print (df_sorted);

产出

为了便于比较,我将两个输出并排放置。 table均以非降序显示点数。

     R                                              Java + WEKA
[1] "Points sorted in increasing order from "   Points sorted in increasing order from 
        V1       V2
1 0.560954 0.313231                      0.560954,0.313231
         V1        V2      dist              V1,        V2,     dist
5  0.866816  0.476897 0.3468979          0.866816,0.476897,0.3280721928065624
10 0.262637  0.554558 0.3837079          0.262637,0.554558,0.37871658916675316
4  1.038752  0.396173 0.4849436          1.038752,0.396173,0.43517244797543775
2  0.330345 -0.137681 0.5064604          1.053889,0.486349,0.4795184359817083
7  1.053889  0.486349 0.5224507          1.113799,0.42203,0.506782009966262
6  1.113799  0.422030 0.5634490          0.330345,-0.137681,0.5448256434359463
8  0.416051 -0.338858 0.6679947          0.416051,-0.338858,0.7411841020052856
3  0.870481 -0.302856 0.6894709          0.870481,-0.302856,0.7425541767563134
9  1.386459  0.425101 0.8330507          1.386459,0.425101,0.7451474897289354

问题

距离明显不同,一些数据点排序也不同。

可视化

我绘制了 10 个点并根据它们的排序顺序对它们进行了编号,由图中的数字表示。

因此4、5、6不同。如果两个数据点等距,那么这可以解释不同的顺序,但是没有两个点与第一个数据点等距。

数据集

"V1", "V2"
0.560954,0.313231
0.330345,-0.137681
0.870481,-0.302856
1.038752,0.396173
0.866816,0.476897
1.113799,0.42203
1.053889,0.486349
0.416051,-0.338858
1.386459,0.425101
0.262637,0.554558

问题

如有不明之处或了解更多信息,请发表评论。

如评论中所述,R 距离是正确的。问题是 WEKA 默认值。您使用了:

EuclideanDistance dist_obj = new EuclideanDistance ();

WEKA 中的欧几里得距离具有默认参数。其中之一是 DontNormalize=FALSE,即默认情况下,WEKA 在计算距离之前对数据进行归一化。我在 java 方面帮不上什么忙,所以我将在 R 中执行此操作。如果缩放数据,使每个变量的最小值为零,最大值为一,您将获得 WEKA 提供的距离度量。

NData = Data
NData[,1] = (NData[,1]-min(NData[,1]))/(max(NData[,1])-min(NData[,1]))
NData[,2] = (NData[,2]-min(NData[,2]))/(max(NData[,2])-min(NData[,2]))
dist(NData)

这些距离与您为 WEKA 显示的距离相符。要获得与 R 相同的结果,请查看 WEKA 中 EuclideanDistance 的参数。