在R中设置kmeans的静态中心

问题描述 投票:1回答:2

我想根据预先确定的中心点(my_center_Points)对Long和Lats(my_long_lats)列表进行分组。

当我跑: -

k <- kmeans(as.matrix(my_long_lats), centers = as.matrix(my_center_Points))

k$centers不等于my_center_Points。

我假设k-means已将我的中心点调整到最佳中心。但我需要的是my_center_Points不会更改并将my_long_lats分组。

在这个link中,他们讨论了设置初始中心但是如何设置一旦我运行k意味着不会改变的中心?或者有更好的聚类算法吗?

我甚至可以尽量减少中心的移动。

我在R中还有很多东西要学,任何帮助都非常感谢。

r k-means
2个回答
1
投票

这是使用geosphere库计算正确计算纬度和经度距离的计算。

变量closestcenter是识别每个点的最近中心的结果。

#define random data
centers<-data.frame(x=c(44,44, 50, 50), y=c(44, 50, 44, 50))
pts<-data.frame(x=runif(25, 40, 55), y=runif(25, 40, 55))

#allocate space
distance<-matrix(-1, nrow = length(pts$x), ncol= length(centers$x))

library(geosphere)
#calculate the dist matrix - the define centers to each point
#columns represent centers and the rows are the data points
dm<-apply(data.frame(1:length(centers$x)), 1, function(x){ replace(distance[,x], 1:length(pts$x), distGeo(centers[x,], pts))})

#find the column with the smallest distance
closestcenter<-apply(dm, 1, which.min)

#color code the original data for verification
colors<-c("black", "red", "blue", "green")
plot(pts , col=colors[closestcenter], pch=19) 

2
投票

执行centers聚类后,会自动评估kmeans。事实上,确定centers是分成群组的关键点。我认为可以帮助你的几个选项。

  1. 限制iter.max。您可以在1函数调用中将其设置为kmeans。这不保证保持中心固定,但如果您处理大型数据集,更改将会更少。
  2. 使用虚拟数据。您可以在选定的dummy周围的实际数据集中添加许多centers数据。这将为预先确定的centers增加额外的重量。最有可能的centers将保持不变。
© www.soinside.com 2019 - 2024. All rights reserved.