2017-01-24 66 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的值。 –