2016-12-13 26 views
4

我正在使用Accord.net library做一些聚类工作。最终,我试图找到the elbow method需要一些相对简单的计算使用的群集的最佳数量。但是,我很难得到我需要的值,以便确定在我的KMeans建模中使用的最佳数K使用Accord.net获取从数据点到其质心的距离

我有一些示例数据/代码:

open Accord 
open Accord.Math 
open Accord.MachineLearning 
open Accord.Statistics 
open Accord.Statistics.Analysis 

let x = [| 
    [|4.0; 1.0; 1.0; 2.0|]; 
    [|2.0; 4.0; 1.0; 2.0|]; 
    [|2.0; 3.0; 1.0; 1.0|]; 
    [|3.0; 6.0; 2.0; 1.0|]; 
    [|4.0; 4.0; 1.0; 1.0|]; 
    [|5.0; 10.0; 1.0; 2.0|]; 
    [|7.0; 8.0; 1.0; 2.0|]; 
    [|6.0; 5.0; 1.0; 1.0|]; 
    [|7.0; 7.0; 2.0; 1.0|]; 
    [|5.0; 8.0; 1.0; 1.0|]; 
    [|4.0; 1.0; 1.0; 2.0|]; 
    [|3.0; 5.0; 0.0; 3.0|]; 
    [|1.0; 2.0; 0.0; 0.0|]; 
    [|4.0; 7.0; 1.0; 2.0|]; 
    [|5.0; 3.0; 2.0; 0.0|]; 
    [|4.0; 11.0; 0.0; 3.0|]; 
    [|8.0; 7.0; 2.0; 1.0|]; 
    [|5.0; 6.0; 0.0; 2.0|]; 
    [|8.0; 6.0; 3.0; 0.0|]; 
    [|4.0; 9.0; 0.0; 2.0|] 
    |] 

,我可以生成簇很轻松地与

let kmeans = new KMeans 5 

let kmeansMod = kmeans.Learn x 
let clusters = kmeansMod.Decide x 

,但我怎么能计算出从任何给定的数据点x到它的距离分配的集群?我没有看到KMeans Cluster Collection class documentation中的任何内容,这表明已经为此问题实施了一种方法。

它似乎应该是相对简单的计算这个距离,但我很茫然。难道是因为做这样的事情

let dataAndClusters = Array.zip clusters x 

let getCentroid (m: KMeansClusterCollection) (i: int) = 
    m.Centroids.[i] 

dataAndClusters 
|> Array.map (fun (c, d) -> (c, (getCentroid kmeansMod c) 
           |> Array.map2 (-) d 
           |> Array.sum)) 

返回

val it : (int * float) [] = 
    [|(1, 0.8); (0, -1.5); (1, -0.2); (0, 1.5); (0, -0.5); (4, 0.0); (2, 1.4); 
    (2, -3.6); (2, 0.4); (3, 0.75); (1, 0.8); (0, 0.5); (1, -4.2); (3, -0.25); 
    (1, 2.8); (4, 0.0); (2, 1.4); (3, -1.25); (2, 0.4); (3, 0.75)|] 

我是不是正确地计算这个距离,容易吗?我怀疑不是。

正如我所提到的,我期待确定在KMeans聚类中使用的K的正确数量。我只是认为我会使用the second paragraph of this Stats.StackExchange.com answer中列出的简单算法。 请注意,我不反对使用顶部答案底部的“差距统计”。

+0

您应该能够使用Scores()方法而不是Decide()计算距离其最近的集群的距离。 – Cesar

回答

0

原来,我不是正确计算距离,但我很接近。

做了一些更多的挖掘,我看到了this similar question, but for the R language,并在我自己的R会话中破坏了接受的答案中列出的过程。

的步骤似乎是非常简单的:

1. From each data value, subtract the centroid values 
2. Sum the differences for a given data/centroid pair 
3. Square the differences 
4. Find the square root of the differences. 

对于我上面的数据。例如,它会打破这样的:

let distances = 
    dataAndClusters 
    |> Array.map (fun (c, d) -> (c, ((getCentroid kmeansMod c) 
            |> Array.map2 (-) d 
            |> Array.sum 
            |> float) ** 2.0 
            |> sqrt)) 

注:将两条线,

|> float) ** 2.0将该值转换为浮点数,以便它可以平方(即,x**y

|> sqrt)指找到的值的平方根。

可能有一个内置的方法来做到这一点,但我还没有找到它。现在,这对我有用。