【问题标题】:Finding centers' index using kmeans in R在 R 中使用 kmeans 查找中心的索引
【发布时间】:2015-03-06 05:42:37
【问题描述】:

我正在使用 R 中的 kmeans,并使用此代码行来查找我的数据中心。

res=kmeans(data,centers=5)

我可以使用此代码到达我的中心:

res$centers

我的第一个问题是:它们是我数据的成员还是恰好是 5 个数据中心?

如果中心是我的数据点,我怎样才能达到我的中心的索引?

如果中心不是我的数据点,我如何找到离这些中心最近的数据点?

谢谢

算法网址here

【问题讨论】:

    标签: r statistics k-means


    【解决方案1】:
    1. 第一个问题(中心是我数据的一部分吗?):

    不,质心不是您的数据的成员。它们是在数据集中随机生成的。质心可能会落在一个数据点上,但这只是巧合,质心仍然是一个单独的点。

    1. 第二个问题(如何找到离我的中心最近的数据点?)

    它不能在kmeans 函数中发生,但你自己很容易做到。请参阅以下示例:

    library(stats)
    x <- matrix(runif(3000),ncol=3 ) #create a 3-column matrix
    mymod <- kmeans(x=x, centers=3)  #run the kmeans model
    
    x <- cbind(x,1:nrow(x)) #add index id (the row number) so that we can find the nearest data point later
    
    #find nearest data point for the 1st cluster for this example
    cluster1  <- data.frame(x[mymod$cluster==1,]) #convert to data.frame to work with dplyr
    
    
    library(dplyr)
    
    #calculate the euclidean distance between each data point in cluster 1 and the centroid 1
    #store in column dist
    cluster1 <- cluster1 %>% mutate(dist=sqrt(  (cluster1[,1] - mymod$centers[1,1])^2 +
                                                (cluster1[,2] - mymod$centers[1,2])^2 +
                                                (cluster1[,3] - mymod$centers[1,3])^2 ) 
                        )
    
    
    #nearest point to cluster 1
    > cluster1[which.min(cluster1$dist), ]
              X1        X2        X3  X4       dist
    86 0.3801898 0.2592491 0.6675403 280 0.04266474
    

    如上图所示,距离中心 1 最近的数据点是 matrix x 中的第 280 行

    您可以对每个中心执行完全相同的操作。如果您有很多中心,那么只需编写一个函数并在lapply 中使用。

    希望有帮助!

    附:欧式距离计算公式为here

    【讨论】:

    • 很高兴有帮助:)
    猜你喜欢
    • 2016-05-10
    • 2021-02-04
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    相关资源
    最近更新 更多