2015-02-10 92 views
0

我試圖建立一個簡單的遺傳算法,將優化到輸入字符串,但我有麻煩建設[個人x基因組]矩陣(第n行是個人n的基因組)。我希望能夠改變人口規模,變異率和其他參數,以研究如何影響收斂速度和程序效率。矩陣的可變大小[ixj](Python,Numpy)

這是我到目前爲止有:

import random 
import itertools 
import numpy as np 
def evolve(): 


goal    = 'Hello, World!'       #string to optimize towards 
ideal = list(goal) 

#converting the string into a list of integers 
for i in range (0,len(ideal)): 
    ideal [i]  = ord(ideal[i]) 


print(ideal) 
popSize    = 10          #population size 
genome    = len(ideal)        #determineing the length of the genome to be the length of the target string 
mut     = 0.03          #mutation rate 
S     = 4           #tournament size 
best    = float("inf")        #initial best is very large 
maxVal    = max(ideal) 
minVal    = min(ideal) 
print (maxVal) 
i     = 0           #counting variables assigned to solve UnboundLocalError 
j     = 0 

print(maxVal, minVal) 


#constructing initial population array (individual x genome) 
pop = np.empty([popSize, len(ideal)]) 
for i, j in itertools.product(range(i), range(j)): 
    pop[i, j] = [i, random.randint(minVal,maxVal)] 
print(pop) 

這產生了人口規模與正確的基因組長度的矩陣,但基因組是這樣的:

[ 6.91364167e-310 6.91364167e-310 1.80613009e-316 1.80613009e-316 
5.07224590e-317 0.00000000e+000 6.04100487e+151 3.13149876e-120 
1.11787892e+253 1.47872844e-028 7.34486815e+223 1.26594941e-118 
7.63858409e+228] 

我需要他們爲與隨機ASCII字符對應的隨機整數。

我在做什麼錯誤的這種方法? 有沒有辦法讓這個更快?

我發現我在這裏電流法: building an nxn matrix in python numpy, for any n

我發現,我不明白的另一種方法,但似乎更快,和假笑,如果我能在這裏使用它,我想。 Initialise numpy array of unknown length

感謝您提供任何幫助。

回答

1

您的循環未執行,因爲i和j均爲0,所以範圍(i)和範圍(j)爲空。你也不能將一個列表[i,random]分配給一個數組值(np.empty默認爲np.float64)。我只是把它改爲只存儲隨機數,但如果你真的想存儲的列表,你可以改變流行音樂的創作是pop = np.empty([popSize, len(ideal)],dtype=list)

否則用這個的最後幾行:

for i, j in itertools.product(range(popSize), range(len(ideal))): 
    pop[i, j] = random.randint(minVal,maxVal) 
+0

或使用np.random.randint – tillsten 2015-02-10 23:54:04

+0

謝謝Ethan。這是問題所在。如果我有足夠的代表,我會贊成。我想我應該注意到一個問題,當它給了我UnboundLocalError。 我決定讓它存儲一個列表,因爲我更熟悉它們,並且認爲當我進入基因交叉階段時它會更容易。 – MatthewC 2015-02-11 00:29:56

+0

'np.random.randint(0,10,(10,10))'生成一個10x10的隨機整數數組 – hpaulj 2015-02-11 01:30:08