二进制数的Python遗传算法

时间:2013-04-13 19:00:48

标签: python genetic-algorithm

我被要求制作一个遗传算法,其目标是确定最多1和0的8位字符串。 eval函数应返回更改的数量加1.例如,00000000返回1,00011100返回3,01100101返回6.这就是我所拥有的:

def random_population():
    from random import choice

    pop = ''.join(choice(('0','1')) for _ in range(8))
    return pop   

def mutate(dna):   
    """   For each gene in the DNA, there is a 1/mutation_chance chance 
    that it will be   switched out with a random character. This ensures 
    diversity in the   population, and ensures that is difficult to get stuck in 
    local minima.   """   
    dna_out = ""   
    mutation_chance = 100   
    for c in xrange(DNA_SIZE):
        if int(random.random()*mutation_chance) == 1:
            dna_out += random_char()
        else:
            dna_out += dna[c]   return dna_out

def crossover(dna1, dna2):   
    """   Slices both dna1 and dna2 into two parts at a random index within their   
    length and merges them. Both keep their initial sublist up to the crossover   
    index, but their ends are swapped.   """   
    pos = int(random.random()*DNA_SIZE)
    return (dna1[:pos]+dna2[pos:], dna2[:pos]+dna1[pos:])

def eval(dna):
    changes = 0
    for index, bit in enumerate(dna):
        if(index == 0):
            prev = bit
        else:
            if(bit != prev):
                changes += 1
        prev = bit
    return changes+1


#============== End Functions =======================#


#============== Main ================# changes = 0

prev = 0
dna = random_population()
print "dna: "
print dna
print eval(dna)

我在实际找出遗传算法部分(交叉/突变)时遇到了麻烦。我应该随机配对数字,然后随机选择一对,留下一对未接触,然后在随机点交叉。然后它将通过随机改变整个群体中的一位来结束。交叉和变异的当前代码仅来自我发现并试图理解的遗传算法示例。欢迎任何帮助。

2 个答案:

答案 0 :(得分:1)

我建议的部分内容:

代码无效但可能会传输信息。

# a population consists of many individuals
def random_population(population_size = 10):
    from random import choice

    pop = [''.join(choice(('0','1')) for _ in range(8)) for i in range(population_size)]
    return pop   

# you need a fitness function
def fitness(individual):
    return # a value from 0 up

def algorithm():
    # a simple algorithm somehow alike
    # create population
    population = random_population()
    # this loop must stop after some rounds because the best result may never be reached
    while goal_not_reached(population) and not time_is_up():
        # create the roulette wheel
        roulette_wheel = map(fitness, population)
        # highest value of roulette wheel
        max_value = sum(roulette_wheel)
        # the new generation
        new_population = []
        for i in range(len(population) - len(new_population)):
             # create children from the population
                 # choose 2 random values from 0 to max_value and find the individuals
                 # for it in the roulette wheel, combine them to new individuals 
             new_population.append(new_individual)
        # mutate the population
        population = map(mutate, new_population)             # a new generation is created

答案 1 :(得分:0)

我发现我喜欢做的一件事是:

  1. 选择最后一批的最佳候选人,比如说5.
  2. 与2,3,4,5交配1次。
  3. 有3个,4个,5个
  4. 的2个伴侣
  5. 有4个伴侣,4个和5个
  6. 与5配对。一般来说,如果你让原来的5进入下一代并且每次交配产生2个后代,你的人口已经满了你到达这一点。一个交配和对面的双胞胎。
  7. 就实际穿越而言,我喜欢在长度的40%到60%之间的点处随机切割染色体,然后在下次交配时,我会选择该范围内的另一个随机点。
  8. 在我交配完毕后,我会在染色体上检查每一点并给它大约0.5%的翻转或变异几率
  9. 有时候我也会让一些最糟糕的两个伙伴降低我的局部最大值或最小值的机会
  10. 我希望这对你有所帮助。

    -Jeff

    编辑:哦,我4月份被问过这个问题。抱歉严重挖掘。