R中的聚类分析:确定群集的最佳数量

a0zr77ik  于 2023-01-10  发布在  其他
关注(0)|答案(8)|浏览(192)

如何选择最佳的聚类数来进行k-均值分析?在绘制了以下数据的子集后,多少个聚类数是合适的?如何进行聚类树分析?

n = 1000
kk = 10    
x1 = runif(kk)
y1 = runif(kk)
z1 = runif(kk)    
x4 = sample(x1,length(x1))
y4 = sample(y1,length(y1)) 
randObs <- function()
{
  ix = sample( 1:length(x4), 1 )
  iy = sample( 1:length(y4), 1 )
  rx = rnorm( 1, x4[ix], runif(1)/8 )
  ry = rnorm( 1, y4[ix], runif(1)/8 )
  return( c(rx,ry) )
}  
x = c()
y = c()
for ( k in 1:n )
{
  rPair  =  randObs()
  x  =  c( x, rPair[1] )
  y  =  c( y, rPair[2] )
}
z <- rnorm(n)
d <- data.frame( x, y, z )
iswrvxsc

iswrvxsc1#

如果您的问题是"* 我如何确定多少个聚类适合对我的数据进行kmeans分析?*",那么这里有一些选项。关于确定聚类数量的wikipedia article对其中的一些方法有很好的回顾。
首先,一些可重复的数据(Q中的数据......我不清楚):

n = 100
g = 6 
set.seed(g)
d <- data.frame(x = unlist(lapply(1:g, function(i) rnorm(n/g, runif(1)*i^2))), 
                y = unlist(lapply(1:g, function(i) rnorm(n/g, runif(1)*i^2))))
plot(d)

mydata <- d
wss <- (nrow(mydata)-1)*sum(apply(mydata,2,var))
  for (i in 2:15) wss[i] <- sum(kmeans(mydata,
                                       centers=i)$withinss)
plot(1:15, wss, type="b", xlab="Number of Clusters",
     ylab="Within groups sum of squares")

我们可以得出结论,该方法将指示4个聚类:

    • 两个**。您可以使用fpc包中的pamk函数围绕medoid进行分区,以估计集群的数量。
library(fpc)
pamk.best <- pamk(d)
cat("number of clusters estimated by optimum average silhouette width:", pamk.best$nc, "\n")
plot(pam(d, pamk.best$nc))

# we could also do:
library(fpc)
asw <- numeric(20)
for (k in 2:20)
  asw[[k]] <- pam(d, k) $ silinfo $ avg.width
k.best <- which.max(asw)
cat("silhouette-optimal number of clusters:", k.best, "\n")
# still 4
    • 三个**.卡林斯基准则:另一种诊断有多少聚类适合数据的方法。在这种情况下,我们尝试1到10个组。
require(vegan)
fit <- cascadeKM(scale(d, center = TRUE,  scale = TRUE), 1, 10, iter = 1000)
plot(fit, sortg = TRUE, grpmts.plot = TRUE)
calinski.best <- as.numeric(which.max(fit$results[2,]))
cat("Calinski criterion optimal number of clusters:", calinski.best, "\n")
# 5 clusters!

    • 四**.根据用于期望最大化的贝叶斯信息准则确定最佳模型和聚类数目,通过用于参数化高斯混合模型的分级聚类来初始化
# See http://www.jstatsoft.org/v18/i06/paper
# http://www.stat.washington.edu/research/reports/2006/tr504.pdf
#
library(mclust)
# Run the function to see how many clusters
# it finds to be optimal, set it to search for
# at least 1 model and up 20.
d_clust <- Mclust(as.matrix(d), G=1:20)
m.best <- dim(d_clust$z)[2]
cat("model-based optimal number of clusters:", m.best, "\n")
# 4 clusters
plot(d_clust)

library(apcluster)
d.apclus <- apcluster(negDistMat(r=2), d)
cat("affinity propogation optimal number of clusters:", length(d.apclus@clusters), "\n")
# 4
heatmap(d.apclus)
plot(d.apclus, d)

