我正在使用通航套餐 https://cran.r-project.org/web/packages/GA/GA.pdf我的目标是找到 k 均值聚类算法的最佳初始质心位置。我的数据是 TF-IDF 分数中单词的稀疏矩阵,可下载here. https://drive.google.com/open?id=0B0heEjN4tZlWNGE4OTgzUjkxN28以下是我实施的一些阶段:
0. 库和数据集
library(clusterSim) ## for index.DB()
library(GA) ## for ga()
corpus <- read.csv("Corpus_EnglishMalay_tfidf.csv") ## a dataset of 5000 x 1168
1. 二进制编码并生成初始种群。
k_min <- 15
initial_population <- function(object) {
## generate a population to turn-on 15 cluster bits
init <- t(replicate(object@popSize, sample(rep(c(1, 0), c(k_min, object@nBits - k_min))), TRUE))
return(init)
}
2. 健身功能最小化 Davies-Bouldin (DB) 指数。我在其中评估生成的每个解决方案的 DBIinitial_population
.
DBI2 <- function(x) {
## x is a vector of solution of nBits
## exclude first column of corpus
initial_centroid <- corpus[x==1, -1]
cl <- kmeans(corpus[-1], initial_centroid)
dbi <- index.DB(corpus[-1], cl=cl$cluster, centrotypes = "centroids")
score <- -dbi$DB
return(score)
}
3. 运行遗传算法。有了这些设置。
g2<- ga(type = "binary",
fitness = DBI2,
population = initial_population,
selection = ga_rwSelection,
crossover = gabin_spCrossover,
pcrossover = 0.8,
pmutation = 0.1,
popSize = 100,
nBits = nrow(corpus),
seed = 123)
4.问题。kmeans(corpus[-1],initial_centroid) 中的错误:初始中心不明显`。
我发现了类似的问题here https://community.tableau.com/thread/193251,其中用户还必须使用参数来动态传入要使用的集群数量。它是通过硬编码簇的数量来解决的。然而对于我的情况,我确实需要动态地传递簇的数量,因为它来自随机生成的二进制向量,其中那些1's
将代表初始质心。
检查与kmeans()
code https://svn.r-project.org/R/trunk/src/library/stats/R/kmeans.R,我注意到错误是由重复的中心引起的:
if(any(duplicated(centers)))
stop("initial centers are not distinct")
我编辑了kmeans
功能与trace
打印出重复的中心。输出:
[1] "206" "520" "564" "1803" "2059" "2163" "2652" "2702" "3195" "3206" "3254" "3362" "3375"
[14] "4063" "4186"
这表明随机选择的内容没有重复initial_centroids
我不知道为什么这个错误不断发生。还有其他什么会导致此错误吗?
P/S:我确实理解有些人可能认为 GA + K-means 不是一个好主意。但我确实希望完成我已经开始的事情。最好将此问题视为 K 均值问题(至少在解决initial centers are not distinct
error).