2017-01-24 64 views
0

聚类我有以下dataset(获得here):优化K均值使用遗传算法

----------item survivalpoints weight 
1 pocketknife    10  1 
2  beans    20  5 
3  potatoes    15  10 
4  unions    2  1 
5 sleeping bag    30  7 
6   rope    10  5 
7  compass    30  1 

我可以使用一个二进制字符串作为我的中心的初始选择群集此数据集成三个簇与kmeans()。对于如:

## 1 represents the initial centers 
chromosome = c(1,1,1,0,0,0,0) 
## exclude first column (kmeans only support continous data) 
cl <- kmeans(dataset[, -1], dataset[chromosome == 1, -1]) 
## check the memberships 
cl$clusters 
# [1] 1 3 3 1 2 1 2 

使用这个基本概念,我尝试过了与GA包进行那里我想优化(最小化),戴维斯 - 尔丁(DB)索引搜索。

library(GA)   ## for ga() function 
library(clusterSim) ## for index.DB() function 

## defining my fitness function (Davies-Bouldin) 
DBI <- function(x) { 
     ## converting matrix to vector to access each row 
     binary_rep <- split(x, row(x)) 
     ## evaluate the fitness of each chromsome 
     for(each in 1:nrow(x){ 
      cl <- kmeans(dataset, dataset[binary_rep[[each]] == 1, -1]) 
      dbi <- index.DB(dataset, cl$cluster, centrotypes = "centroids") 
      ## minimizing db 
      return(-dbi) 
    } 
} 

g<- ga(type = "binary", fitness = DBI, popSize = 100, nBits = nrow(dataset)) 

当然(我不知道发生了什么),我收到的 Warning messages: Error in row(x) : a matrix-like object is required as argument to 'row'

以下错误消息是我的问题:

  1. 如何正确使用GA包来解决我的问题?
  2. 我怎样才能确保随机产生的染色体包含相同数量的1 S的对应k号群(例如,如果k=3那么染色体必须包含正好是三个1 S)的?
+0

我不认为这种方法有任何意义。它可能不会工作,因为k-means常常收敛到完全相同的解决方案。 –

+0

有没有什么建议可以提供这样的问题?我的数据集是否太小? –

+0

我不认为GA + k-means *永远*是有意义的。 –

回答

2

我不能评论k-means与ga结合的感觉,但我可以指出你的健身功能有问题。此外,当所有的基因开启或关闭产生错误,所以健身的计算只当是情况并非如此:

DBI <- function(x) { 
    if(sum(x)==nrow(dataset) | sum(x)==0){ 
    score <- 0 
    } else { 
    cl <- kmeans(dataset[, -1], dataset[x==1, -1]) 
    dbi <- index.DB(dataset[,-1], cl=cl$cluster, centrotypes = "centroids") 
    score <- dbi$DB 
    } 

    return(score) 
} 

g <- ga(type = "binary", fitness = DBI, popSize = 100, nBits = nrow(dataset)) 
plot(g) 

enter image description here

[email protected] 
[email protected] 

貌似几个基因组合产生相同的“最佳“健身价值

+1

我无法告诉你我对这个答案有多感激。是的,我同意这些基因倾向于融合到相同的解决方案中,但了解如何应用用户定义的健身对我来说是一个很好的开始。非常感谢! –

+0

欢呼声 - 如果不清楚,请确保您了解ga将尝试_maximize_适应性函数,而不是最小化 - 就像在基于成本函数的其他优化算法中所做的那样。 –

+0

这给我带来了另一个问题,因为'ga'使适应度函数最大化,为什么不必为了最小化它而将-1与-1相乘?我在其他例子中看到过,特别是使用'genalg'软件包来最小化适应函数,因此,为了最大化它,它们只会返回乘以-1的值。 –