library(cluster)
clusGap(d, kmeans, 10, B = 100, verbose = interactive())

Clustering k = 1,2,..., K.max (= 10): .. done
Bootstrapping, b = 1,2,..., B (= 100)  [one "." per sample]:
.................................................. 50 
.................................................. 100 
Clustering Gap statistic ["clusGap"].
B=100 simulated reference sets, k = 1..10
 --> Number of clusters (method 'firstSEmax', SE.factor=1): 4
          logW   E.logW        gap     SE.sim
 [1,] 5.991701 5.970454 -0.0212471 0.04388506
 [2,] 5.152666 5.367256  0.2145907 0.04057451
 [3,] 4.557779 5.069601  0.5118225 0.03215540
 [4,] 3.928959 4.880453  0.9514943 0.04630399
 [5,] 3.789319 4.766903  0.9775842 0.04826191
 [6,] 3.747539 4.670100  0.9225607 0.03898850
 [7,] 3.582373 4.590136  1.0077628 0.04892236
 [8,] 3.528791 4.509247  0.9804556 0.04701930
 [9,] 3.442481 4.433200  0.9907197 0.04935647
[10,] 3.445291 4.369232  0.9239414 0.05055486

以下是Edwin Chen实施差距统计的结果:

library(NbClust)
nb <- NbClust(d, diss=NULL, distance = "euclidean",
        method = "kmeans", min.nc=2, max.nc=15, 
        index = "alllong", alphaBeale = 0.1)
hist(nb$Best.nc[1,], breaks = max(na.omit(nb$Best.nc[1,])))
# Looks like 3 is the most frequently determined number of clusters
# and curiously, four clusters is not in the output at all!

如果您的问题是"* 如何生成树状图以可视化聚类分析的结果?*",那么您应该从以下内容开始:
http://www.statmethods.net/advstats/cluster.html
http://www.r-tutor.com/gpu-computing/clustering/hierarchical-cluster-analysis
http://gastonsanchez.wordpress.com/2012/10/03/7-ways-to-plot-dendrograms-in-r/更多奇特的方法请参见此处:http://cran.r-project.org/web/views/Cluster.html
以下是一些例子:

d_dist <- dist(as.matrix(d))   # find distance matrix 
plot(hclust(d_dist))           # apply hirarchical clustering and plot

# a Bayesian clustering method, good for high-dimension data, more details:
# http://vahid.probstat.ca/paper/2012-bclust.pdf
install.packages("bclust")
library(bclust)
x <- as.matrix(d)
d.bclus <- bclust(x, transformed.par = c(0, -50, log(16), 0, 0, 0))
viplot(imp(d.bclus)$var); plot(d.bclus); ditplot(d.bclus)
dptplot(d.bclus, scale = 20, horizbar.plot = TRUE,varimp = imp(d.bclus)$var, horizbar.distance = 0, dendrogram.lwd = 2)
# I just include the dendrogram here

pvclust库也适用于高维数据,它通过多尺度bootstrap重采样计算层次聚类的p值,下面是文档中的示例(不适用于我的示例中的低维数据):

library(pvclust)
library(MASS)
data(Boston)
boston.pv <- pvclust(Boston)
plot(boston.pv)

tvz2xvvm

tvz2xvvm2#

很难再为这样一个复杂的答案添加一些东西,尽管我觉得我们应该在这里提到identify,特别是因为@Ben展示了很多树状图的例子。

d_dist <- dist(as.matrix(d))   # find distance matrix 
plot(hclust(d_dist)) 
clusters <- identify(hclust(d_dist))

identify允许您以交互方式从树状图中选择聚类,并将您的选择存储到列表中。按Esc退出交互模式并返回R控制台。请注意,列表包含索引,而不是行名称(与cutree相反)。

4sup72z8

4sup72z83#

