我是 Python 中 pyevolve 和 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
似乎可以工作,但是当我添加一些其他检查时,例如 if 1
is in A
,2
can not be in C
,它会失败。这怎么可能?(许多检查)
提前致谢。