如何绘制群集内的簇内平方和的图?

时间:2014-09-21 12:52:12

标签: r plot cluster-analysis hierarchical-clustering

我有一个R的聚类图,而我想用wss图来优化聚类的“肘部标准”,但我不知道如何绘制给定聚类的wss图,任何人都会帮助我?

这是我的数据:

Friendly<-c(0.467,0.175,0.004,0.025,0.083,0.004,0.042,0.038,0,0.008,0.008,0.05,0.096)
Polite<-c(0.117,0.55,0,0,0.054,0.017,0.017,0.017,0,0.017,0.008,0.104,0.1)
Praising<-c(0.079,0.046,0.563,0.029,0.092,0.025,0.004,0.004,0.129,0,0,0,0.029)
Joking<-c(0.125,0.017,0.054,0.383,0.108,0.054,0.013,0.008,0.092,0.013,0.05,0.017,0.067)
Sincere<-c(0.092,0.088,0.025,0.008,0.383,0.133,0.017,0.004,0,0.063,0,0,0.188)
Serious<-c(0.033,0.021,0.054,0.013,0.2,0.358,0.017,0.004,0.025,0.004,0.142,0.021,0.108)
Hostile<-c(0.029,0.004,0,0,0.013,0.033,0.371,0.363,0.075,0.038,0.025,0.004,0.046)
Rude<-c(0,0.008,0,0.008,0.017,0.075,0.325,0.313,0.004,0.092,0.063,0.008,0.088)
Blaming<-c(0.013,0,0.088,0.038,0.046,0.046,0.029,0.038,0.646,0.029,0.004,0,0.025)
Insincere<-c(0.075,0.063,0,0.013,0.096,0.017,0.021,0,0.008,0.604,0.004,0,0.1)
Commanding<-c(0,0,0,0,0,0.233,0.046,0.029,0.004,0.004,0.538,0,0.146)
Suggesting<-c(0.038,0.15,0,0,0.083,0.058,0,0,0,0.017,0.079,0.133,0.442)
Neutral<-c(0.021,0.075,0.017,0,0.033,0.042,0.017,0,0.033,0.017,0.021,0.008,0.717)

data <- data.frame(Friendly,Polite,Praising,Joking,Sincere,Serious,Hostile,Rude,Blaming,Insincere,Commanding,Suggesting,Neutral)

这是我的聚类代码:

cor <- cor (data)
dist<-dist(cor)
hclust<-hclust(dist)
plot(hclust)

运行上面的代码后我会得到一个树形图,而我怎么画这样的图:

enter image description here

1 个答案:

答案 0 :(得分:9)

如果我按照您的意愿行事,那么我们需要一个计算WSS的函数

wss <- function(d) {
  sum(scale(d, scale = FALSE)^2)
}

以及此wss()函数的包装器

wrap <- function(i, hc, x) {
  cl <- cutree(hc, i)
  spl <- split(x, cl)
  wss <- sum(sapply(spl, wss))
  wss
}

此包装器采用以下参数,输入:

  • i将数据剪切为
  • 的群集数量
  • hc层次聚类分析对象
  • x原始数据
然后

wrap将树形图切割为i个簇,将原始数据拆分为cl给出的聚类成员资格,并计算每个聚类的WSS。将这些WSS值相加以给出该群集的WSS。

我们使用sapply在群集1,2,...,nrow(data)

的数量上运行所有这一切
res <- sapply(seq.int(1, nrow(data)), wrap, h = cl, x = data)

可以使用

绘制一个screeplot
plot(seq_along(res), res, type = "b", pch = 19)

以下是使用着名的Edgar Anderson Iris数据集的示例:

iris2 <- iris[, 1:4]  # drop Species column
cl <- hclust(dist(iris2), method = "ward.D")

## Takes a little while as we evaluate all implied clustering up to 150 groups
res <- sapply(seq.int(1, nrow(iris2)), wrap, h = cl, x = iris2)
plot(seq_along(res), res, type = "b", pch = 19)

这给出了:

enter image description here

我们可以通过显示前1:50群集来放大

plot(seq_along(res[1:50]), res[1:50], type = "o", pch = 19)

给出了

enter image description here

您可以通过适当的并行替代方案运行sapply()来加快主要计算步骤,或者只对少于nrow(data)个群集进行计算,例如

res <- sapply(seq.int(1, 50), wrap, h = cl, x = iris2) ## 1st 50 groups