为了确定聚类方法中的最优k-聚类,我通常使用Elbow方法,并伴随并行处理以避免时间消耗。此代码示例如下:

    • 弯头法**
elbow.k <- function(mydata){
dist.obj <- dist(mydata)
hclust.obj <- hclust(dist.obj)
css.obj <- css.hclust(dist.obj,hclust.obj)
elbow.obj <- elbow.batch(css.obj)
k <- elbow.obj$k
return(k)
}
    • 活动弯头平行**
no_cores <- detectCores()
    cl<-makeCluster(no_cores)
    clusterEvalQ(cl, library(GMD))
    clusterExport(cl, list("data.clustering", "data.convert", "elbow.k", "clustering.kmeans"))
 start.time <- Sys.time()
 elbow.k.handle(data.clustering))
 k.clusters <- parSapply(cl, 1, function(x) elbow.k(data.clustering))
    end.time <- Sys.time()
    cat('Time to find k using Elbow method is',(end.time - start.time),'seconds with k value:', k.clusters)

效果很好。

rn0zuynd

rn0zuynd4#

一个简单的解决方案是库factoextra。您可以更改聚类方法和计算最佳组数的方法。例如,如果您想知道k均值的最佳聚类数:

数据:mtcar

library(factoextra)   
fviz_nbclust(mtcars, kmeans, method = "wss") +
      geom_vline(xintercept = 3, linetype = 2)+
      labs(subtitle = "Elbow method")

最后,我们得到一个图,如:

unftdfkk

unftdfkk5#

Ben的回答很棒。但是我很惊讶这里建议的亲和传播(AP)方法仅仅是为了找到k均值方法的聚类数,一般来说AP在聚类数据方面做得更好。请参阅支持此方法的科学论文,在Science中:

**Frey、Brendan J.和Delbert Dueck,《通过在数据点之间传递消息进行聚类》,《科学》315.5814(2007):第972至976段。

因此,如果你不偏向于k均值,我建议直接使用AP,它将对数据进行聚类,而不需要知道聚类的数量:

library(apcluster)
apclus = apcluster(negDistMat(r=2), data)
show(apclus)

如果负欧氏距离不合适,则可以使用同一软件包中提供的其他相似性度量。例如,对于基于斯皮尔曼相关性的相似性,您需要:

sim = corSimMat(data, method="spearman")
apclus = apcluster(s=sim)

请注意,AP包中的相似性函数只是为了简单起见而提供的。事实上,R中的apcluster()函数可以接受任何相关矩阵。之前corSimMat()的相同功能可以通过以下方式完成:

sim = cor(data, method="spearman")

sim = cor(t(data), method="spearman")

这取决于你想在你的矩阵上聚集什么(行或列)。

hfyxw5xn

hfyxw5xn6#

这些方法都很好,但是当试图为更大的数据集找到k时,这些方法在R中可能会非常慢。
我发现的一个很好的解决方案是“RWeka”包,它有效地实现了X均值算法-K均值的扩展版本,扩展更好,并将为您确定最佳的聚类数量。
首先,您需要确保Weka已经安装在您的系统上,并且已经通过Weka的包管理器工具安装了XMeans。

library(RWeka)

# Print a list of available options for the X-Means algorithm
WOW("XMeans")

# Create a Weka_control object which will specify our parameters
weka_ctrl <- Weka_control(
    I = 1000,                          # max no. of overall iterations
    M = 1000,                          # max no. of iterations in the kMeans loop
    L = 20,                            # min no. of clusters
    H = 150,                           # max no. of clusters
    D = "weka.core.EuclideanDistance", # distance metric Euclidean
    C = 0.4,                           # cutoff factor ???
    S = 12                             # random number seed (for reproducibility)
)

# Run the algorithm on your data, d
x_means <- XMeans(d, control = weka_ctrl)

# Assign cluster IDs to original data set
d$xmeans.cluster <- x_means$class_ids
xxslljrj

