Пример #1
0
def run(config_file):
    # Load configuration.
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_file)

    # 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 for up to 300 generations.
    winner = p.run(eval_genomes, num_generations)

    visualize.visualize_stats(stats,
                              fitness_out_file='avg_fitness_static.svg',
                              species_out_file='species_static.svg')
    output_winner(winner,
                  config,
                  net_filename='nn_winner_static',
                  genome_filename='winner_static')
Пример #2
0
def run(config_file):
    """
    запускает алгоритм NEAT, чтобы обучить нейронную сеть играть в беспечную fluppi bird.
    : param config_file: расположение файла конфигурации
    :return: None
    """
    config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction,
                                neat.DefaultSpeciesSet, neat.DefaultStagnation,
                                config_file)

    # Создайте совокупность, которая является объектом верхнего уровня для запуска NEAT.
    p = neat.Population(config)

    # Добавьте репортер stdout, чтобы показать прогресс в терминале.
    p.add_reporter(neat.StdOutReporter(True))
    stats = neat.StatisticsReporter()
    p.add_reporter(stats)
    #p.add_reporter(neat.Checkpointer(5))

    # Lj 50 генов
    winner = p.run(eval_genomes, 50)

    # показать окончательную статистику
    print('\nBest genome:\n{!s}'.format(winner))
def run(config_file):
    """
    runs the NEAT algorithm to train a neural network to play flappy bird.
    :param config_file: location of config file
    :return: None
    """
    config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction,
                                neat.DefaultSpeciesSet, neat.DefaultStagnation,
                                config_file)

    # 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)
    #p.add_reporter(neat.Checkpointer(5))

    # Run for up to 50 generations.
    winner = p.run(eval_genomes, 50)

    # show final stats
    print('\nBest genome:\n{!s}'.format(winner))
Пример #4
0
def run(config_file):
    # Load configuration.
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_file)

    # 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)
    p.add_reporter(neat.Checkpointer(50))

    winner = p.run(eval_genomes, 1000)

    with open("population.data","wb") as f:
        pickle.dump(p,f)

    # Show output of the most fit genome against training data.
    winner_net = neat.nn.FeedForwardNetwork.create(winner, config)
    with open("winner.genome","wb") as f:
        pickle.dump((winner,config), f)
Пример #5
0
def run(config_path):
    train, save = option()

    config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction,
                                neat.DefaultSpeciesSet, neat.DefaultStagnation,
                                config_path)

    p = neat.Population(config)

    p.add_reporter(neat.StdOutReporter(True))
    stats = neat.StatisticsReporter()
    p.add_reporter(stats)

    if train:
        winner = p.run(main, 50)
        print('Model Trained Successfully!')

    else:

        if os.path.exists('winner.pkl'):  # check if file exist

            with open('winner.pkl', 'rb') as f:
                genome = pickle.load(f)  # load the trained neural network

            genomes = [(1, genome)]
            main(genomes, config)  # run the game with the best genome
            pygame.quit()

        else:
            print('Trained Neural Network File Doesn\'t Exist!')
            quit()

    if save:
        with open('winner.pkl', 'wb') as f:
            pickle.dump(winner, f)
            print('Model Saved on: "winner.pkl"')
Пример #6
0
def test_run_iznn():
    """
    Basic test of spiking neural network (iznn).
    [TODO: Takes the longest of any of the tests in this file, by far. Why?]
    Was because had population of 290 thanks to too much speciation -
    too-high compatibility_weight_coefficient relative to range for weights.
    """
    # Load configuration.
    local_dir = os.path.dirname(__file__)
    config_path = os.path.join(local_dir, 'test_configuration_iznn')
    config = neat.Config(neat.iznn.IZGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_path)

    # 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)
    p.add_reporter(neat.Checkpointer(2, 10))

    # Run for up to 20 generations.
    p.run(eval_dummy_genomes_iznn, 20)

    stats.save()

    unique_genomes = stats.best_unique_genomes(5)
    assert 1 <= len(unique_genomes) <= 5, "Unique genomes: {!r}".format(
        unique_genomes)
    genomes = stats.best_genomes(5)
    assert len(genomes) == 5, "Genomes: {!r}".format(genomes)
    stats.best_genome()

    p.remove_reporter(stats)
