我一直在尝试用NEAT-python库编写一个遗传算法来玩FlappyBird。我遇到了for循环覆盖基因组的问题。在基因组迭代开始后,for loop只完成一只鸟的动作,而不是继续并重新开始新基因组的游戏。下面是我处理这个问题的函数,以及我如何初始化游戏环境。
game = FlappyBird()
p = PLE(game, fps=30, display_screen=True, force_fps=False)
p.init()
def eval_genomes(genomes, config):
for genome_id, genome in genomes:
p.reset_game()
net = FeedForwardNetwork.create(genome, config)
genome.set_actions(p.getActionSet())
genome.fitness = 0
while not p.game_over():
game_state = game.getGameState()
decision = genome.play(net, game_state)
if decision == 1:
p.act(0)
else:
genome.fitness = p.score()
genome.is_dead = True发布于 2018-12-29 21:46:36
就在今天我也这么做了!:D
不同的是它对我很有效……
您可能需要在github上查看以下存储库。https://github.com/rsk2327/NEAT_FlappyBird
我不认为它已经更新了。但是没有必要这么做。在他的代码中,我唯一需要修改的就是删除所有代码:"/home/roshan/Documents/FlappyBird/“。你可以把它们放在一边,把所有的资源放在同一个文件夹里。
此外,我将获胜者的酸菜转储更改为:
#outputDir = 'bestGenomes/'
#os.chdir(outputDir)
#serialNo = len(os.listdir(outputDir))+1
#outputFile = open(str(serialNo)+'_'+str(int(MAX_FITNESS))+'.p','wb' )
outputFile = 'bestGenome/winner.p'
pickle.dump(winner, outputFile)这是因为在最初的几次运行中,我保存了每个基因组,而更改目录会使一切变得混乱。
除此之外,它工作得很好。一旦它工作了,你就可以替换游戏,或者整个评估。
否则,请看一下整洁python的示例。在进化最小的例子中,他们所需要的就是遵循代码,它对每个基因组都运行。
def eval_genomes(genomes, config):
for genome_id, genome in genomes:
genome.fitness = 4.0
net = neat.nn.FeedForwardNetwork.create(genome, config)
for xi, xo in zip(xor_inputs, xor_outputs):
output = net.activate(xi)
genome.fitness -= (output[0] - xo[0]) ** 2尽管我不得不说,对我来说,它在功能上看起来是一样的。因此,while循环中可能有什么问题,不是吗?
发布于 2022-02-19 17:17:59
示例:
在适应度函数方法中
世代开始
environment.init()
for genome_id, genome in genomes:
net = neat.nn.FeedForwardNetwork.create(genome, configuration)
pipe_count = 0 # this is the score
# Game loop for a single genome
while True:
last_score = environment.game.getScore() # score before action
output = networkOutput(net, environment) # Get output from network
if output[0] > 0.5:
environment.act(environment.getActionSet()[0]) # Jump
else:
environment.act(environment.getActionSet()[1]) # Don't jump (NOOP)
# keep track of score
score = environment.game.getScore() - last_score
if(score >= 1):
# print("and anotha one: " + str(score))
pipe_count += 1
# when genome dies
if(environment.lives() <= 0):
genome.fitness = environment.game.score
environment.init() # Take note (init(), not reset_game)
print("Dead: " + str(genome_id) + " score: " + str(pipe_count))
breakhttps://stackoverflow.com/questions/52837084
复制相似问题