Python neat.DefaultReproduction() Examples

The following are 30 code examples of neat.DefaultReproduction(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module neat , or try the search function .
Example #1
Source File: test_simple_run.py    From neat-python with BSD 3-Clause "New" or "Revised" License 11 votes vote down vote up
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() 
Example #2
Source File: cont_train.py    From super-mario-neat with MIT License 6 votes vote down vote up
def _run(self, config_file, n):
        config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                             neat.DefaultSpeciesSet, neat.DefaultStagnation,
                             config_file)
        # p = neat.Population(config)
        p = neat.Checkpointer.restore_checkpoint(self.file_name)
        p.add_reporter(neat.StdOutReporter(True))
        p.add_reporter(neat.Checkpointer(5))
        stats = neat.StatisticsReporter()
        p.add_reporter(stats)
        print("loaded checkpoint...")
        winner = p.run(self._eval_genomes, n)
        win = p.best_genome
        pickle.dump(winner, open('winner.pkl', 'wb'))
        pickle.dump(win, open('real_winner.pkl', 'wb'))

        visualize.draw_net(config, winner, True)
        visualize.plot_stats(stats, ylog=False, view=True)
        visualize.plot_species(stats, view=True) 
Example #3
Source File: test_simple_run.py    From neat-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_serial_bad_input():
    """Make sure get error for bad input."""
    # 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)

    try:
        p.run(eval_dummy_genomes_nn_bad, 45)
    except Exception:  # may change in nn.feed_forward code to more specific...
        pass
    else:
        raise Exception("Did not get Exception from bad input") 
Example #4
Source File: test_config.py    From neat-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_bad_config_unknown_option():
    """Check that an unknown option (at least in some sections) raises an exception."""
    local_dir = os.path.dirname(__file__)
    config_path = os.path.join(local_dir, 'bad_configuration2')
    try:
        config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                             neat.DefaultSpeciesSet, neat.DefaultStagnation,
                             config_path)
    except NameError:
        pass
    else:
        raise Exception("Did not get a NameError from an unknown configuration file option (in the 'DefaultSpeciesSet' section)")
    config3_path = os.path.join(local_dir, 'bad_configuration3')
    try:
        config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                             neat.DefaultSpeciesSet, neat.DefaultStagnation,
                             config3_path)
    except NameError:
        pass
    else:
        raise Exception("Did not get a NameError from an unknown configuration file option (in the 'NEAT' section)") 
Example #5
Source File: test_simple_run.py    From neat-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_run_iznn_bad():
    """Make sure iznn gives error on bad input."""
    # 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)

    try:
        p.run(eval_dummy_genomes_iznn_bad, 19)
    except RuntimeError:
        pass
    else:
        raise Exception("Did not get RuntimeError for bad input to iznn") 
Example #6
Source File: test_simple_run.py    From neat-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_run_ctrnn_bad():
    """Make sure ctrnn gives error on bad input."""
    # 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)

    try:
        p.run(eval_dummy_genomes_ctrnn_bad, 19)
    except RuntimeError:
        pass
    else:
        raise Exception("Did not get RuntimeError for bad input to ctrnn") 
Example #7
Source File: test_simple_run.py    From neat-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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") 
Example #8
Source File: test_population.py    From neat-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_valid_fitness_criterion(self):
        for c in ('max', 'min', 'mean'):
            # 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.fitness_criterion = c

            p = neat.Population(config)

            def eval_genomes(genomes, config):
                for genome_id, genome in genomes:
                    genome.fitness = 1.0

            p.run(eval_genomes, 10) 
Example #9
Source File: test_simple_run.py    From neat-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_serial_bad_config():
    """Test if bad_configuration1 causes a LookupError or TypeError on trying to run."""
    # Load configuration.
    local_dir = os.path.dirname(__file__)
    config_path = os.path.join(local_dir, 'bad_configuration1')
    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)

    try:
        p.run(eval_dummy_genomes_nn, 19)
    except (LookupError, TypeError):
        pass
    else:
        raise Exception(
            "Should have had a LookupError/TypeError with bad_configuration1") 
