【问题标题】:Getting the coordinates of every observation at each iteration of kmeans in R在 R 中的 kmeans 的每次迭代中获取每个观察值的坐标
【发布时间】:2014-05-19 22:15:27
【问题描述】:

我想在 R 中构建 kmeans 聚类算法的动画。动画将显示数据集中以 2(或 3)维绘制的每个观察值(行),然后让它们移动到它们的集群中每次迭代都会过去。

为此,我需要在每次迭代时访问观察的坐标。我可以在 kmeans 包的哪个位置访问这些?

谢谢,

【问题讨论】:

  • 在 k-means 算法中,观测值的坐标不变。相反,集群的质心(均值)从一个迭代移动到下一个迭代。 k-means 算法非常简单,您应该能够在几分钟内为您的动画编写一个基本版本。

标签: r k-means


【解决方案1】:

我认为kmeans() 不会输出这种跟踪信息。您最好的办法可能是多次重新运行kmeans(),并保留集群中心。

set.seed(1)
clus.1 <- kmeans(iris[,1:2],5,iter.max=1)
clus.2 <- kmeans(iris[,1:2],centers=clus.1$centers,iter.max=1)
clus.3 <- kmeans(iris[,1:2],centers=clus.2$centers,iter.max=1)

changing <- which(apply(cbind(clus.1$cluster,clus.2$cluster,clus.3$cluster),1,sd)>0)
changing
opar <- par(mfrow=c(1,3))
    plot(iris[,c(1,2)],col=clus.1$cluster,pch=19,main="Iteration 1")
    points(iris[changing,c(1,2)],pch=21,cex=2)
    plot(iris[,c(1,2)],col=clus.2$cluster,pch=19,main="Iteration 2")
    points(iris[changing,c(1,2)],pch=21,cex=2)
    plot(iris[,c(1,2)],col=clus.3$cluster,pch=19,main="Iteration 3")
    points(iris[changing,c(1,2)],pch=21,cex=2)
par(opar)

我指出确实改变集群成员的点;不幸的是,只有一个人这样做,因为kmeans() 收敛得非常快;-)

您写道,您希望“在每次迭代时让它们移动到它们的集群中”。当然,点在聚类算法中不会移动。所以像这样的颜色编码表示是你最好的选择。

二维以上的可以试试pairs(),或者只关注二维。准备好解释为什么 n 维集群在投影到二维时看起来不像“集群”。

【讨论】:

  • 很好,很好的答案,谢谢。是的,对不起,我的意思是质心动画。似乎没有将其标记为正确的选项。我找到的另一个链接是这个:mcube.nju.edu.cn/jokergoo/animation-of-kmeans-clustering.html
  • 感谢您的反馈。如果您想“接受”我的回答,只需单击答案投票数下方的复选标记即可。
【解决方案2】:

您可以使用tryCatch 自动执行收敛过程,如下所示

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)

cent <- list(dfCluster$centers)

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})
  cent[[i]] <- dfCluster$centers
  if(done) break
}

cent 是一个包含每次迭代时集群中心的列表

cent
[[1]]
  Sepal.Length Sepal.Width
1     6.795833    3.081250
2     5.769231    2.678846
3     5.006000    3.428000

[[2]]
  Sepal.Length Sepal.Width
1     6.812766    3.074468
2     5.773585    2.692453
3     5.006000    3.428000

要绘制此图,请参阅How to visualize k-means centroids for each iteration?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 1970-01-01
    相关资源
    最近更新 更多