我是pyevolve和Python中的GA新手。
我试图制作一个表示匹配的二维二进制数组。像这样:
A B C
1 1 0 0
2 0 1 0
3 1 0 0
4 0 0 1
我的目标是每行只有一个“1”,数组中的“1”应该等于行数。一个数字只能与一个字母匹配,但一个字母可以与多个数字匹配。 我在求值函数中编写了这个代码
def eval_func(chromosome):
score = 0.0
num_of_rows = chromosome.getHeight()
num_of_cols = chromosome.getWidth()
# create 2 lists. One with the sums of each row and one
# with the sums of each column
row_sums = [sum(chromosome[i]) for i in xrange(num_of_rows)]
col_sums = [sum(x) for x in zip(*chromosome)]
# if the sum of "1"s in a row is > 1 then a number (1,2,3,4) is matched with
# more than one letter. We want to avoid that.
for row_sum in row_sums:
if row_sum <= 1:
score += 0.5
else:
score -= 1.0
# col_sum is actually the number of "1"s in the array
col_sum = sum(col_sums)
# if all the numbers are matched we increase the score
if col_sum == num_of_rows:
score += 0.5
if score < 0:
score = 0.0
return score
似乎可以工作,但当我添加一些其他检查时,例如如果1
在A
,2
不能在C
,它就会失败。
这怎么可能呢?(许多支票)
提前谢谢。你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