Example #10
Source File: train.py    From super-mario-neat with MIT License 6 votes vote down vote up
def _run(self, config_file, n):
        config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                             neat.DefaultSpeciesSet, neat.DefaultStagnation,
                             config_file)
        p = neat.Population(config)
        p.add_reporter(neat.StdOutReporter(True))
        p.add_reporter(neat.Checkpointer(5))
        stats = neat.StatisticsReporter()
        p.add_reporter(stats)
        print("loaded checkpoint...")
        winner = p.run(self._eval_genomes, n)
        win = p.best_genome
        pickle.dump(winner, open('winner.pkl', 'wb'))
        pickle.dump(win, open('real_winner.pkl', 'wb'))

        visualize.draw_net(config, winner, True)
        visualize.plot_stats(stats, ylog=False, view=True)
        visualize.plot_species(stats, view=True) 
Example #11
Source File: trainer.py    From go_dino with GNU General Public License v3.0 6 votes vote down vote up
def main():
    local_dir = os.path.dirname(__file__)
    config = Config(neat.DefaultGenome, neat.DefaultReproduction,
                    neat.DefaultSpeciesSet, neat.DefaultStagnation,
                    os.path.join(local_dir, 'train_config.txt'))
    config.save_best = True
    config.checkpoint_time_interval = 3

    pop = population.Population(config)
    stats = neat.StatisticsReporter()
    pop.add_reporter(stats)
    pop.add_reporter(neat.StdOutReporter(True))
    pop.add_reporter(neat.StatisticsReporter())
    pop.add_reporter(neat.Checkpointer(2))
    winner = pop.run(eval_fitness, 100)
    with open('winner.pkl', 'wb') as f:
        pickle.dump(winner, f) 
Example #12
Source File: test_simple_run.py    From neat-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_serial_extinction_exception():
    """Test for complete extinction with exception."""
    # 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.stagnation_config.max_stagnation = 1
    config.stagnation_config.species_elitism = 0

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

    try:
        # Run for up to 45 generations.
        p.run(eval_dummy_genomes_nn, 45)
    except Exception:
        pass
    else:
        raise Exception("Should have had a complete extinction at some point!") 
Example #13
Source File: run_cartpole.py    From Evolutionary-Algorithm with MIT License 6 votes vote down vote up
def run():
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation, CONFIG)
    pop = neat.Population(config)

    # recode history
    stats = neat.StatisticsReporter()
    pop.add_reporter(stats)
    pop.add_reporter(neat.StdOutReporter(True))
    pop.add_reporter(neat.Checkpointer(5))

    pop.run(eval_genomes, 10)       # train 10 generations

    # visualize training
    visualize.plot_stats(stats, ylog=False, view=True)
    visualize.plot_species(stats, view=True) 
Example #14
Source File: test_simple_run.py    From neat-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_threaded_evaluation():
    """Tests a neat evolution using neat.threaded.ThreadedEvaluator"""
    # 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(1, 5))

    # Run for up to 19 generations.
    pe = neat.ThreadedEvaluator(4, eval_dummy_genome_nn)
    p.run(pe.evaluate, 19)

    stats.save() 
Example #15
Source File: test_simple_run.py    From neat-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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() 
Example #16
Source File: test_activation.py    From neat-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_bad_add1():
    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)

    try:
        config.genome_config.add_activation('1.0', 1.0)
    except TypeError:
        pass
    else:
        raise Exception("Should have had a TypeError/derived for 'function' 1.0") 
Example #17
Source File: test_simple_run.py    From neat-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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) 
Example #18
Source File: test_simple_run.py    From neat-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_run_ctrnn():
    """Basic test of continuous-time recurrent neural network (ctrnn)."""
    # 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_ctrnn, 19)

    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 1 <= len(genomes) <= 5, "Genomes: {!r}".format(genomes)
    stats.best_genome()

    p.remove_reporter(stats) 
