以下代码有助于了解最佳簇数。
set.seed(123)
# function to compute total within-cluster sum of square
wss <- function(k) {
kmeans(df, k, nstart = 10 )$tot.withinss
}
# Compute and plot wss for k = 1 to k = 15
k.values <- 1:15
# extract wss for 2-15 clusters
wss_values <- map_dbl(k.values, wss)
plot(k.values, wss_values,
type="b", pch = 19, frame = FALSE,
xlab="Number of clusters K",
ylab="Total within-clusters sum of squares")
参考:https://uc-r.github.io/
目标是将其转换为具有多个内核的共享内存,以便快速完成。fviz_nbclust
尝试使用此方法,并且非常慢。
方法/尝试:
首先,创建wss
方法在mclapply
parallel.wss <- function(i, k) {
set.seed(101)
kmeans(df, k, nstart=i)$tot.withinss
}
这里i
是并行启动的数量,k
实际上是k.values
,我们需要尝试找到最佳的群集数。
k.values <- 1:15
kmean_results <- mclapply(c(25,25,25,25), k.values, FUN=parallel.wss)
但遵循警告:
Warning message:
In mclapply(c(25, 25, 25, 25), k.values, FUN = parallel.wss) :
all scheduled cores encountered errors in user code
查看kmean_results
对象:
头(kmean_results( [[1] [1]" kmeans中的错误(df,k,nstart = i(: n必须在'x'和'x'和'Centers' n" n"中具有相同数量的列 attr(," class"( [1]" try-error" attr(,"条件"(
使用foreach
,您可以做
ncores <- parallel::detectCores(logical = FALSE)
cl <- parallel::makeCluster(ncores)
doParallel::registerDoParallel(cl)
library(foreach)
wss_values2 <- foreach(k = k.values, .combine = 'c') %dopar% {
kmeans(df, k, nstart = 10)$tot.withinss
}
parallel::stopCluster(cl)
如果将kmeans
调用包含在函数中,则需要将所有变量作为参数传递(df
和k
(。