Пример #7
0
def run(config_file):
    # Load config file
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_file)
    # Creates population
    pop = neat.Population(config)
    # Adds reporter
    pop.add_reporter(neat.StdOutReporter(True))
    stats = neat.StatisticsReporter()
    pop.add_reporter(stats)
    # // Uncomment below to add checkpoints
    # pop.add_reporter(neat.Checkpointer(5))
    # Run for 50 generations
    winner = pop.run(eval_genomes, 50)
    # Display winner
    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)
    accuracy = 0
    total = 0
    for train in training_images:
        temp_input = train.image_array.flatten()
        output = winner_net.activate(temp_input)
        print("input {!r}, expected output {!r}, got {!r}".format(
            train.image_name, train.answer,
            pa.answers.__getitem__(output.index(max(output)))))
        total += 1
        if train.answer == pa.answers.__getitem__(output.index(max(output))):
            accuracy += 1
    print("Best accuracy percentage: ", (accuracy / total * 100))
    # visualize things
    visualize.plot_accuracy(average_accuracy, view=True)
    visualize.draw_net(config, winner, True)
    visualize.plot_stats(stats, ylog=False, view=True)
Пример #8
0
def main():
    # setup our main classes
    agent = agents.NeatAgent()
    task = marioai.NeatTask(name="NeatAgent", visualization=True)
    exp = marioai.NeatExperiment(task, agent)

    # set some environment vars
    exp.max_fps = 24
    task.env.level_type = 0

    # load from checkpoint, uncomment if running from scratch
    exp.p = neat.Checkpointer.restore_checkpoint('neat-checkpoint-14')

    # get the statistics of NEAT during training
    stats = neat.StatisticsReporter()
    exp.p.add_reporter(stats)
    exp.p.add_reporter(neat.Checkpointer(5))

    # print some statistics at the end
    winner = exp.p.run(exp.doEpisodes, 300)
    print('\nBest genome:\n{!s}'.format(winner))

    visualize.plot_stats(stats, ylog=False, view=True)
    visualize.plot_species(stats, view=True)
Пример #9
0
def run():
    # get config
    local_dir = os.path.dirname(__file__)
    config_path = os.path.join(local_dir, 'config-recurrent-small')
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_path)
    
    # set population and set reporting options
    pop = neat.Population(config)
    stats = neat.StatisticsReporter()
    pop.add_reporter(stats)
    pop.add_reporter(neat.StdOutReporter(True))
    # Checkpoint every x generations or 15 minutes
    pop.add_reporter(neat.Checkpointer(250, 900, "checkpoints/"+fn_results+"-checkpoint"))
    
    #winner = pop.run(eval_genomes) # non-parallel
    pe = neat.ParallelEvaluator(NUM_WORKERS, eval_genome)
    winner = pop.run(pe.evaluate, NUM_GEN)
    
    # save network
    with open("results/winner-pickle-"+fn_results, 'wb') as f:
        pickle.dump(winner, f)
        
    #print(winner)
    
    visualize.plot_stats(stats, ylog=True, view=True, filename="results/"+fn_results+"-fitness.svg")
    visualize.plot_species(stats, view=True, filename="results/"+fn_results+"-speciation.svg")
    
    if DRAW_NETS:
        visualize.draw_net(config, winner, view=True,
                        filename="results/winner-"+fn_results+".net")
        visualize.draw_net(config, winner, view=True,
                        filename="results/winner-"+fn_results+"-enabled.net", show_disabled=False)
        visualize.draw_net(config, winner, view=True,
                        filename="results/winner-"+fn_results+"-pruned.net", show_disabled=False, prune_unused=True)
