繁体   English   中英

遗传算法的位变异

[英]Bit Mutation of Genetic algorithm

我有一个类似的数据,例如b = [['00000001','00000010','00000011'],['00000011','00000100','00000101']]。 我想根据一定的概率来突变或翻转列表中的某些项目。 突变后,说出列表中的第一项,说出b [0] [0]变成'10000001'。 我尝试过这种方式。

    b=[['00000001', '00000010', '00000011'], ['00000011', '00000100', '00000101']]
from random import random, sample, choice
def mutation(x, mutation_rate):    ## Mutation function define
    for i in range(len(x)):
        for j in range(len(x[0])):
            if random() < mutation_rate:           #### Make mutation based on certain probability
                x[i][j] = type(x[i][j])(not x[i][j])  ## This portion flip [0 to 1 or 1 to 0]

    return x

c=mutation(b, .05)

没有错误提示,但是当mutation_rate .05时,变异函数没有任何变化,但是当mutation_rate为.5时,结果是这样的:c = mutation(b,.5)##调用函数[['00000001','False',' False'],['False','False','00000101']]

x是字符串列表的列表。 因此, x[i]是一个字符串列表。 因此, x[i][j]是一个字符串。

然后:

type(x[i][j]) == str
(not x[i][j]) == (not bool(x[i][j])) == (not True) == False
=> type(x[i][j])(not x[i][j]) == str(False) == 'False'

这就是为什么在输出中出现很多'False'的原因。 这些1和0不是位,而是string

换成这个

for i in range(len(x)):
    for j in range(len(x[0])):
        for bit in len(x[i][j])
            if random() < mutation_rate:           #### Make mutation based on certain probability
                x[i][j][bit] = '1' if x[i][j][bit] == '0' else '1'  ## This portion flip [0 to 1 or 1 to 0]

迭代到每一位并在可能的情况下更改

我想我知道了。 我根据您的建议进行了一些修改,并进行了更改。

from random import random, sample, choice
def mutation(x, mutation_rate):
    for i in range(len(x)):
        for j in range(len(x[0])):
            p=[]
            if random() < mutation_rate:  #### Make mutation based on certain probability#
                for bit in range(len(x[i][j])):
                    m=x[i][j][bit]
                    p.append(m)
                p[0] = '1' if p[0] == '0' else '1'
                b=p[0] + p[1] + p[2] + p[3] + p[4] + p[5] + p[6] + p[7]
                x[i][j]=b
    return x

b = [['00000001','00000010','00000011'],['00000011','00000100','00000101']]

c =变异(b,.5)

结果:[['00000001','10000010','10000011'],['00000011','00000100','00000101']]

如此修改。

感谢您的帮助和建议。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM