【发布时间】:2015-04-11 04:58:33
【问题描述】:
我正在尝试构建一个简单的遗传算法来优化输入字符串,但是在构建 [individual x 基因组] 矩阵时遇到了麻烦(第 n 行是个体 n 的基因组。)我希望能够改变人口大小、突变率和其他参数来研究它如何影响收敛速度和程序效率。
这是我目前所拥有的:
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
感谢您提供的任何帮助。
【问题讨论】:
标签: python python-3.x numpy genetic-algorithm itertools