예제 #1
0
def run_primary(addr, authkey, generations):
    """Starts a DistributedEvaluator in primary mode."""
    # 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(True))
    stats = neat.StatisticsReporter()
    p.add_reporter(stats)
    p.add_reporter(neat.Checkpointer(max(1,int(generations/3)), 5))

    # Run for the specified number of generations.
    de = neat.DistributedEvaluator(
        addr,
        authkey=authkey,
        eval_function=eval_dummy_genome_nn,
        mode=MODE_PRIMARY,
        secondary_chunksize=15,
        )
    print("Starting DistributedEvaluator")
    sys.stdout.flush()
    de.start()
    print("Running evaluate")
    sys.stdout.flush()
    p.run(de.evaluate, generations)
    print("Evaluated")
    sys.stdout.flush()
    de.stop(wait=5)
    print("Did de.stop")
    sys.stdout.flush()

    stats.save()
예제 #2
0
def run(config_file, checkpoint_generation):
    # 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.
    if not checkpoint_generation is None:
      p = neat.Checkpointer.restore_checkpoint('neat-checkpoint-' + str(checkpoint_generation))

      for f in os.listdir('.'):
        if re.search('neat-checkpoint', f) and not re.search('-' + str(checkpoint_generation), f):
          os.remove(os.path.join('.', f))
        if re.search('winner-net', f) and not re.search('-' + str(checkpoint_generation), f):
          os.remove(os.path.join('.', f))

    else:
      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(10))

    plot_handles = []
    pe = neat.ParallelEvaluator(60, eval_genome)
    for x in range(11):

      plot_handles.append(evolute_for_x_generations(
          config,
          p,
          pe,
          stats,
          10,
          0 if not checkpoint_generation else checkpoint_generation
      ))

    plt.legend(handles=plot_handles)
예제 #3
0
def run(config_path):
    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)
    checkpoint = neat.Checkpointer(10)
    p.add_reporter(checkpoint)

    # pe = neat.ParallelEvaluator(4,main)
    # winner = p.run(pe.evaluate,100)
    winner = p.run(main, 100)

    print(winner)
    f = open('winner.p', 'wb')
    pickle.dump(winner, f)
    visualize.draw_net(config, winner, True)
    visualize.plot_stats(stats, ylog=False, view=True)
    visualize.plot_species(stats, view=True)
예제 #4
0
def run(config_file_path, checkpoints_folder_path):
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_file_path)

    # Change dir to save checkpoints in suitable folder
    if not os.path.exists(checkpoints_folder_path):
        os.makedirs(checkpoints_folder_path)
    os.chdir(checkpoints_folder_path)
    # Clear checkpoint folder each 10 seconds
    # threading.Thread(target = clear_checkpoints, args = os.curdir).start()
    file_list = glob.glob(os.path.join(os.curdir, "neat-checkpoint-*"))
    p = None
    if (len(file_list) != 0):
        last_checkpoint = max(file_list,
                              key=lambda file: os.path.getmtime(file))
        print(last_checkpoint)
        # p = neat.Checkpointer.restore_checkpoint(last_checkpoint)
        p = neat.Checkpointer.restore_checkpoint(last_checkpoint)
    else:
        p = neat.Population(config)

    p.add_reporter(neat.StdOutReporter(True))
    stats = neat.StatisticsReporter()
    p.add_reporter(stats)
    # Save the process after each 10 frames
    p.add_reporter(CheckpointerWithClear(10))
    pe = neat.ParallelEvaluator(5, eval_genome_parallel)

    # Parallel run
    winner = p.run(pe.evaluate)
    done = True

    # Sequential run
    # winner = p.run(eval_genomes_sequential)

    path_to_winner_file = os.path.join(os.path.dirname(__file__), 'winner.pkl')
    with open(path_to_winner_file, 'wb') as output:
        pickle.dump(winner, output, 1)
