在每次预测后实现NEAT python重新训练

2024-04-29 02:18:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想了解如何实现整洁的python,以便它在每次预测后重新训练,因此每次预测后训练集的大小都会增加。在

我试图通过配置文件设置整洁的python,以便在每次预测测试/未查看集之后重新进行训练。例如,如果XOR“进化极小”的例子,根据我的理解,它可以被调整,这样它就可以对部分数据进行训练(达到特定的适应度水平,获得最佳的基因组),然后它就可以对作为测试集的其他数据进行预测。我看下面的代码是什么意思:

from __future__ import print_function
import neat
import visualize

# 2-input XOR inputs and expected outputs. Training set
xor_inputs = [(0.0, 0.0, 0.0), (0.0, 1.0, 0.0), (1.0, 1.0, 1.0), (0.0, 0.0, 1.0), (1.0, 1.0, 0.0)]
xor_outputs = [(1.0,), (1.0,), (1.0,), (0.0,), (0.0,)]

# Test set
xor_inputs2 = [(1.0, 0.0, 1.0), (1.0, 1.0, 0.0), (1.0, 0.0, 0.0)]
xor_outputs2 = [(1.0,), (0.0,), (0.0,)]


def eval_genomes(genomes, config):
 for genome_id, genome in genomes:
    genome.fitness = 5
    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


# Load configuration.
config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                 neat.DefaultSpeciesSet, neat.DefaultStagnation,
                 'config-feedforward')

# Create the population, which is the top-level object for a NEAT run.
p = neat.Population(config)

# Add a stdout reporter to show progress in the terminal.
p.add_reporter(neat.StdOutReporter(True))
stats = neat.StatisticsReporter()
p.add_reporter(stats)

# Run until a solution is found.
winner = p.run(eval_genomes) 

# Display the winning genome.
 print('\nBest genome:\n{!s}'.format(winner))

# Show output of the most fit genome against training data.
print('\nOutput:')
winner_net = neat.nn.FeedForwardNetwork.create(winner, config)
count = 0

#To make predictions using the best genome
for xi, xo in zip(xor_inputs2, xor_outputs2):
  prediction = winner_net.activate(xi)
  print("  input {!r}, expected output {!r}, got {!r}".format(
  xi, xo[0], round(prediction[0])))
  #to get prediction accuracy
  if int(xo[0]) == int(round(prediction[0])):
    count = count + 1
accuracy = count / len(xor_outputs2)
print('\nAccuracy: ', accuracy)

node_names = {-1: 'A', -2: 'B', 0: 'A XOR B'}
visualize.draw_net(config, winner, True, node_names=node_names)
visualize.plot_stats(stats, ylog=False, view=True)
visualize.plot_species(stats, view=True)

配置文件为:

^{pr2}$

然而,这里的问题是,在测试集中的每个预测被做出之后,不会发生再训练。我相信配置文件中的参数是静态的,在训练过程开始后不能改变,所以如果你的健康水平是基于训练集的正确分类的数量(这是我试图实现的,这将是一个问题,因此我想了解是否可以通过调整配置文件中的设置来实现重新训练的模型。或者还有比这更多的吗?在


Tags: theconfigfornetgenomestats配置文件neat
1条回答
网友
1楼 · 发布于 2024-04-29 02:18:42

如果我正确地理解了您的要求,这不能简单地在config文件中完成。在

config_文件中定义的参数只是改变模型直接运行数据时发生的情况,无需任何重新训练就可以做出预测。在

如果您希望模型在每次预测之后重新训练,那么您必须在eval_genomes和/或run函数中实现此功能。你可以在遍历每个基因组的循环中添加另一个for循环,以获取每个输出并重新训练模型。然而,这可能会显著增加计算时间,因为您不只是简单地获取输出,而是为每个输出运行另一组训练生成。在

相关问题 更多 >