genetic.py 文件源码

python
阅读 26 收藏 0 点赞 0 评论 0

项目:Isolation-AI 作者: ryanshrott 项目源码 文件源码
def evolve(pop, gamesFactor=2, retain=0.2, random_select=0.05, mutate=0.01):
    # Determine the parents to breed from the population
    agent_score = {}
    numGames = len(pop) * gamesFactor
    bar = progressbar.ProgressBar()

    for game in bar(range(numGames)):
        competitors = random.sample(pop, 2)
        game = Board(competitors[0], competitors[1])
        winner, history, outcome = game.play()
        competitors.remove(winner)
        loser = competitors[0]
        if winner not in agent_score.keys():
            agent_score[winner] = 1
        else:
            agent_score[winner] += 1
        if loser not in agent_score.keys():
            agent_score[winner] = -1
        else:
            agent_score[loser] -= 1        

    top_performers_size = int(retain * len(pop))
    bottom_performers_size = len(pop) - top_performers_size
    rand_select_size = int(len(pop) * random_select)
    top_perfomers = heapq.nlargest(top_performers_size, agent_score, key=agent_score.get)
    bottom_performers = heapq.nsmallest(bottom_performers_size, agent_score, key=agent_score.get)
    parents = top_perfomers + random.sample(bottom_performers, rand_select_size)
    random.shuffle(parents)

    # Create children
    numChildren = len(pop) - len(parents)

    children = []
    for i in range(numChildren):
        par = random.sample(parents, 2)
        father = par[0]
        mother = par[1] 
        child = breed(mother, father)
        children.append(child)

    new_pop = parents + children

    mutated_pop = []
    # Randomly mutate some of the new population
    for agent in new_pop:
        if mutate > random.uniform(0,1):
            print('Mutate')
            mutated_agent = mutate_agent(agent)
            mutated_pop.append(mutated_agent)
        else:
            mutated_pop.append(agent)
    return mutated_pop
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号