xxslljrj7#

答案很棒。如果你想给予另一种聚类方法一个机会,你可以使用层次聚类,看看数据是如何分裂的。

> set.seed(2)
> x=matrix(rnorm(50*2), ncol=2)
> hc.complete = hclust(dist(x), method="complete")
> plot(hc.complete)

根据你需要多少类,你可以把你的树状图切割成;

> cutree(hc.complete,k = 2)
 [1] 1 1 1 2 1 1 1 1 1 1 1 1 1 2 1 2 1 1 1 1 1 2 1 1 1
[26] 2 1 1 1 1 1 1 1 1 1 1 2 2 1 1 1 2 1 1 1 1 1 1 1 2

如果你输入?cutree,你会看到定义。如果你的数据集有三个类,它将是cutree(hc.complete, k = 3)cutree(hc.complete,k = 2)的等价物是cutree(hc.complete,h = 4.9)

ss2ws0br

ss2ws0br8#

浏览这么多函数而不考虑性能因素是非常令人困惑的。我知道在可用的包中很少有函数做了很多事情,而不仅仅是找到最佳的集群数量。以下是这些函数的基准测试结果,供任何考虑在他/她的项目中使用这些函数的人使用-

n = 100
g = 6 
set.seed(g)
d <- data.frame(x = unlist(lapply(1:g, function(i) rnorm(n/g, runif(1)*i^2))), 
                y = unlist(lapply(1:g, function(i) rnorm(n/g, runif(1)*i^2))))

mydata <- d
require(cluster)
require(vegan)
require(mclust)
require(apcluster)
require(NbClust)
require(fpc)

microbenchmark::microbenchmark(
  wss = {
    wss <- (nrow(mydata)-1)*sum(apply(mydata,2,var))
    for (i in 2:15) wss[i] <- sum(kmeans(mydata, centers=i)$withinss)
  },
  
  fpc = {
    asw <- numeric(20)
    for (k in 2:20)
      asw[[k]] <- pam(d, k) $ silinfo $ avg.width
    k.best <- which.max(asw)
  },
  fpc_1 = fpc::pamk(d),
  
  vegan = {
    fit <- cascadeKM(scale(d, center = TRUE,  scale = TRUE), 1, 10, iter = 1000)
    plot(fit, sortg = TRUE, grpmts.plot = TRUE)
    calinski.best <- as.numeric(which.max(fit$results[2,]))
  },
  
  mclust = {
    d_clust <- Mclust(as.matrix(d), G=1:20)
    m.best <- dim(d_clust$z)[2]
  },
  d.apclus = apcluster(negDistMat(r=2), d),
  clusGap = clusGap(d, kmeans, 10, B = 100, verbose = interactive()),
  NbClust = NbClust(d, diss=NULL, distance = "euclidean",
                method = "kmeans", min.nc=2, max.nc=15, 
                index = "alllong", alphaBeale = 0.1),
  
  
  times = 1)
Unit: milliseconds
     expr         min          lq        mean      median          uq         max neval
      wss    16.83938    16.83938    16.83938    16.83938    16.83938    16.83938     1
      fpc   221.99490   221.99490   221.99490   221.99490   221.99490   221.99490     1
    fpc_1    43.10493    43.10493    43.10493    43.10493    43.10493    43.10493     1
    vegan  1096.08568  1096.08568  1096.08568  1096.08568  1096.08568  1096.08568     1
   mclust  1531.69475  1531.69475  1531.69475  1531.69475  1531.69475  1531.69475     1
 d.apclus    28.56100    28.56100    28.56100    28.56100    28.56100    28.56100     1
  clusGap  1096.50680  1096.50680  1096.50680  1096.50680  1096.50680  1096.50680     1
  NbClust 10940.98807 10940.98807 10940.98807 10940.98807 10940.98807 10940.98807     1

我发现fpc包中的pamk函数对我的需求最有用。

相关问题