使用Accord.net获取数据点到其质心的距离

时间:2016-12-13 14:40:49

标签: f# cluster-analysis accord.net

我正在使用Accord.net library进行一些群集工作。最后,我试图找到与the elbow method一起使用的最佳簇数,这需要一些相对简单的计算。但是,我很难获得所需的值,以确定在KMeans建模中使用的 K 的最佳数量。

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

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)|]

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

正如我所提到的,我希望确定在K群集中使用的KMeans的正确数量。我只是想我会使用the second paragraph of this Stats.StackExchange.com answer中列出的简单算法。 请注意,我并不反对使用" Gap Statistic"链接到最顶层答案的底部。

1 个答案:

答案 0 :(得分: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)找到值的平方根。

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