Пример #10
0
def run(config_file):
    # Load configuration.
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_file)

    # 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)
    p.add_reporter(neat.Checkpointer(5))

    # Run for up to 50 generations.
    winner = p.run(ai_plays, 50)

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

    pickle.dump(winner, open("chad.p", "wb"))

    node_names = {
        -1: "gameSpeed",
        -2: "yPosition",
        -3: "distToNextObstable",
        -4: "heightOfNextObstacle",
        0: 'Jump',
        1: 'Duck',
        2: 'Unduck',
        3: "Nothing"
    }
    visualize.draw_net(config, winner, True, node_names=node_names)
    visualize.plot_stats(stats, ylog=False, view=True)
    visualize.plot_species(stats, view=True)
def run(ins, outs, config_file, generations, kind, cores=4, labels=None, initial_state=None, showDiagrams=False):
    # Load configuration.
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_file)

    ###register here custom activation function (which must take 1 argument (the output)
    #config.genome_config.add_activation('name',func)

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

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

    # Run for up to <gen> generations.
    pe = neat.ParallelEvaluator(cores, eval_genome, kind, inputs=ins, outputs=outs)
    winner = p.run(pe.evaluate, generations)
    final_state = p.population, p.species, p.generation
    #winner = p.run(eval_genome, generations)

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

    #winner_net = neat.nn.FeedForwardNetwork.create(winner, config)
    winner_net = neuralnetworks[kind](winner, config)

    if showDiagrams:
        node_names = labels #{-1:'A', -2: 'B', 0:'Output', 1:'First hidden'}
        visualize.draw_net(config, winner, True, node_names = node_names)
        visualize.plot_stats(stats, ylog=False, view=True)
        #visualize.plot_species(stats, view=True)

    return winner_net, final_state
Пример #12
0
def run(n_generations, batch_size, threads):
    # Load the config file, which is assumed to live in
    # the same directory as this script.
    config_path = os.path.join(os.path.dirname(__file__), "neat.cfg")
    config = neat.Config(
        neat.DefaultGenome,
        neat.DefaultReproduction,
        neat.DefaultSpeciesSet,
        neat.DefaultStagnation,
        config_path,
    )

    pop = neat.Population(config)
    stats = neat.StatisticsReporter()
    pop.add_reporter(stats)
    reporter = neat.StdOutReporter(True)
    pop.add_reporter(reporter)

    evaluator = RewardToGoEnvEvaluator(make_net,
                                       activate_net,
                                       batch_size=batch_size,
                                       make_env=make_env,
                                       max_env_steps=max_env_steps)

    def eval_genomes(genomes, config):
        for _, genome in genomes:
            genome.fitness = evaluator.eval_genome(genome, config)

    logger = TensorBoardReporter(
        "%s-rtg-%s-batch" % (env_name, str(batch_size)), "neat4.log",
        evaluator.eval_genome)
    pop.add_reporter(logger)

    peval = neat.ParallelEvaluator(threads, eval_genomes)

    pop.run(peval.eval_function, n_generations)
Пример #13
0
def run(config_file):
    # Load configuration.
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_file)

    # 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)
    p.add_reporter(neat.Checkpointer(100))

    # Run for up to 300 generations.
    winner = p.run(eval_genomes, 10000)

    # 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)
Пример #14
0
def run(config_file):
    """load the config, create a population, evolve and show the result"""
    # Load configuration.
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_file)

    # 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 for up to 300 generations.
    pe = neat.ThreadedEvaluator(4, eval_genome)
    winner = p.run(pe.evaluate, 300)
    pe.stop()

    # 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)
    for xi, xo in zip(xor_inputs, xor_outputs):
        output = winner_net.activate(xi)
        print("input {!r}, expected output {!r}, got {!r}".format(
            xi, xo, output))

    if visualize is not None:
        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)
