如何为每次迭代可视化k均值质心?

时间:2014-11-21 11:39:20

标签: r k-means

我想通过从初始簇的起始值(at(3,5),(6,2),(8,3))绘制算法的迭代来图形化地说明k-means的行为,直到集群中心。 每次迭代可以对应于具有质心和簇的单个图。

假设:

                x<-c(3,6,8,1,2,2,6,6,7,7,8,8)
                y<-c(5,2,3,5,4,6,1,8,3,6,1,7)


                df<-data.frame(x,y)
                dfCluster<-kmeans(df,centers=3) # with 3 centroids

我想使用前三个元组作为我的初始聚类并跟踪质心的移动。

1 个答案:

答案 0 :(得分:3)

尝试使用tryCatch自动执行转换时停止的过程: 我使用虹膜数据集,因为kmeans需要2次迭代((6,3.5)-Point开关)

set.seed(1337)
df = iris[,1:2]


dfCluster<-kmeans(df,centers=3, iter.max = 1)
  plot(df[,1], df[,2], col=dfCluster$cluster,pch=19,cex=2, main="iter 1")
  points(dfCluster$centers,col=1:5,pch=3,cex=3,lwd=3)

max_iter = 10

for (i in 2:max_iter){
  tryCatch({
    dfCluster <- kmeans(df,centers = dfCluster$centers, iter.max = 1)
    done <- TRUE
  }, 
  warning=function(w) {done <- FALSE})
  plot(df[,1], df[,2], col=dfCluster$cluster,pch=19,cex=2, main=paste("iter",i))
  points(dfCluster$centers,col=1:5,pch=3,cex=3,lwd=3)
  if(done) break
}

结果: enter image description here enter image description here

如果您想在每次迭代步骤中获取坐标,请参阅此处:Getting the coordinates of every observation at each iteration of kmeans in R