0

我有一個遺傳算法,目前正在使用輪盤選擇來產生一個新的羣體,我想將其改爲隨機通用採樣。python中的隨機通用採樣GA

我有事情將如何在這裏工作的一個大致的輪廓:

pointerDistance = sumFitness/popSize 
start = rand.uniform(0, pointerDistance) 
for i in xrange(popSize): 
    pointers.append(start + i*pointerDistance) 
cumulativeFit = 0 
newIndiv = 0 
for p in pointers: 
    while cumulativeFit <= p: 
     cumulativeFit += pop[newIndiv].fitness 
     newPop[newIndiv] = copy.deepcopy(pop[newIndiv]) 
     newIndiv += 1 

,但我有究竟如何實現隨機抽樣普遍掙扎。有沒有人知道一些僞代碼的好源,或者一個例子?

的是用一個例子什麼隨機抽樣普遍的簡要說明(但我不知道這是否有意義?):

http://en.wikipedia.org/wiki/Stochastic_universal_sampling

+0

如果添加了它可以幫助鏈接或描述什麼是隨機通用抽樣是 – inspectorG4dget

+0

我已經添加了一個關於它的維基文章的鏈接。它確實有一些示例代碼,但我不確定我是否理解它/我不相信它是正確的。 – user2902575

+0

這是什麼,你不明白:你不確定你的實現是多麼準確,或者該方法本身是有用的? – inspectorG4dget

回答

2
def makeWheel(population): 
    wheel = [] 
    total = sum(fitness(p) for p in population) 
    top = 0 
    for p in population: 
     f = fitness(p)/total 
     wheel.append((top, top+f, p)) 
     top += f 
    return wheel 

def binSearch(wheel, num): 
    mid = len(wheel)//2 
    low, high, answer = wheel[mid] 
    if low<=num<=high: 
     return answer 
    elif low > num: 
     return binSearch(wheel[mid+1:], num) 
    else: 
     return binSearch(wheel[:mid], num) 

def select(wheel, N): 
    stepSize = 1.0/N 
    answer = [] 
    r = random.random() 
    answer.append(binSearch(wheel, r)) 
    while len(answer) < N: 
     r += stepSize 
     if r>1: 
      r %= 1 
     answer.append(binSearch(wheel, r)) 
    return answer 
+0

你能否添加一些評論來解釋你的邏輯? @ inspectorG4dget? – Loligans