Пример #15
0
def run(cp, threads=1):
    evaluator = create_evaluator(threads)

    # initialize the population
    p = None
    stats = neat.StatisticsReporter()
    if cp:
        p = load_from_checkpoint(cp, evaluator)
    else:
        local_dir = os.path.dirname(__file__)
        config_path = os.path.join(local_dir, 'config')
        p = new_population(config_path, evaluator)

    if p:
        if mode != 'replay':
            p.add_reporter(neat.StdOutReporter(True))
            p.add_reporter(stats)
            p.add_reporter(checkpointer())
        else:
            p.add_reporter(replay())

        winner = p.run(evaluator, GENERATIONS)
        visualize.plot_stats(stats, ylog=False, filename="ff_fit_stats.svg")
        visualize.plot_species(stats, filename="ff_speciation.svg")
Пример #16
0
def run():
    # Load the file, witch is assumed to live in the same directory as this script
    local_dir = os.path.dirname(__file__)
    config_path = os.path.join(local_dir, 'cfg.txt')
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_path)

    pop = neat.Population(config)
    stats = neat.StatisticsReporter()
    pop.add_reporter(stats)
    pop.add_reporter(neat.StdOutReporter(True))
    best_genome = pop.run(eval_genomes, 100)

    visualize.draw_net(config,
                       best_genome,
                       view=False,
                       filename=str(pop.generation) + "net")
    visualize.plot_stats(stats, filename=str(pop.generation) + "plot_fit.png")
    visualize.plot_species(stats,
                           filename=str(pop.generation) + "plot_spec.png")

    with open('winner_ff.p', 'wb') as f:
        pickle.dump(best_genome, f)
Пример #17
0
def test_parallel():
    """Test parallel run using ParallelEvaluator (subprocesses)."""
    # Load configuration.
    local_dir = os.path.dirname(__file__)
    config_path = os.path.join(local_dir, 'test_configuration')
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_path)

    # 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(VERBOSE))
    stats = neat.StatisticsReporter()
    p.add_reporter(stats)
    p.add_reporter(neat.Checkpointer(1, 5))

    # Run for up to 19 generations.
    pe = neat.ParallelEvaluator(1 + multiprocessing.cpu_count(),
                                eval_dummy_genome_nn)
    p.run(pe.evaluate, 19)

    stats.save()
Пример #18
0
def run(config):
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config)

    # Create the population, which is the top-level object for a NEAT run.
    p = neat.Population(config)
    stats = neat.StatisticsReporter()
    p.add_reporter(stats)
    p.add_reporter(neat.StdOutReporter(True))
    # Checkpoint every 25 generations or 900 seconds.
    # p.add_reporter(neat.Checkpointer(10, 900))

    # Add a stdout reporter to show progress in the terminal.
    winner = p.run(evaluation, num_of_generations)

    # 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)
    best_fitness = do_rollout(winner_net, is_render)
    print("Test fitness of the best genome: ", best_fitness)
Пример #19
0
    def initialise(self, frequency_checkpoints, restore_checkpoint_name=None):
        if restore_checkpoint_name is not None:
            self._population = CheckpointerMine.restore_checkpoint_with_novelty(
                filename=restore_checkpoint_name,
                output_directory=self._output_directory,
                prob_add=self._prob_add)
        else:
            # Create the population, which is the top-level object for a NEAT run.
            self._population = PopulationWithNovelty(
                self._config,
                prob_add=self._prob_add,
                output_directory=self._output_directory)

        # Add a stdout reporter to show progress in the terminal.
        self._population.add_reporter(
            MineReporter(show_species_detail=True,
                         logger=self._log,
                         mlflow=self._mlflow))
        self._stats = neat.StatisticsReporter()
        self._population.add_reporter(self._stats)
        self._population.add_reporter(
            CheckpointerMine(generation_interval=frequency_checkpoints,
                             filename_prefix="{}/neat-checkpoint-".format(
                                 self._output_directory)))
