我想根据预先确定的中心点(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中还有很多东西要学,任何帮助都非常感谢。
这是使用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)
执行centers
聚类后,会自动评估kmeans
。事实上,确定centers
是分成群组的关键点。我认为可以帮助你的几个选项。
iter.max
。您可以在1
函数调用中将其设置为kmeans
。这不保证保持中心固定,但如果您处理大型数据集,更改将会更少。dummy
周围的实际数据集中添加许多centers
数据。这将为预先确定的centers
增加额外的重量。最有可能的centers
将保持不变。