Example #19
Source File: test_distributed.py    From neat-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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() 
Example #20
Source File: test_activation.py    From neat-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_add_plus():
    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.genome_config.add_activation('plus', plus_activation)
    assert config.genome_config.activation_defs.get('plus') is not None
    assert config.genome_config.activation_defs.is_valid('plus') 
Example #21
Source File: neat_es.py    From DistributedES with Apache License 2.0 5 votes vote down vote up
def load_neat_config(self):
        local_dir = os.path.dirname(__file__)
        config_path = os.path.join(local_dir, 'neat-config/%s.txt' % self.config.task)
        neat_config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                             neat.DefaultSpeciesSet, neat.DefaultStagnation,
                             config_path)
        neat_config.fitness_threshold = self.config.target
        return neat_config 
Example #22
Source File: test_activation.py    From neat-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_bad_add2():
    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)

    try:
        config.genome_config.add_activation('dud_function', dud_function)
    except TypeError:
        pass
    else:
        raise Exception("Should have had a TypeError/derived for dud_function") 
Example #23
Source File: test_config_save_restore.py    From neat-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_config_save_restore(self):
        """Check if it is possible to restore saved config"""

        config_filename_initial = 'test_configuration'
        config_filename_save = 'save_configuration'

        # Get config path
        local_dir = os.path.dirname(__file__)
        config_path_initial = os.path.join(local_dir, config_filename_initial)
        config_path_save = os.path.join(local_dir, config_filename_save)

        # Load initial configuration from file
        config_initial = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                                     neat.DefaultSpeciesSet, neat.DefaultStagnation, config_path_initial)

        config1 = config_initial.genome_config
        names1 = [p.name for p in config1._params]
        for n in names1:
            assert hasattr(config1, n)

        # Save configuration to another file
        config_initial.save(config_path_save)

        # Obtain configuration from saved file
        config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                             neat.DefaultSpeciesSet, neat.DefaultStagnation, config_path_save)

        config2 = config.genome_config
        names2 = [p.name for p in config2._params]
        for n in names2:
            assert hasattr(config2, n)

        self.assertEqual(names1, names2)

        for n in names1:
            v1 = getattr(config1, n)
            v2 = getattr(config2, n)
            self.assertEqual(v1, v2) 
Example #24
Source File: test_config_save_restore.py    From neat-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_config_save_restore1(self):
        """Check if it is possible to restore saved config2"""

        config_filename_initial = 'test_configuration2'
        config_filename_save = 'save_configuration2'

        # Get config path
        local_dir = os.path.dirname(__file__)
        config_path_initial = os.path.join(local_dir, config_filename_initial)
        config_path_save = os.path.join(local_dir, config_filename_save)

        # Load initial configuration from file
        config_initial = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                                     neat.DefaultSpeciesSet, neat.DefaultStagnation, config_path_initial)

        config1 = config_initial.genome_config
        names1 = [p.name for p in config1._params]
        for n in names1:
            assert hasattr(config1, n)

        # Save configuration to another file
        config_initial.save(config_path_save)

        # Obtain configuration from saved file
        config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                             neat.DefaultSpeciesSet, neat.DefaultStagnation, config_path_save)

        config2 = config.genome_config
        names2 = [p.name for p in config2._params]
        for n in names2:
            assert hasattr(config2, n)

        self.assertEqual(names1, names2)

        for n in names1:
            v1 = getattr(config1, n)
            v2 = getattr(config2, n)
            self.assertEqual(v1, v2) 