Пример #20
0
def run(config_file, clientSocket, pigpio):

    # Load configuration.
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_file)

    # 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)
    p.add_reporter(neat.Checkpointer(5))

    # Run for up to 300 generations.
    winner = p.run(eval_box, eval_genomes, 300, clientSocket, pigpio)

    # Display the winning genome.
    # for g in itervalues(p.population):
    #     print('\nGemome:\n{!s}'.format(g))

    # print('\nSpecies:\n{!s}'.format(p.species))

    # species_to_json(p.species);

    # 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)
    for xi, xo in zip(xor_inputs, xor_outputs):
        output = winner_net.activate(xi)
        print("input {!r}, expected output {!r}, got {!r}".format(
            xi, xo, output))
Пример #21
0
    def main(self):
        #NEAT set up
        local_dir = os.path.dirname(__file__)
        config_path = os.path.join(local_dir, 'config')
        config = neat.Config(Player, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, config_path)

        pop = neat.Population(config)
        pop.add_reporter(neat.StdOutReporter(True))
        stats = neat.StatisticsReporter()
        pop.add_reporter(stats)

        winner = pop.run(self.eval_genomes,30)

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

        #Visualizes the statistics involved in the training
        visualize.plot_stats(stats, ylog=False, view=True) 
        visualize.plot_species(stats, view=True)
        node_names = {-1:'Obstacle Width', -2: 'Obstacle Height', -3: 'Distance to Obstacle', 0:'Jump or Not'}
        visualize.draw_net(config, winner, True, node_names=node_names)
        
        # Save winner in a file
        with open('bestPlayer_better.pickle', 'wb') as handle:
            pickle.dump(winner, handle, protocol = pickle.HIGHEST_PROTOCOL)
Пример #22
0
def run(config_file_path):
    """
    Main function for NEAT-NN
    :param config_file_path: path to a config file
    :return: None
    """
    config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction,
                                neat.DefaultSpeciesSet, neat.DefaultStagnation,
                                config_file_path)

    population = neat.Population(config)
    population.add_reporter(neat.StdOutReporter(True))
    statistics = neat.StatisticsReporter()
    population.add_reporter(statistics)

    try:
        winner = population.run(main, 100)
    except pygame.error as e:
        pass
    with open("results.txt", "a+") as results_file:
        results_file.write(f"Date: {datetime.datetime.now().ctime()} \n")
        results_file.write(f"Generations: {GEN_NUM}\n")
        results_file.write(f"Max score: {MAX_SCORE}\n")
        results_file.write(f"\n")
Пример #23
0
def train(generations):
	# Load configuration.
	config = create_config()

	# 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)
	p.add_reporter(neat.Checkpointer(1000))

	# Run for up to N generations.
	while True:
		winner = p.run(eval_genomes, generations)

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

		#visualize_net(config, winner, stats)

		net = neat.nn.RecurrentNetwork.create(winner, config)
		show_game(Board(), lambda b: update_from_net(b, net), 50)
Пример #24
0
def run(config_file, epochs):
    config = neat.Config(
        neat.DefaultGenome,
        neat.DefaultReproduction,
        neat.DefaultSpeciesSet,
        neat.DefaultStagnation,
        config_file,
    )

    p = neat.Population(config)
    # show_species_detail=True
    p.add_reporter(neat.StdOutReporter(True))
    p.add_reporter(neat.StatisticsReporter())
    p.add_reporter(neat.Checkpointer(10))

    winner = p.run(eval_genomes, epochs)
    print('\nBest genome:\n{!s}'.format(winner))

    winner_net = neat.nn.FeedForwardNetwork.create(winner, config)
    trader = NeatBasedTrader(amount=INITIAL_AMOUNT, net=winner_net)
    print('\nTrade with best genome:')

    p, _ = evaluate_agent(agent=trader, verbose=True)
    print('\nProfit: {:.2f}'.format(p))
Пример #25
0
    def run(config_file):
        # Load configuration.
        config = neat.Config(
            neat.DefaultGenome,
            neat.DefaultReproduction,
            neat.DefaultSpeciesSet,
            neat.DefaultStagnation,
            config_file,
        )

        # 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
        reporter = neat.StdOutReporter(False)
        p.add_reporter(reporter)
        stats = neat.StatisticsReporter()
        p.add_reporter(stats)
        #checkpointer = neat.Checkpointer(100)
        #p.add_reporter(checkpointer)
        # Run for up to 300 generations.
        winner = p.run(eval_genomes, num_generations)

        return [stats, winner]
