r - 如何从 clusGap 函数中获取最佳簇数作为输出?
问题描述
我有一个包含 2 个变量的数据框,我想使用该clusGap
函数来查找最适合使用的集群数量。这段代码有类似的结果:
library(cluster)
x <- as.vector(runif(100, 0, 1))
y <- as.vector(runif(100, 0, 1))
df <- data.frame(x, y)
gap_stat <- clusGap(df, FUN = kmeans, nstart = n,
K.max = 10, B = 50)
gap_stat
结果:
Clustering Gap statistic ["clusGap"] from call:
clusGap(x = df, FUNcluster = kmeans, K.max = 10, B = 50, nstart = n)
B=50 simulated reference sets, k = 1..10; spaceH0="scaledPCA"
--> Number of clusters (method 'firstSEmax', SE.factor=1): 1
logW E.logW gap SE.sim
[1,] 2.569315 2.584217 0.0149021144 0.03210076
[2,] 2.285049 2.284537 -0.0005116382 0.03231529
[3,] 2.053193 2.033653 -0.0195399122 0.03282376
[4,] 1.839085 1.835590 -0.0034952935 0.03443303
[5,] 1.691219 1.708479 0.0172603348 0.03419994
[6,] 1.585084 1.597277 0.0121935992 0.03440672
[7,] 1.504763 1.496853 -0.0079104306 0.03422321
[8,] 1.416176 1.405903 -0.0102731340 0.03371149
[9,] 1.333721 1.323658 -0.0100626869 0.03245958
[10,] 1.253199 1.250366 -0.0028330498 0.03034140
正如您在第 4 行中看到的,最佳聚类数是 1。我希望函数有 1 作为输出。我需要最佳输出数量才能成为环境中的对象,例如n
1。
解决方案
通常,此类信息直接位于对象内部的某个位置,例如gap_stat$nc
. 寻找它str(gap_stat)
通常就足够了。
然而,在这种情况下,上述策略是不够的。但是您可以在输出中看到您感兴趣的数字这一事实意味着print.clusGap
(因为类gap_stat
是 clusGap)将显示如何获得该数字。因此,检查cluster:::print.clusGap
导致
maxSE(f = gap_stat$Tab[, "gap"], SE.f = gap_stat$Tab[, "SE.sim"])
# [1] 1
推荐阅读
- javascript - ng 模型值没有被清除
- javascript - 如何使用 CSS 创建动态背景?
- haskell - 具有/不具有显示约束的 GHCi 值的不同行为
- c++ - 自定义循环迭代器的 C++ 编译器优化问题
- angular - 使用 Visual Studio for Mac 在解决方案资源管理器中复制客户端文件
- android - 如何使用不同的包名实现 3rdParty 库
- powershell - 这段代码有效吗?
- python - pythonnet dll目录访问被拒绝
- android - Job Scheduler vs Runnable:缺点?
- python - python中的循环,定时器和线程