Example #25
Source File: run.py    From super-mario-neat with MIT License 5 votes vote down vote up
def main(config_file, file, level="1-1"):
    # with gzip.open(FILENAME) as f:
    #   config = pickle.load(f)[1]
    # print(str(config.genome_type.size))
    config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_file)
    genome = pickle.load(open(file, 'rb'))
    env = gym.make('ppaquette/SuperMarioBros-'+level+'-Tiles-v0')
    net = neat.nn.FeedForwardNetwork.create(genome, config)
    info = {'distance': 0}
    try:
        while info['distance'] != 3252:
            state = env.reset()
            done = False
            i = 0
            old = 40
            while not done:
                state = state.reshape(208)
                output = net.activate(state)
                ind = output.index(max(output))
                s, reward, done, info = env.step(ACTIONS[ind])
                state = s
                i += 1
                if i % 50 == 0:
                    if old == info['distance']:
                        break

                    else:
                        old = info['distance']
            print("Distance: {}".format(info['distance']))
        env.close()
    except KeyboardInterrupt:
        env.close()
        exit() 
Example #26
Source File: play_winner.py    From go_dino with GNU General Public License v3.0 5 votes vote down vote up
def main():
    local_dir = os.path.dirname(__file__)
    config = Config(neat.DefaultGenome, neat.DefaultReproduction,
                    neat.DefaultSpeciesSet, neat.DefaultStagnation,
                    os.path.join(local_dir, 'train_config.txt'))
    with open('winner.pkl', 'rb') as f:
        winner = pickle.load(f)
    print('\nBest genome:\n{!s}'.format(winner))
    print('\nOutput:')
    winner_net = neat.nn.FeedForwardNetwork.create(winner, config)
    print('Score:', dino_api.play_game(GetCommand(winner_net))) 
Example #27
Source File: run_xor.py    From Evolutionary-Algorithm with MIT License 5 votes vote down vote up
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))

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

    p = neat.Checkpointer.restore_checkpoint('neat-checkpoint-49')
    p.run(eval_genomes, 10) 
Example #28
Source File: main.py    From TensorFlow-NEAT with Apache License 2.0 5 votes vote down vote up
def run(n_generations):
    # 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,
    )

    evaluator = MultiEnvEvaluator(
        make_net, activate_net, 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)

    pop = neat.Population(config)
    stats = neat.StatisticsReporter()
    pop.add_reporter(stats)
    reporter = neat.StdOutReporter(True)
    pop.add_reporter(reporter)
    logger = LogReporter("./logs/neat.json", evaluator.eval_genome)
    pop.add_reporter(logger)

    pop.run(eval_genomes, n_generations) 
Example #29
Source File: main.py    From PyTorch-NEAT with Apache License 2.0 5 votes vote down vote up
def run(n_generations):
    # 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,
    )

    evaluator = MultiEnvEvaluator(
        make_net, activate_net, 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)

    pop = neat.Population(config)
    stats = neat.StatisticsReporter()
    pop.add_reporter(stats)
    reporter = neat.StdOutReporter(True)
    pop.add_reporter(reporter)
    logger = LogReporter("neat.log", evaluator.eval_genome)
    pop.add_reporter(logger)

    pop.run(eval_genomes, n_generations) 
Example #30
Source File: cppn.py    From poet with Apache License 2.0 5 votes vote down vote up
def __init__(self, cppn_config_path='config-cppn', genome_path=None):
        self.cppn_config_path = os.path.dirname(__file__) + '/' + cppn_config_path
        self.genome_path = genome_path
        self.hardcore = False
        self.cppn_config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, self.cppn_config_path)
        self.cppn_genome = None
        self.altitude_fn = lambda x: x
        if genome_path is not None:
            self.cppn_genome = pickle.load(open(genome_path, 'rb'))
        else:
            start_cppn_genome = PrettyGenome('0')
            start_cppn_genome.configure_new(self.cppn_config.genome_config)
            start_cppn_genome.nodes[0].activation = 'identity'
            self.cppn_genome = start_cppn_genome
        self.reset_altitude_fn()