【问题标题】:How to visualize k-means centroids for each iteration?如何可视化每次迭代的 k-means 质心?
【发布时间】:2015-01-19 13:11:36
【问题描述】:

我想通过绘制从初始集群的起始值(在 (3,5),(6,2),(8,3))到集群中心。 每次迭代可能对应于具有质心和聚类的单个图。

给定:

                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

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

【问题讨论】:

标签: r k-means


【解决方案1】:

尝试使用tryCatch 自动完成转换时停止的过程: 我使用 iris 数据集,因为 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
}

结果:

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

【讨论】:

  • 非常好,非常感谢您提供的功能。我怎样才能在(3,5),(6,2),(8,3)处包含起始质心?使用 iris 复制和粘贴代码只会以图形方式生成第二个迭代
  • 只需保存一个起始矩阵start &lt;- matrix(c(3,5,6,2,8,3), 3, byrow = TRUE) 并在第三行执行..., centers = start, ... 而不是..., centers = 3, ...
  • 是的,就是这样。谢谢。但是,省略了初始图形迭代 iter1。只显示最后一个,即 iter 2。使用 iris 从上面复制您的示例,我也只有 iter 2。
  • 使用 RStudio 来点击图表,或par(mfrow=c(2,1)) 将它们绘制在一张图像中或使用png 保存图表,请参阅?png 这是如何工作的
  • 问题更多是关于迭代而不是情节。如果我有需要更多迭代才能找到质心的数据,我该如何扩展您的代码。因为将随机数据集放入您的代码中会返回两次迭代...再次感谢
猜你喜欢
  • 2020-04-09
  • 2017-09-12
  • 2020-02-21
  • 1970-01-01
  • 1970-01-01
  • 2019-05-14
  • 2019-12-18
  • 2016-07-29
  • 2017-03-13
相关资源
最近更新 更多