예제 #5
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-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)
def run(config_path):
    """
        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_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)

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

    pass
예제 #7
0
def run(config_file: str):
    config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction,
                                neat.DefaultSpeciesSet, neat.DefaultStagnation,
                                config_path)

    population = neat.Population(config)

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

    winner = population.run(eval_fitness, 500)

    winner

    some_input = input("Save winner? ")
    if some_input == 'yes':
        try:
            pickle_in = open("saved_winners.pickle", "rb")
            current = pickle.load(pickle_in)
            pickle_in.close()
        except FileNotFoundError:
            current = None

        if current == None:
            current = []

        current.append(winner)

        pickle_out = open("saved_winners.pickle", "wb")

        pickle.dump(current, pickle_out)
        pickle_out.close()

    some_input = input("Display winners? ")
    if some_input == 'yes':
        pickle_in = open("saved_winners.pickle", "rb")
        them = pickle.load(pickle_in)
        print(them)
예제 #8
0
def main():

    # 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: 'x', -2: 'y', 0: 'wait', 1: 'flap'}

    visualize.draw_net(config,
                       winner,
                       view=True,
                       node_names=node_names,
                       filename="winner-feedforward.gv")
예제 #9
0
def run(config_file):
    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)
    # Create the population, which is the top-level object for a NEAT run
    population = neat.Population(config)

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

    #Run for 300 generation
    winner = population.run(eval_genomes, generations)

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

    # Show output of the most fit genome against training data.
    winner_net = neat.nn.FeedForwardNetwork.create(winner, config)
    observation = env.reset()
    scores = []
    for i in range(trials):
        score = 0
        env.reset()
        for _ in range(goal_steps):
            env.render()
            action = np.argmax(winner_net.activate(observation))
            # do it!
            observation, reward, done, info = env.step(action)
            score += reward
            if done: break
        scores.append(score)
    print("The winning neural network obtained an average score of: " +
          str(np.average(scores)))
    p = neat.Checkpointer.restore_checkpoint('neat-checkpoint-4')
    p.run(eval_genomes, 10)
def run(config_file_path, checkpoint_file_path=None, parallel=False):
    """ Load Neat configuration with all Defaults, register reporters and train the population with eval_genomes """
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_file_path)

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

    # Add reporters to show progress in the terminal.
    pop.add_reporter(neat.StdOutReporter(True))
    pop.add_reporter(neat.StatisticsReporter())

    # Enable Checkpointing and possibly load existing checkpoint
    pop.add_reporter(neat.Checkpointer(5))
    if checkpoint_file_path is not None:
        print(
            "Using pre-existing checkpoint and configuration! Possible different config file is dismissed!"
        )
        pop = neat.Checkpointer.restore_checkpoint(checkpoint_file_path)

    # Calculate reshape resolution tuple according to specified parameters
    in_x, in_y, _ = env.observation_space.shape
    global env_reshape_tuple
    env_reshape_tuple = (int(in_x / cv_resolution_divisor),
                         int(in_y / cv_resolution_divisor))

    # Run either paralle or single-threaded for specified max number of generations.
    if parallel:
        pe = neat.ParallelEvaluator(nr_parallel_env, eval_genome)
        best_genome = pop.run(pe.evaluate, max_generations)
    else:
        best_genome = pop.run(eval_genomes, max_generations)

    # Display and save the winning genome.
    print('\nBest genome:\n{!s}'.format(best_genome))
    with open('best_genome.pkl', 'wb') as output:
        pickle.dump(best_genome, output, 1)
예제 #11
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)
        # TODO can we get checkpoint to store current opponent as well

    # 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=10, 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)

    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)
예제 #12
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())

    if 0:
        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)

    visualize.plot_stats(stats, ylog=True, view=True, filename="ctrnn-fitness.svg")
    visualize.plot_species(stats, view=True, filename="ctrnn-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-ctrnn.gv")
    visualize.draw_net(config, winner, view=True, node_names=node_names,
                       filename="winner-ctrnn-enabled.gv", show_disabled=False)
    visualize.draw_net(config, winner, view=True, node_names=node_names,
                       filename="winner-ctrnn-enabled-pruned.gv", show_disabled=False, prune_unused=True)
def run(config_file, n_gen, train_loader, val_loader):
    """
    Launches a run until convergence or max number of generation reached
    :param config_file: path to the config file
    :param n_gen: lax number of generation
    :return: the best genontype (winner), the configs, the stats of the run and the accuracy on the testing set
    """
    # 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(generation_interval=100))

    # Run for up to n_gen generations.
    multi_evaluator = Anti_spoofing_Evaluator(n_processes,
                                              eval_genome,
                                              train_loader,
                                              val_loader,
                                              config_,
                                              gc_eval=eer_gc)
    winner_ = p.run(multi_evaluator.evaluate, n_gen)

    gc_scores = np.zeros(n_gen)
    for gc_index in range(n_gen):
        _, genome = multi_evaluator.gc[gc_index]
        gc_scores[gc_index] = eer_gc(genome, config_, test_loader)

    _, winner_ = multi_evaluator.gc[np.argmax(gc_scores)]

    return winner_, config_, stats_
예제 #14
0
def _run_neat(checkpoint, eval_network, eval_single_genome):
    # Create the population, which is the top-level object for a NEAT run.

    print_config_info()

    if checkpoint is not None:
        print("Resuming from checkpoint: {}".format(checkpoint))
        p = neat.Checkpointer.restore_checkpoint(checkpoint)
    else:
        print("Starting run from scratch")
        p = neat.Population(config)

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

    p.add_reporter(
        neat.Checkpointer(CHECKPOINT_GENERATION_INTERVAL,
                          filename_prefix=CHECKPOINT_PREFIX))

    # Add a stdout reporter to show progress in the terminal.
    p.add_reporter(neat.StdOutReporter(False))

    # Run until a solution is found.
    winner = p.run(partial(_eval_genomes, eval_single_genome), n=MAX_GENS)

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

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

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

    test_genome(eval_network, net)

    generate_stat_plots(stats, winner)

    print("Finishing...")
예제 #15
0
def run(window, surface):
    global SIZE, screen, game_over, main_menu
    config_file = os.path.join(PATH, "config2.txt")
    SIZE = window
    screen = surface
    config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction,
                                neat.DefaultSpeciesSet, neat.DefaultStagnation,
                                config_file)
    population = neat.Population(config)
    best_genome = population.run(gameplay, 500)
    if __name__ == "__main__" and not game_over:
        test_database = shelve.open("test_database")
        test_database["test"] = high_net
        test_database.close()
        f = open("score_list.json", "wt")
        json.dump(max_score_list, f)
        f.close()
    if main_menu:
        return None
    elif game_over:
        return 'gameover'
    else:
        return None
예제 #16
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(multiprocessing.cpu_count(), eval_genome)
    winner = p.run(pe.evaluate, 2000)

    return stats
예제 #17
0
def test_run_nn_recurrent():
    """Basic test of nn.recurrent function."""
    # 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)
    config.feed_forward = False

    # 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.
    p.run(eval_dummy_genomes_nn_recurrent, 19)

    stats.save()
예제 #18
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(4, eval_dummy_genome_nn)
    p.run(pe.evaluate, 19)

    stats.save()
예제 #19
0
def test_serial4_bad():
    """Make sure no_fitness_termination and n=None give an error."""
    # Load configuration.
    local_dir = os.path.dirname(__file__)
    config_path = os.path.join(local_dir, 'test_configuration4')
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_path)

    if VERBOSE:
        print("config.genome_config.__dict__: {!r}".format(
            config.genome_config.__dict__))

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

    try:
        p.run(eval_dummy_genomes_nn, None)
    except RuntimeError:
        pass
    else:
        raise Exception(
            "Should have had a RuntimeError with n=None and no_fitness_termination")
예제 #20
0
def run():
    # Load configuration.
    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)
    
    # 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, 400)
    print('\nBest genome:\n{!s}'.format(winner)) 
    
    visualize.draw_net(config, winner, True)
    visualize.plot_stats(stats, ylog=False, view=True)
    visualize.plot_species(stats, view=True)    
    
    return winner, config
예제 #21
0
def run(config_file):
    # Load configuration.
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_file)

    with open(config_dump_filename, 'wb') as f:
        pickle.dump(config, f)

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

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

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

    with open('the_genome.dump', 'wb') as f:
        pickle.dump(winner, f)
def run(configure_pathway):
    """
    runs NEAT algorithm to train neural network for Flappy Bird
    :param configure_pathway: location
    :return: None
    """
    config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction,
                                neat.DefaultSpeciesSet, neat.DefaultStagnation,
                                configure_pathway)

    # Create population
    p = neat.Population(config)

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

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

    # Show final stats
    print('n\Best genome: \n{!s}'.format(winner))
예제 #23
0
def run():
    # Load the config file, which is assumed to live in
    # the same directory as this script.
    local_dir = os.getcwd()
    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(multiprocessing.cpu_count(), eval_genome)
    best_w = pop.run(pe.evaluate)
    winner = neat.nn.FeedForwardNetwork.create(best_w, config)

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

    print(best_w)
    def evolve(self):

        logger.info("generation,best_fitness,mean_fitness,median_fitness")

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

        pe = neat.ParallelEvaluator(self.NCPU, self.evaluate_genome)
        self.winner = pop.run(pe.evaluate, self.NGEN)
        self.model = neat.nn.FeedForwardNetwork.create(self.winner,
                                                       self.config)

        best_genomes = stats.most_fit_genomes
        fitness_mean = stats.get_fitness_mean()
        fitness_median = stats.get_fitness_median()
        for e in range(0, self.NGEN):
            logger.info("{},{},{},{}".format(e, best_genomes[e].fitness,
                                             fitness_mean[e],
                                             fitness_median[e]))

        logger.removeHandler(file_handler)
예제 #25
0
def population_loader():
    choice = (input("Do you want to load a population checkpoint (y/n) : ")).lower()
    if choice == 'n':
        print("Creating new population...//")
        time.sleep(2)
        pop = neat.Population(config)  # Use this to start afresh.
    elif choice == 'y':
        # version    = input(" -------Enter the model version     : ")
        version    = VERSION
        checkpoint = int(input(" -------Enter the checkpoint number : "))
        try:
            os.chdir(f"C:/Users/ParthikB/PycharmProjects/mario/checkpoint/v{version}")
            print(f"Loading Checkpoint {checkpoint} from model v{version} ...//")
            pop = neat.Checkpointer.restore_checkpoint(f"neat-checkpoint-{checkpoint}")
            print(f"Population at Checkpoint {checkpoint} loaded...//")
        except FileNotFoundError:
            print("Invalid Version/Checkpoint. Try again.")
            population_loader()
    else:
        print("Invalid input. Please answer in y/n.")
        population_loader()

    return pop
예제 #26
0
def run(config_file):
    """
    runs the NEAT algorithm to train a neural network to play flappy bird.

    """
    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))
예제 #27
0
def runNeat(config_file):
    # This method differs a bit from the version in the thesis. The changes run the algorithm multiple times to calculate the average generations needed for a succesful worm.

    config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction,
                                neat.DefaultSpeciesSet, neat.DefaultStagnation,
                                config_file)
    sumGen = 0
    i = 0
    while i <= 200:
        population = neat.Population(config)
        population.add_reporter(neat.StdOutReporter(True))
        stats = neat.StatisticsReporter()
        population.add_reporter(stats)
        winner = population.run(evaluatePop, 200)
        app = App("winner", winner, config, True)
        app.on_execute()
        print(population.generation)
        sumGen += population.generation
        i += 1
    print(sumGen / 100)

    app = App("winner", winner, config, True)
    app.on_execute()
예제 #28
0
def run(config_file):

    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(main, 10)
    with open("winner.pkl", "wb") as f:
        pickle.dump(winner, f)
        f.close()

    # show final stats
    print('\nBest genome:\n{!s}'.format(winner))
예제 #29
0
def run():
    # Determine path to configuration file.
    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)

    # Demonstration of saving a configuration back to a text file.
    # config.save('test_save_config.txt')

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

    winner = pop.run(eval_genomes, NUM_OF_GENERATIONS)

    # Log statistics.
    stats.save()

    # Show output of the most fit genome against a random input.
    print('\nBest genome:\n{!s}'.format(winner))
예제 #30
0
파일: main.py 프로젝트: nt314p/Mancala-neat
def run(config_file):
    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))

    global stats
    stats = neat.StatisticsReporter()
    p.add_reporter(stats)
    # p.add_reporter(neat.Checkpointer(5))

    global prevBest
    prevBest = None

    winner = p.run(eval_genomes)

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