使用 Elbow 方法查找簇数时返回多个值

Multiple values returned when using Elbow method to find the number of clusters

我正在尝试使用 Elbow 方法来查找数据中名为 "data.clustering" 的簇数。它必须具有以下特征:年龄和性别。它的头部如下: 头(data.clustering);

> head(data.clustering)
age gender
2 2 1
3 6 2
4 2 1
5 2 1
6 6 2
7 6 1

我在 "data.clustering" 数据框上查找 k-clusters 值的代码:

# include library
require(stats)
library(GMD)
library(ggplot2)
library(parallel)
# include function
source('~/Workspaces/Projects/RProject/MovielensCluster/readData.R');
###
elbow.k <- function(mydata){
## determine a "good" k using elbow
dist.obj <- dist(mydata);
hclust.obj <- hclust(dist.obj);
css.obj <- css.hclust(dist.obj,hclust.obj);
elbow.obj <- elbow.batch(css.obj);
# print(elbow.obj)
k <- elbow.obj$k
return(k)
}
# include file
filePath <- "dataset/u.user";
data.original <- readtext.tocsv(filePath);
data.convert <- readtext.convert(filePath);
data.clustering <- data.convert[,c(-1,-4)];
# find k value
no_cores <- detectCores();
cl<-makeCluster(no_cores);
clusterEvalQ(cl, library(GMD));
clusterExport(cl, list("data.clustering", "data.original", "elbow.k", "clustering.kmeans"));
start.time <- Sys.time();
k.clusters <- parSapply(cl, c(1:3), 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);

如您在 elbow.k 函数中所见。我只是 return k 值,但是在我 运行 上面的代码片段之后,结果有三个 k return 因为相同的值是:

Time to find k using Elbow method is 38.39039 seconds with k value: 10 10 10

我对结果的期望是:

Time to find k using Elbow method is 38.39039 seconds with k value: 10

谁能帮我解决这个问题?

我认为您的代码运行良好。但是你必须编辑行代码

k.clusters <- parSapply(cl, c(1:3), function(x) elbow.k(data.clustering)); 

k.clusters <- parSapply(cl, 1, function(x) elbow.k(data.clustering));

第二个值将使 k return 的数量符合您的预期。这只是你函数中的一个简单错误。