2017-12-27 1445 views
1

我想根據預先確定的中心點(my_center_Points)將Long和Lats(my_long_lats)列表分組。在R中設置kmeans的靜態中心

當我運行: -

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學習,任何幫助真的很感激。

+2

也許你需要一個距離度量,而不是點之間的歐幾里得距離? – jsb

回答

1

centers會在執行kmeans聚類後自動進行評估。實際上,確定centers是劃分成羣集羣的關鍵點。我認爲這可以幫助你的幾個選項。

  1. 限制iter.max。你可以在kmeans函數調用中將其設置爲1。這並不能保證固定中心,但如果你正在處理大量的數據集,變化將會減少。

  2. 使用虛擬數據。您可以在選定的centers附近的實際數據集中添加多個dummy數據。這將會沿着預先確定的centers增加額外的重量。最有可能的centers將保持不變。

+0

#2似乎也會對我很好。謝謝! – Coopa

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) 
+0

是的這種方法更符合我的需求,謝謝! – Coopa