【问题标题】:R: Cluster analysis with hclust(). How to get the cluster representatives?R:使用 hclust() 进行聚类分析。如何获得集群代表?
【发布时间】:2016-12-30 18:11:47
【问题描述】:

我正在用 R 进行一些聚类分析。我正在使用hclust() 函数,我想在执行聚类分析后得到每个聚类的聚类代表。

我将集群代表定义为最接近集群质心的实例。

所以步骤是:

  1. 寻找聚类的质心
  2. 寻找集群代表

我已经问过类似的问题,但使用的是 K-means:https://stats.stackexchange.com/questions/251987/cluster-analysis-with-k-means-how-to-get-the-cluster-representatives

在这种情况下,问题在于hclust 没有给出质心!

比如说d是我的数据,到目前为止我所做的是:

hclust.fit1 <- hclust(d, method="single")     
groups1 <- cutree(hclust.fit1, k=3) # cut tree into 3 clusters

## getting centroids ##

mycentroid <- colMeans(CV)    
clust.centroid = function(i, dat, groups1) {    
  ind = (groups1 == i)   
  colMeans(dat[ind,])
}

centroids <- sapply(unique(groups1), clust.centroid, data, groups1)

但是现在,我试图用这段代码来获取集群代表(我在我问的另一个问题中得到了它,对于 k-means):

index <- c()

for (i in 1:3){    
  rowsum <- rowSums(abs(CV[which(centroids==i),1:3] - centroids[i,]))    
  index[i] <- as.numeric(names(which.min(rowsum)))   
}

它说:

“e2[[j]] 中的错误:索引超出限制”

如果有人能给我一点帮助,我将不胜感激。谢谢。

-- (not) 代码的工作示例--

example_data.txt

A,B,C
10.761719,5.452188,7.575762
10.830457,5.158822,7.661588
10.75391,5.500170,7.740330
10.686719,5.286823,7.748297
10.864527,4.883244,7.628730
10.701415,5.345650,7.576218
10.820583,5.151544,7.707404
10.877528,4.786888,7.858234
10.712337,4.744053,7.796390

至于代码:

# Install R packages

#install.packages("fpc")

#install.packages("cluster")

#install.packages("rgl")

library(fpc)
library(cluster)
library(rgl)

CV <- read.csv("example_data")

str(CV)

data <- scale(CV)

d <- dist(data,method = "euclidean")
hclust.fit1 <- hclust(d, method="single") 
groups1 <- cutree(hclust.fit1, k=3) # cut tree into 3 clusters
mycentroid <- colMeans(CV)

clust.centroid = function(i, dat, groups1) {
  ind = (groups1 == i)
  colMeans(dat[ind,])
}

centroids <- sapply(unique(groups1), clust.centroid, CV, groups1)

index <- c()
for (i in 1:3){
  rowsum <- rowSums(abs(CV[which(centroids==i),1:3] - centroids[i,]))
  index[i] <- as.numeric(names(which.min(rowsum)))
}

【问题讨论】:

  • 请参阅stackoverflow.com/questions/5963269/…,了解如何制作可重现的示例。现在,如果没有大量的猜测工作,我们无法从头到尾运行您的代码。
  • 我刚刚添加了我尝试使用的代码。

标签: r cluster-analysis


【解决方案1】:

层次聚类不使用(或计算)代表。

特别是对于单个链接(但它也可能发生在其他链接中),“中心”可以在不同的集群中。只需考虑示例中的前两个数据集:

此外,质心(均值)与欧几里得距离有关。其他距离,可能是一个很差的代表。

所以要小心使用!

无论哪种方式,层次聚类都不会定义或计算代表。您必须自己进行

【讨论】:

    猜你喜欢
    • 2021-03-19
    • 2016-06-03
    • 2013-12-18
    • 2011-09-12
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    相关资源
    最近更新 更多