【发布时间】:2016-12-30 18:11:47
【问题描述】:
我正在用 R 进行一些聚类分析。我正在使用hclust() 函数,我想在执行聚类分析后得到每个聚类的聚类代表。
我将集群代表定义为最接近集群质心的实例。
所以步骤是:
- 寻找聚类的质心
- 寻找集群代表
我已经问过类似的问题,但使用的是 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