Cluster analysis in R: determine the optimal number of clusters
作为R的新手,我不太确定如何选择最佳数目的聚类来进行k均值分析。 在绘制了以下数据的子集之后,多少个簇才合适? 如何执行聚类dendro分析?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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 ) |
如果您的问题是
首先,一些可重现的数据(Q中的数据对我来说尚不清楚):
1 2 3 4 5 6 | 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) |
一。在平方误差总和(SSE)碎石图上查找弯曲或弯头。有关更多信息,请参见http://www.statmethods.net/advstats/cluster.html和http://www.mattpeeples.net/kmeans.html。弯头在结果图中的位置表明适合kmeans的簇数:
1 2 3 4 5 6 | 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软件包中的
1 2 3 4 5 | library(fpc) pamk.best <- pamk(d) cat("number of clusters estimated by optimum average silhouette width:", pamk.best$nc," ") plot(pam(d, pamk.best$nc)) |
1 2 3 4 5 6 7 8 9 | # 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," ") # still 4 |
三。 Calinsky准则:诊断有多少簇适合数据的另一种方法。在这种情况下,我们尝试1至10组。
1 2 3 4 5 6 7 | 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," ") # 5 clusters! |
四。根据贝叶斯信息准则确定最佳模型和聚类数,以实现期望最大化,并通过分层聚类对参数化的高斯混合模型进行初始化
1 2 3 4 5 6 7 8 9 10 11 12 13 | # 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," ") # 4 clusters plot(d_clust) |
五。相似性传播(AP)群集,请参见http://dx.doi.org/10.1126/science.11??36800
1 2 3 4 5 6 7 | library(apcluster) d.apclus <- apcluster(negDistMat(r=2), d) cat("affinity propogation optimal number of clusters:", length(d.apclus@clusters)," ") # 4 heatmap(d.apclus) plot(d.apclus, d) |
六。估计簇数的差距统计。另请参见一些代码以获取良好的图形输出。在这里尝试2-10个集群:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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实施差值统计的结果:
七。您可能还会发现使用聚类图浏览数据以可视化聚类分配很有用,请参阅http://www.r-statistics.com/2010/06/clustergram-visualization-and-diagnostics-for-cluster-analysis-r-代码/了解更多详情。
八。 NbClust软件包提供30个索引来确定数据集中的簇数。
1 2 3 4 5 6 7 | 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
这里有一些例子:
1 2 | d_dist <- dist(as.matrix(d)) # find distance matrix plot(hclust(d_dist)) # apply hirarchical clustering and plot |
1 2 3 4 5 6 7 8 9 | # 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 |
对于高维数据,还有
1 2 3 4 5 | library(pvclust) library(MASS) data(Boston) boston.pv <- pvclust(Boston) plot(boston.pv) |
有什么帮助吗?
很难添加过于详尽的答案。尽管我觉得我们应该在这里提到
1 2 3 | d_dist <- dist(as.matrix(d)) # find distance matrix plot(hclust(d_dist)) clusters <- identify(hclust(d_dist)) |
为了确定最佳的k聚类方法。我通常在并行处理中使用
肘法
1 2 3 4 5 6 7 8 | 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) } |
平行运行弯头
1 2 3 4 5 6 7 8 9 | 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) |
它运作良好。
这些方法很棒,但是当试图为更大的数据集找到k时,这些方法在R中可能会很慢。
我发现一个很好的解决方案是" RWeka"程序包,该程序包有效地实现了X-Means算法-K-Means的扩展版本,可更好地扩展并为您确定最佳的群集数量。
首先,您需要确保系统上已安装Weka并通过Weka的软件包管理器工具安装了XMeans。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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 |
Ben的精彩回答。但是,令我惊讶的是,这里建议使用"亲和传播(AP)"方法只是为了找到k均值方法的聚类数,通常在此方法中AP可以更好地对数据进行聚类。请在此处查看支持此方法的科学论文:
Frey,Brendan J.和Delbert Dueck。"通过在数据点之间传递消息进行集群。"科学315.5814(2007):972-976。
因此,如果您不偏向于k均值,我建议直接使用AP,它将在不需要知道簇数的情况下对数据进行聚类:
1 2 3 | library(apcluster) apclus = apcluster(negDistMat(r=2), data) show(apclus) |
如果负欧氏距离不合适,则可以使用同一软件包中提供的另一种相似性度量。例如,对于基于Spearman相关性的相似性,这是您需要的:
1 2 | sim = corSimMat(data, method="spearman") apclus = apcluster(s=sim) |
请注意,为简化起见,仅提供了AP软件包中用于相似性的那些功能。实际上,R中的apcluster()函数将接受任何相关矩阵。使用corSimMat()之前可以通过以下操作完成:
1 | sim = cor(data, method="spearman") |
要么
1 | sim = cor(t(data), method="spearman") |
取决于要在矩阵(行或列)上进行聚类的对象。
一个简单的解决方案是库
数据:mtcars
1 2 3 4 | library(factoextra) fviz_nbclust(mtcars, kmeans, method ="wss") + geom_vline(xintercept = 3, linetype = 2)+ labs(subtitle ="Elbow method") |
最后,我们得到如下图:
答案很好。如果您想给其他聚类方法一个机会,可以使用分层聚类并查看数据如何拆分。
1 2 3 4 | > set.seed(2) > x=matrix(rnorm(50*2), ncol=2) > hc.complete = hclust(dist(x), method="complete") > plot(hc.complete) |
根据需要的类数,可以将树状图剪切为:
1 2 3 | > 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 |
如果键入