Beispiel #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)

    checkpointer = neat.Checkpointer(generation_interval=50)
    p.add_reporter(checkpointer)

    # Run for up to 300 generations.
    if debug:
        pe = neat.ParallelEvaluator(2, eval_genome)
        winner = p.run(pe.evaluate, 1)
    else:
        pe = neat.ParallelEvaluator(30, eval_genome)
        winner = p.run(pe.evaluate, 1000)

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

    # write the most fit nn
    checkpointer.save_checkpoint(config, p, winner,
                                 checkpointer.current_generation)
    winner_net = neat.nn.FeedForwardNetwork.create(winner, config)
    pickle_winner_net(winner_net)
Beispiel #2
0
def run(config_file):
    '''Run neat using config_file

    Args:
        config_file (os.path): Path to 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.
    pop = neat.Population(config)

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

    if RUN_MULTITHREADED:
        # Run for up to 300 generations.
        pop_eval = neat.ParallelEvaluator(THREADS, eval_genome)
        winner = pop.run(pop_eval.evaluate, GENERATIONS)
    else:
        # Run for up to 300 generations.
        winner = pop.run(eval_genomes, 300)

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

    # Save the winner.
    with open('winner-feedforward', 'wb') as winner_file:
        pickle.dump(winner, winner_file)
Beispiel #3
0
def run(config_file, it, cores):
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_file)

    # Create the population
    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 x generations
    pe = neat.ParallelEvaluator(cores, eval_genome)
    winner = p.run(pe.evaluate, it)

    # Display and save the winning genome
    print('\nBest genome:\n{!s}'.format(winner))
    with open('winner/winner-parallel.pkl', 'wb') as output:
        pickle.dump(winner, output, 1)

    visualize.draw_net(config, winner, view=True, filename="draw_net")
    visualize.plot_stats(stats, ylog=False, view=True)
    visualize.plot_species(stats, view=True)
Beispiel #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)

    # Run for up to 300 generations.
    pe = neat.ParallelEvaluator(4, eval_genome)
    winner = p.run(pe.evaluate, 300)

    # 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))

    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)
Beispiel #5
0
def run(config_file):

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

    population = neat.Population(config)
    population.add_reporter(neat.StdOutReporter(True))
    stats = neat.StatisticsReporter()
    population.add_reporter(stats)
    population.add_reporter(neat.Checkpointer(5))

    parallelEval = neat.ParallelEvaluator(cpu_count, eval_genomes)
    print('Evaluating on {} CPUs'.format(cpu_count))

    winner = population.run(parallelEval.evaluate, 1000)

    print('\n Best Genome : \n {}'.format(winner))
    print('\n\n Output : ')

    winner_net = neat.nn.FeedForwardNetwork.create(winner, config)

    visualize.draw_net(config, winner, True)
    visualize.plot_stats(stats, ylog=False, view=True)
    visualize.plot_species(stats, view=True)

    environment(winner_net)
Beispiel #6
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.
    # We restore the population that was the fittest
    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(15))

    parallel_evaluator = neat.ParallelEvaluator(8, eval_genomes)

    # Run for up to 200 generations.
    winner = p.run(parallel_evaluator.evaluate)

    # 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)
    # We save the winner network in a pickle container
    with open('winner.pkl', 'wb') as output:
        pickle.dump(winner, output, 1)
Beispiel #7
0
    def train(self, config_file):
        local_dir = os.path.dirname(__file__)
        config_path = os.path.join(local_dir, config_file)

        # Load Config
        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(True))
        stats = neat.StatisticsReporter()
        p.add_reporter(stats)
        p.add_reporter(neat.Checkpointer(50))

        # Run for up to 300 generations
        pe = neat.ParallelEvaluator(24, self.play)
        winner = p.run(pe.evaluate, 1000)

        #save winnning genome
        with open("winner.pkl", "wb") as output:
            pickle.dump(winner, output, 1)

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

        visualize.plot_stats(stats, ylog=False, view=True)
        visualize.plot_species(stats, view=True)
def run():
    # Load the config file, which is assumed to live in
    # the same directory as this script.
    local_dir = os.path.dirname(__file__)
    config_path = os.path.join(local_dir, config_name)
    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))
    pop.add_reporter(neat.Checkpointer(5))

    pe = neat.ParallelEvaluator(8, eval_genome)
    winner = pop.run(pe.evaluate, 200)

    # winner = pop.run(eval_genomes, 300)

    # Save the winner.
    with open('winner-feedforward', 'wb') as f:
        pickle.dump(winner, f)

    print(winner)

    net = neat.nn.FeedForwardNetwork.create(winner, config)

    visualize_winner(net)
Beispiel #9
0
def main(config_file):
    # Get initial time.
    start_time = time()
    # Load configuration for NEAT-Python.
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_file)

    # Create population, core of NEAT algorithm.
    pop = neat.Population(config)

    # Create stdout reporter to print progress, currently not implemented.
    pop.add_reporter(neat.StdOutReporter(False))
    stats = neat.StatisticsReporter()
    pop.add_reporter(stats)

    # Run for unlimited generations max.
    para_eval = neat.ParallelEvaluator(4, play_game)
    winner = pop.run(para_eval.evaluate, 1000)

    # Display winning genome.
    print "\nBest Genome: " + str(winner)
    print "Running Time (in secs.): " + str(time() - start_time)

    visualize.draw_net(config, winner, True)
    visualize.plot_stats(stats, ylog=False, view=True)
Beispiel #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)

    # TODO restart from checkpoint
    # neat.Checkpointer.restore_checkpoint(filename)

    # Add a stdout reporter to show progress in the terminal.
    p.add_reporter(neat.StdOutReporter(False))
    stats = neat.StatisticsReporter()
    p.add_reporter(stats)
    p.add_reporter(
        neat.Checkpointer(generation_interval=100, time_interval_seconds=None))

    p.add_reporter(opponent_tracker)

    # Run for up to 300 generations.
    winner = None
    if debug:
        winner = p.run(eval_genomes, 300)
    else:
        pe = neat.ParallelEvaluator(4, eval_genome)
        winner = p.run(pe.evaluate)
Beispiel #11
0
def run(generation = 0, num_iterations = None):
    # Carrega o config
    local_dir = os.path.dirname(__file__)
    config_path = os.path.join(local_dir, 'config')
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_path)


    check_point = neat.Checkpointer(generation_interval=5)    
    pop = None

    if(generation == 0):
        # Inicia nova população
        pop = neat.Population(config)
    else:
        # Restaura população de um checkpoint
        filename = 'neat-checkpoint-' + str(generation)
        pop = check_point.restore_checkpoint(filename)

    pop.add_reporter(neat.StdOutReporter(True))
    pop.add_reporter(check_point)
    pe = neat.ParallelEvaluator(None, eval_genome)
    winner = pop.run(pe.evaluate, num_iterations)        

    # Save the winner.
    with open('winner', 'wb') as f:
        winner_tuple = (winner, config, main_actions)
        pickle.dump(winner_tuple, f)
        print("Winner salvo")
def run():
    # Load the config file, which is assumed to live in
    # the same directory as this script.
    local_dir = os.path.dirname(__file__)
    config_path = os.path.join(local_dir, 'config-feedforward')
    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))

    pe = neat.ParallelEvaluator(4, eval_genome)
    winner = pop.run(pe.evaluate)

    # Save the winner.
    with open('winner-feedforward', 'wb') as f:
        pickle.dump(winner, f)

    print(winner)

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

    node_names = {-1: 'M1', -2: 'M2', -3: 'M3', 0: 'x1', 1: 'x2'}
    visualize.draw_net(config, winner, True, node_names=node_names)

    visualize.draw_net(config, winner, view=True, node_names=node_names,
                       filename="winner-feedforward.gv")
    visualize.draw_net(config, winner, view=True, node_names=node_names,
                       filename="winner-feedforward-enabled.gv", show_disabled=False)
    visualize.draw_net(config, winner, view=True, node_names=node_names,
                       filename="winner-feedforward-enabled-pruned.gv", show_disabled=False, prune_unused=True)
Beispiel #13
0
    def run(self):
        if self.generation > 0:
            with gzip.open('checkpoints/neat-checkpoint-{0}'.format(
                    self.generation)) as f:
                self.generation, self.config, population, species_set, rndstate = pickle.load(
                    f)
                self.generation += 1
                random.setstate(rndstate)
                self.population = neat.Population(
                    self.config, (population, species_set, self.generation))
        else:
            self.config = neat.Config(neat.DefaultGenome,
                                      neat.DefaultReproduction,
                                      neat.DefaultSpeciesSet,
                                      neat.DefaultStagnation, 'config')

            self.population = neat.Population(self.config)

        stats = neat.StatisticsReporter()
        self.population.add_reporter(neat.StdOutReporter(True))
        self.population.add_reporter(stats)
        self.population.add_reporter(
            neat.Checkpointer(generation_interval=200,
                              filename_prefix='checkpoints/neat-checkpoint-'))

        self.evaluator_thread = neat.ParallelEvaluator(self.threads,
                                                       eval_genome, 4000)
        winner = self.population.run(self.evaluator_thread.evaluate,
                                     200)  # 200 generations

        with open('checkpoints/winner', 'wb') as output:
            pickle.dump(winner, output, 1)
Beispiel #14
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(False))
    # stats = neat.StatisticsReporter()
    # p.add_reporter(stats)

    # winner = p.run(eval_genomes, 300)
    pe = neat.ParallelEvaluator(8, eval_genome)
    winner = p.run(pe.evaluate, 300)

    # Show output of the most fit genome against training data.
    winning_net = neat.nn.FeedForwardNetwork.create(winner, config)
    winning_player = ANNPlayer(winning_net, "ANN")
    results = play_games(100, [winning_player] + OTHER_PLAYERS)
    print("Winner sample game results:")
    print(results[winning_player.name])
    print(sum([1 for x in results[winning_player.name] if x == 1]))
Beispiel #15
0
def evolve(config, evalfun, seed, task_name, ngen, checkpoint):
    '''
    NEAT evolution with parallel evaluator
    '''

    # Set random seed (including None)
    random.seed(seed)

    # Make directories for saving results
    os.makedirs('models', exist_ok=True)
    os.makedirs('visuals', exist_ok=True)

    # Create an ordinary population or a population for NoveltySearch
    pop = _NoveltyPopulation(config) if config.is_novelty() else Population(
        config)

    # Add a stdout reporter to show progress in the terminal.
    pop.add_reporter(_StdOutReporter(show_species_detail=False))
    stats = neat.StatisticsReporter()
    pop.add_reporter(stats)

    # Add a reporter (which can also checkpoint the best)
    pop.add_reporter(_SaveReporter(task_name, checkpoint))

    # Create a parallel fitness evaluator
    pe = neat.ParallelEvaluator(mp.cpu_count(), evalfun)

    # Run for number of generations specified in config file
    winner = pop.run(pe.evaluate) if ngen is None else pop.run(
        pe.evaluate, ngen)

    # Save winner
    config.save_genome(winner)
Beispiel #16
0
def evolve(config, num_cores):
    pop = load_checkpoint(config)
    pop.add_reporter(
        neat.Checkpointer(1, 600, CHECKPOINTS_DIR + "neat-checkpoint-"))
    pop.add_reporter(neat.StdOutReporter(True))
    stats = neat.StatisticsReporter()
    pop.add_reporter(stats)

    pe = neat.ParallelEvaluator(num_cores, evaluate)

    while True:
        winner = pop.run(pe.evaluate, 1)

        visualize.plot_stats(stats,
                             ylog=False,
                             view=False,
                             filename=SESSION_DIR + 'avg_fitness.svg')
        visualize.plot_species(stats,
                               view=False,
                               filename=SESSION_DIR + 'speciation.svg')

        # Save the best Genome from the last 5 gens.
        with open(
                SESSION_DIR +
                'Best-{}.pkl'.format(len(stats.most_fit_genomes)),
                'wb') as output:
            pickle.dump(winner, output, 1)

        if stats.get_fitness_mean()[-1] >= END_DISTANCE:
            break
Beispiel #17
0
def run():
    # Load configuration.
    config = neat.Config(neat.SharedGenome, 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)
    p.add_reporter(neat.Checkpointer(5, filename_prefix='shared_'))

    pe = neat.ParallelEvaluator(multiprocessing.cpu_count(), eval_genome)
    # Run until a solution is found.
    winner = p.run(pe.evaluate, 100)

    # 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)
Beispiel #18
0
def run():
    # Load the config file, which is assumed to live in
    # the same directory as this script.
    local_dir = os.path.dirname(__file__)
    config_path = os.path.join(local_dir, 'configs/neat_config.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)
    pop.add_reporter(neat.StdOutReporter(True))

    pe = neat.ParallelEvaluator(6, eval_genome)
    winner = pop.run(pe.evaluate)

    # Save the winner.
    with open('models/winner-feedforward.model', 'wb') as f:
        pickle.dump(winner, f)

    visualize.plot_stats(stats,
                         ylog=True,
                         view=True,
                         filename="models/feedforward-fitness.svg")
    visualize.plot_species(stats,
                           view=True,
                           filename="models/feedforward-speciation.svg")
    visualize.draw_net(config, winner, True)
Beispiel #19
0
def run():

    pop = Checkpointer.restore_checkpoint('neat-checkpoint-3')

    winner = Checkpointer.

    stats = neat.StatisticsReporter()

    pe = neat.ParallelEvaluator(1, eval_genome)
    winner = pop.run(pe.evaluate)

    print(winner)

    #print(pop.statistics.best_genome())

    net = neat.nn.FeedForwardNetwork.create(genome, config)
    driver = main(TestNeatDriver(logdata=False, net=net))
    
    visualize.plot_stats(stats, ylog=True, view=True, filename="feedforward-fitness.svg")
    visualize.plot_species(stats, view=True, filename="feedforward-speciation.svg")

    node_names = {-1: 'x', -2: 'dx', -3: 'theta', -4: 'dtheta', 0: 'control'}
    visualize.draw_net(config, winner, True, node_names=node_names)

    visualize.draw_net(config, winner, view=True, node_names=node_names,
                       filename="winner-feedforward.gv")
    visualize.draw_net(config, winner, view=True, node_names=node_names,
                       filename="winner-feedforward-enabled.gv", show_disabled=False)
    visualize.draw_net(config, winner, view=True, node_names=node_names,
                       filename="winner-feedforward-enabled-pruned.gv", show_disabled=False, prune_unused=True)
Beispiel #20
0
def run(config_file, restore_file=None):
    # 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 = None
    if restore_file is None:
        p = neat.Population(config)
    else:
        p = neat.Checkpointer.restore_checkpoint(restore_file)

    p.add_reporter(neat.Checkpointer(generation_interval=10, time_interval_seconds=None))

    p.add_reporter(trackers.AssistanceRequestTracker(p.generation))
    p.add_reporter(trackers.ReportBestTracker(p.generation))

    # Run for up to 300 generations.
    winner = None
    if debug:
        winner = p.run(eval_genomes, 300)
    else:
        pe = neat.ParallelEvaluator(4, eval_genome)
        winner = p.run(pe.evaluate)

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

    print("Saving as winner-genome-{}.pkl".format(winner.fitness))
    with open('winner-genome-{}.pkl'.format(winner.fitness), 'wb') as output:
        pickle.dump(winner, output, 1)

    visualize.plot_stats(stats, ylog=False, view=True)
    visualize.plot_species(stats, view=True)
Beispiel #21
0
def run():
    # Load configuration.
    config = neat.Config(neat.SharedGenome, 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(False))

    pe = neat.ParallelEvaluator(multiprocessing.cpu_count(), eval_genome)
    # Run until a solution is found.
    winner = p.run(pe.evaluate, 100)

    # 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))
Beispiel #22
0
def run():
    # Load the config file, which is assumed to live in
    # the same directory as this script.

    pop = Checkpointer().restore_checkpoint("neat-checkpoint-27")
    # local_dir = os.path.dirname(__file__)
    # config_path = os.path.join(local_dir, 'config-ctrnn')
    # config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
    #                      neat.DefaultSpeciesSet, neat.DefaultStagnation,
    #                      config_path)
    # pop = neat.Population(config)
    stats = neat.StatisticsReporter()
    check = Checkpointer(2, time_interval_seconds=None)
    pop.add_reporter(stats)
    pop.add_reporter(check)
    pop.add_reporter(neat.StdOutReporter(True))

    pe = neat.ParallelEvaluator(1, eval_genome)
    winner = pop.run(pe.evaluate, 500)

    # Save the winner.
    with open('winner-feedforward', 'wb') as f:
        pickle.dump(winner, f)

    print(winner)
Beispiel #23
0
def run():
    run_parallel = False

    # Load the config file, which is assumed to live in
    # the same directory as this script.
    local_dir = os.path.dirname(__file__)
    config_path = os.path.join(local_dir, 'config-feedforward-cartpole')
    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))

    max_generations = 300

    if run_parallel:
        pe = neat.ParallelEvaluator(8, eval_genome)
        winner = pop.run(pe.evaluate, max_generations)
    else:
        winner = pop.run(eval_genomes, max_generations)

    # Save the winner.
    with open('winner-feedforward', 'wb') as f:
        pickle.dump(winner, f)

    print(winner)

    visualize.plot_stats(stats,
                         ylog=True,
                         view=False,
                         filename="feedforward-fitness.svg")
Beispiel #24
0
def evolve(config, num_cores):
    pop = load_checkpoint(config)
    pop.add_reporter(
        neat.Checkpointer(1, 600, CHECKPOINTS_DIR + "neat-checkpoint-"))
    pop.add_reporter(neat.StdOutReporter(True))
    stats = neat.StatisticsReporter()
    pop.add_reporter(stats)

    pe = neat.ParallelEvaluator(num_cores, evaluate)

    for gen in range(500):
        winner = pop.run(pe.evaluate, 1)

        winner_distance = play_best(winner, config)

        with open(SESSION_DIR + 'stats.csv', mode='a') as stats_file:
            stats_writer = csv.writer(stats_file,
                                      delimiter=',',
                                      quotechar='"',
                                      quoting=csv.QUOTE_MINIMAL)
            stats_writer.writerow([gen, winner_distance])

        with open(
                SESSION_DIR +
                'Best-{}.pkl'.format(len(stats.most_fit_genomes)),
                'wb') as output:
            pickle.dump(winner, output, 1)
Beispiel #25
0
def run():
    # Load the config file, which is assumed to live in
    # the same directory as this script.
    local_dir = os.path.dirname(__file__)
    config_path = os.path.join(local_dir, 'config')
    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))

    # runs evaluation functions in parallel subprocesses in order to evaluate multiple genomes at once.
    pe = neat.ParallelEvaluator(multiprocessing.cpu_count(), eval_genome)
    winner = pop.run(pe.evaluate)

    # Save the winner.
    with open('winner-NEAT-pickle', 'wb') as f:
        pickle.dump(winner, f)

    print(winner)

    visualize.plot_stats(stats,
                         ylog=True,
                         view=True,
                         filename="winner-NEAT-fitness")
    visualize.plot_species(stats, view=True, filename="winner-NEAT-speciation")
def run(config_file):
    config = neat.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)

    pe = neat.ParallelEvaluator(4, eval_genome)
    winner = p.run(pe.evaluate, 300)
    print('\nBest genome:\n{!s}'.format(winner))

    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))

    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)
def run(config_file):
    config = neat.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)

    pe = neat.ParallelEvaluator(2, eval_genomes)
    winner = p.run(pe.evaluate, 2000)

    winner_net = neat.nn.FeedForwardNetwork.create(winner, config)
    accuracy = 0.0

    for xi, yo in zip(X_test, y_test):
        output = winner_net.activate(xi)
        if (np.argmax(yo) == np.argmax(output)):
            accuracy += 1

    print("\nAccuracy: ", accuracy / len(y))
    file1 = open("results-05d.txt", "w")
    file1.write("Accuracy test: ")
    file1.write(str(accuracy / len(y)))
    file1.write('\nBest genome:\n{!s}'.format(winner))
    file1.close()

    with open('winner-5d', 'wb') as f:
        pickle.dump(winner, f)
Beispiel #28
0
def run(config_file):
	# Load configuration.
	config = neat.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)

	corecount = 1
	if (CORES == 0):
		corecount = multiprocessing.cpu_count()
	else:
		corecount = CORES
	pe = neat.ParallelEvaluator(corecount, eval_genome)
	# Run for up to x generations.
	winner = p.run(pe.evaluate, GENERATIONS)

	#save winning version

	pickle.dump( winner , open( './models/model.pkl' , 'wb' ) )
Beispiel #29
0
def run():
    # Load the config file, which is assumed to live in
    # the same directory as this script.
    local_dir = os.path.dirname(__file__)
    config_path = os.path.join(local_dir, 'config-ctrnn')
    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))

    if True:
        winner = pop.run(eval_genomes, 2000)
    else:
        pe = neat.ParallelEvaluator(4, eval_genome)
        winner = pop.run(pe.evaluate, 2000)

    # Save the winner.
    with open('winner-ctrnn', 'wb') as f:
        pickle.dump(winner, f)

    print(winner)
Beispiel #30
0
def run(config_file):
    """ Main function that runs the neat platform
        - Loads the config file
        - Initializes the population according to the parameters of the config file
        - Add a Reporter to collect statistics of the runs
        - Add a Checkpointer to save (using picke):
            generation, config, population, species_set, rndstate
    """
    # 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.
    custom_stats = custom_report.StdOutReporter()
    p.add_reporter(custom_stats)

    # save a checkpointer each generation
    p.add_reporter(neat.Checkpointer(1))

    # Run using parallelizing with thenumber of processors for NUM_GENERATIONS
    pe = neat.ParallelEvaluator(multiprocessing.cpu_count(), eval_genome)
    winner = p.run(pe.evaluate, NUM_GENERATIONS)
    # save the results of the Statistics collected by the Reporter into a csv
    custom_stats.save_table('stats_table')