Пример #26
0
def run(config_file):
    # loading the config file and it's details with the headings:
    # [DefaultGenome], [DefaultReproduction], [DefaultSpeciesSet], [DefaultStagnation]
    # [NEAT] is not required to be mentioned as it's a mandatory config
    config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction,
                                neat.DefaultSpeciesSet, neat.DefaultStagnation,
                                config_file)

    # this is used to set the population details from the config file
    p = neat.Population(config)

    # this is used to give the output
    p.add_reporter(neat.StdOutReporter(True))
    stats = neat.StatisticsReporter()
    p.add_reporter(stats)

    if os.path.exists(model_dir + '/' + model_file):
        genomes = []
        with open(model_dir + '/' + model_file, 'rb') as f:
            genomes = [(1, pickle.load(f))]
        eval_genome(genomes, config)
    else:
        # represents the no of generations to run the fitness funtion
        generations = 50
        # the "main" function is our fitness function
        # the function has to be modified to run for more than one bird
        # i.e., the entire population in that generation
        # calling it eval_genome and rewriting the function
        winner = p.run(eval_genome, generations)
        if not os.path.exists(model_dir):
            os.makedirs(model_dir)
        with open(model_dir + '/' + model_file, 'wb') as f:
            pickle.dump(p.best_genome, f)

        # show final stats
        print('\nBest genome:\n{!s}'.format(winner))
Пример #27
0
def run_neat(mode="1p"):
    global env

    if mode == "1p":
        print("Starting 1P mode!")
        env = retro.make('Boxing-Atari2600', 'Start.state')
    if mode == "2p":
        print("Starting 2P mode!")
        env = retro.make('Boxing-Atari2600', 'boxing_2p.state', players=2)

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

    p = neat.Population(config)

    # print statistics after each generation
    p.add_reporter(neat.StdOutReporter(True))
    p.add_reporter(neat.StatisticsReporter())

    # adds a checkpoint every 5 generations - generates a file that can later be reused if you don't want to restart from scratch after making a change
    p.add_reporter(neat.Checkpointer(5))

    winner = p.run(eval_genomes)
Пример #28
0
def run(config_file):

    config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction,
                                neat.DefaultSpeciesSet, neat.DefaultStagnation,
                                config_file)

    p = neat.Population(config)

    p.add_reporter(neat.StdOutReporter(True))
    stats = neat.StatisticsReporter()
    p.add_reporter(stats)

    winner = p.run(eval_genomes, 10)

    visualize.plot_stats(stats,
                         ylog=True,
                         view=True,
                         filename="feedforward-fitness.svg")
    visualize.plot_species(stats,
                           view=True,
                           filename="feedforward-speciation.svg")

    # show final stats
    print('\nBest genome:\n{!s}'.format(winner))
Пример #29
0
def run(config_file):
    # Load configuration.
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_file)

    # 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)
    p.add_reporter(neat.Checkpointer(5))

    # Run for up to 200 generations.
    winner = p.run(eval_genomes, 200)

    # 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)
    for xi, xo in zip(inputs, outputs):
        output = winner_net.activate(xi)
        print("input {!r}, expected output {!r}, got {!r}".format(
            xi, xo, output))

    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)

    p = neat.Checkpointer.restore_checkpoint('neat-checkpoint-4')
    p.run(eval_genomes, 10)
Пример #30
0
def run(config_file):
    """load the config, create a population, evolve and show the result"""
    # Load configuration.
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_file)

    # 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)
    p.add_reporter(neat.Checkpointer(50))

    # Run for up to 300 generations.
    pe = neat.ThreadedEvaluator(8, eval_genome)
    winner = p.run(pe.evaluate, 1000)
    filehandler = open("./winner.pkl", 'wb', pickle.HIGHEST_PROTOCOL)
    pickle.dump(winner, filehandler)
    pe.stop()

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