如何为每次迭代显示k均值质心? [英] How to visualize k-means centroids for each iteration?

查看:54
本文介绍了如何为每次迭代显示k均值质心?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过绘制从初始聚类的起始值(在(3,5),(6,2),(8,3))到该算法的迭代算法来绘制k-均值的行为.集群中心. 每次迭代可能对应一个带有质心和聚类的图.

I would like to graphically demostrate the behavior of k-means by plotting iterations of the algorithm from a starting value (at (3,5),(6,2),(8,3)) of initial cluster till the cluster centers. Each iteration may correspond to a single plot with centroids and clusters.

给出:

                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

我想使用前三个元组作为初始簇,并跟踪质心的运动.

I would like to use the first three tuples as my initial cluster and track the movement of the centroids.

推荐答案

尝试使用tryCatch自动完成转化后的停止过程: 我使用虹膜数据集,因为kmeans需要进行2次迭代((6,3.5)点开关)

Try to use tryCatch to automate the the process of stopping when conversion is reached: I use the iris-data set because there kmeans needs 2 iterations (the (6,3.5)-Point switches)

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
}

结果:

如果要在每个迭代步骤获取坐标,请参见此处:

If you want to get the coordinates at each iteration-step see here: Getting the coordinates of every observation at each iteration of kmeans in R

这篇关于如何为每次迭代显示k均值质心?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