- 第一个问题(中心是我数据的一部分吗?):
不,质心不是您的数据的成员。它们是在数据集中随机生成的。质心可能会落在一个数据点上,但这只是巧合,质心仍然是一个单独的点。
- 第二个问题(如何找到离我的中心最近的数据点?)
它不能在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