def run():
    local_dir = os.path.dirname(__file__)
    pop = population.Population(os.path.join(local_dir, 'nn_config'))
    pe = parallel.ParallelEvaluator(4, eval_fitness)
    pop.run(pe.evaluate, 1000)

    print('Number of evaluations: {0}'.format(pop.total_evaluations))

    # Display the most fit genome.
    print('\nBest genome:')
    winner = pop.statistics.best_genome()
    print(winner)

    # Verify network output against a few randomly-generated sequences.
    winner_net = nn.create_recurrent_phenotype(winner)
    for n in range(4):
        print('\nRun {0} output:'.format(n))
        seq = [random.choice((0, 1)) for _ in range(N)]
        winner_net.reset()
        for s in seq:
            winner_net.activate([s, 0])

        for s in seq:
            output = winner_net.activate([0, 1])
            print("expected {0:1.5f} got {1:1.5f}".format(s, output[0]))

    # Visualize the winner network and plot/log statistics.
    visualize.draw_net(winner, view=True, filename="nn_winner.gv")
    visualize.draw_net(winner, view=True, filename="nn_winner-enabled.gv", show_disabled=False)
    visualize.draw_net(winner, view=True, filename="nn_winner-enabled-pruned.gv", show_disabled=False, prune_unused=True)
    visualize.plot_stats(pop.statistics)
    visualize.plot_species(pop.statistics)
    statistics.save_stats(pop.statistics)
    statistics.save_species_count(pop.statistics)
    statistics.save_species_fitness(pop.statistics)
Exemple #2
0
def run():
    local_dir = os.path.dirname(__file__)
    pop = population.Population(os.path.join(local_dir, 'nn_config'))
    pe = parallel.ParallelEvaluator(4, eval_fitness)
    pop.run(pe.evaluate, 1000)

    print('Number of evaluations: {0}'.format(pop.total_evaluations))

    # Display the most fit genome.
    print('\nBest genome:')
    winner = pop.statistics.best_genome()
    print(winner)

    # Verify network output against a few randomly-generated sequences.
    winner_net = nn.create_recurrent_phenotype(winner)
    for n in range(4):
        print('\nRun {0} output:'.format(n))
        seq = [random.choice((0, 1)) for _ in range(N)]
        winner_net.reset()
        for s in seq:
            winner_net.activate([s, 0])

        for s in seq:
            output = winner_net.activate([0, 1])
            print("expected {0:1.5f} got {1:1.5f}".format(s, output[0]))

    # Visualize the winner network and plot/log statistics.
    visualize.draw_net(winner, view=True, filename="nn_winner.gv")
    visualize.draw_net(winner, view=True, filename="nn_winner-enabled.gv", show_disabled=False)
    visualize.draw_net(winner, view=True, filename="nn_winner-enabled-pruned.gv", show_disabled=False, prune_unused=True)
    visualize.plot_stats(pop.statistics)
    visualize.plot_species(pop.statistics)
    statistics.save_stats(pop.statistics)
    statistics.save_species_count(pop.statistics)
    statistics.save_species_fitness(pop.statistics)
Exemple #3
0
def run():
    local_dir = os.path.dirname(__file__)
    pop = population.Population(os.path.join(local_dir, 'nn_config'))
    pe = parallel.ParallelEvaluator(4, eval_fitness)
    pop.run(pe.evaluate, 1000)

    # Log statistics.
    statistics.save_stats(pop.statistics)
    statistics.save_species_count(pop.statistics)
    statistics.save_species_fitness(pop.statistics)

    print('Number of evaluations: {0}'.format(pop.total_evaluations))

    # Show output of the most fit genome against a random input.
    winner = pop.statistics.best_genome()
    print('\nBest genome:\n{!s}'.format(winner))
    print('\nOutput:')
    winner_net = nn.create_recurrent_phenotype(winner)
    for n in range(4):
        print('\nRun {0} output:'.format(n))
        seq = [random.choice((0, 1)) for _ in range(N)]
        winner_net.reset()
        for s in seq:
            winner_net.activate([s, 0])

        for s in seq:
            output = winner_net.activate([0, 1])
            print("expected {0:1.5f} got {1:1.5f}".format(s, output[0]))
def run():
    local_dir = os.path.dirname(__file__)
    pop = population.Population(os.path.join(local_dir, "nn_config"))
    pe = parallel.ParallelEvaluator(4, eval_fitness)
    pop.run(pe.evaluate, 1000)

    # Log statistics.
    statistics.save_stats(pop.statistics)
    statistics.save_species_count(pop.statistics)
    statistics.save_species_fitness(pop.statistics)

    print("Number of evaluations: {0}".format(pop.total_evaluations))

    # Show output of the most fit genome against a random input.
    winner = pop.statistics.best_genome()
    print("\nBest genome:\n{!s}".format(winner))
    print("\nOutput:")
    winner_net = nn.create_recurrent_phenotype(winner)
    for n in range(4):
        print("\nRun {0} output:".format(n))
        seq = [random.choice((0, 1)) for _ in range(N)]
        winner_net.reset()
        for s in seq:
            winner_net.activate([s, 0])

        for s in seq:
            output = winner_net.activate([0, 1])
            print("expected {0:1.5f} got {1:1.5f}".format(s, output[0]))
def eval_fitness_single(genomes):
    #multiple fights make for better statistics
    num_runs = 1
    for g in genomes:
        net = nn.create_recurrent_phenotype(g)
        achi = 0
        for _ in range(num_runs):
            mooreNeighborhood = ca.Neighborhood(gocl.initNeighborhood)
            gameOfLife = ca.CellularAutomaton(mooreNeighborhood)
            gameOfLife.parameters = gameOfLife.world['parameters']
            newSpecies(gameOfLife, {
                'species': 'test',
                'color': 'Blue',
                'position': {
                    'x': 0,
                    'y': 0
                }
            })
            currentDecision = partial(netDecision, net=net)
            evolve = gameOfLife.evolve
            c = 0
            while c < 20:
                dec = {}
                recursionDecision(gameOfLife.world['space'], dec,
                                  currentDecision)
                gameOfLife.decisions = dec
                evolve()
                c += 1
            achi += countSpecies(gameOfLife.world['space'], 'test')
        g.fitness = achi / num_runs
Exemple #6
0
 def __init__(self, cell_id, genome):
     assert (isinstance(genome, CellGenome))
     self.id = cell_id
     self.genome = genome
     self.userData = dict()
     self.alive = True
     # self.network = nn.create_feed_forward_phenotype(genome)
     self.network = nn.create_recurrent_phenotype(genome)
Exemple #7
0
def fitness(genome):
    net = nn.create_recurrent_phenotype(genome)

    with open("prova.map","rb") as f:
        map = pickle.load(f)
    program = neural_program.NeuralProgram(net)
    s = singlerun2.SingleRun(map, program)
    return s.play()
def eval_fitness_internalfight(allgenomes):
    num_runs = 2
    for g in allgenomes:
        g.fitness = 0
    #sadly, the number of genomes from neat-python is not fixed, so we only train some to fit %4
    genomes = allgenomes[:int(len(allgenomes) / 4) * 4]
    print(len(allgenomes), len(genomes))
    for _ in range(num_runs):
        #geht nur, wenn genomes durch 4 teilbar ist
        grouping = np.reshape(np.random.permutation(len(genomes)),
                              (len(genomes) / 4, 4))
        for group in grouping:
            nets = []
            mooreNeighborhood = ca.Neighborhood(gocl.initNeighborhood)
            gameOfLife = ca.CellularAutomaton(mooreNeighborhood)
            gameOfLife.parameters = gameOfLife.world['parameters']
            for i, g in enumerate(group):
                nets.append(nn.create_recurrent_phenotype(genomes[g]))
                newSpecies(
                    gameOfLife, {
                        'species': i,
                        'color': i,
                        'position': {
                            'x': int(i % 2) * 5,
                            'y': int((i / 2) % 2) * 5
                        }
                    })
            evolve = gameOfLife.evolve
            c = 0
            #length of the game
            while c < 30:
                gameOfLife.decisions = {}
                for i, g in enumerate(group):
                    dec = {}
                    currentDecision = partial(netDecision, net=nets[i])
                    recursionDecision(gameOfLife.world['space'], dec,
                                      currentDecision)
                    #if a species died there might be an error
                    try:
                        gameOfLife.decisions[i] = dec[i]
                    except:
                        pass
                evolve()
                c += 1
            for i, g in enumerate(group):
                genomes[g].fitness += countSpecies(gameOfLife.world['space'],
                                                   i)
    #results of fights define the fitness
    for g in genomes:
        g.fitness = g.fitness / num_runs
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--input", default="res_0.net", help="Il file con la rete da aprire")
    parser.add_argument("-m", "--map", default="prova.map", help="La mappa da usare")
    args = parser.parse_args()

    with open(args.input, "rb") as f:
        genome = pickle.load(f)

    with open(args.map, "rb") as f:
        map = pickle.load(f)
    net = nn.create_recurrent_phenotype(genome)
    prog = neural_program_try.NeuralProgram(net)
    s = singlerun2.SingleRun(map, prog)
    print(s.play())
Exemple #10
0
def cs_fitness(genomes):
    for g in genomes:
        print(g.ID)
        fit = 0
        tot = 0.0
        net = nn.create_recurrent_phenotype(g)
        with open("match_prepared.dat", 'r') as f, open("match_out_prepared.dat", 'r') as f2:
            for line_tr, line_te in itertools.izip(f, f2):
                if tot > 14000:
                    break
                res = int(net.activate([float(num) for num in line_tr.strip().split()])[0])
                if res == int(line_te.strip()):
                    fit += 1
                tot += 1
        g.fitness = fit/tot
        print "Correct guesses {0}, in total of {1} matches.\n".format(str(fit), str(tot))
def eval_fitness(g):
    net = nn.create_recurrent_phenotype(g)

    error = 0.0
    for _ in range(num_tests):
        # Create a random sequence, and feed it to the network with the
        # second input set to zero.
        seq = [random.choice((0, 1)) for _ in range(N)]
        net.reset()
        for s in seq:
            inputs = [s, 0]
            net.activate(inputs)

        # Set the second input to one, and get the network output.
        for s in seq:
            inputs = [0, 1]
            output = net.activate(inputs)

            error += (output[0] - s) ** 2

    return -(error / (N * num_tests)) ** 0.5
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-i",
                        "--input",
                        default="res_0.net",
                        help="Il file con la rete da aprire")
    parser.add_argument("-m",
                        "--map",
                        default="prova.map",
                        help="La mappa da usare")
    args = parser.parse_args()

    with open(args.input, "rb") as f:
        genome = pickle.load(f)

    with open(args.map, "rb") as f:
        map = pickle.load(f)
    net = nn.create_recurrent_phenotype(genome)
    prog = neural_program_try.NeuralProgram(net)
    s = singlerun2.SingleRun(map, prog)
    print(s.play())
Exemple #13
0
def eval_fitness(g):
    net = nn.create_recurrent_phenotype(g)

    error = 0.0
    for _ in range(num_tests):
        # Create a random sequence, and feed it to the network with the
        # second input set to zero.
        seq = [random.choice((0, 1)) for _ in range(N)]
        net.reset()
        for s in seq:
            inputs = [s, 0]
            net.activate(inputs)

        # Set the second input to one, and get the network output.
        for s in seq:
            inputs = [0, 1]
            output = net.activate(inputs)

            error += (output[0] - s) ** 2

    return -(error / (N * num_tests)) ** 0.5
def main():
    print("Starting...")
    pop = population.Population(
        os.path.join(os.path.dirname(__file__), 'nn_config'))
    #HINT change checkpoints for new try or reloading
    pop.load_checkpoint(
        os.path.join(os.path.dirname(__file__), 'checkpoints/popv1.cpt'))
    pop.run(eval_fitness_internalfight, 5)
    pop.save_checkpoint(
        os.path.join(os.path.dirname(__file__), 'checkpoints/popv1.cpt'))

    statistics.save_stats(pop.statistics)
    statistics.save_species_count(pop.statistics)
    statistics.save_species_fitness(pop.statistics)

    winner = pop.statistics.best_genome()
    print('\nBest genome:\n{!s}'.format(winner))
    print('\nOutput:')
    winner_net = nn.create_recurrent_phenotype(winner)
    mooreNeighborhood = ca.Neighborhood(gocl.initNeighborhood)
    gameOfLife = ca.CellularAutomaton(mooreNeighborhood)
    gameOfLife.parameters = gameOfLife.world['parameters']
    newSpecies(gameOfLife, {
        'species': 'test',
        'color': 'Blue',
        'position': {
            'x': 0,
            'y': 0
        }
    })
    currentDecision = partial(netDecision, net=winner_net)
    evolve = gameOfLife.evolve
    c = 0
    while c < 20:
        dec = {}
        recursionDecision(gameOfLife.world['space'], dec, currentDecision)
        gameOfLife.decisions = dec
        evolve()
        c += 1
    print("Ended with: ", countSpecies(gameOfLife.world['space'], 'test'))
Exemple #15
0
#     (MorphogenModule, {'start_genes': 1, 'min_genes': 0})
# (Signal3Module, {'prob_add': .0, 'prob_remove': .0,
#                  'min_genes': 0, 'start_genes': 3, 'max_genes': 6 }),

# (neighbors_continuous.NeighborModule, {}),
# (divide_theta.DivideThetaModule, {}),

# (neighbors_distinct.NeighborModule, {}),
# (divide_distinct.DivideDistinctModule, {})
# ]

LOCAL_DIR = os.path.dirname(__file__)
CONFIG = Config(os.path.join(LOCAL_DIR, 'experiments/shape_config.txt'))
CONFIG.genome_config = genome_config
DUMMY_GENOME = CellGenome.create_unconnected(1, CONFIG)
network = nn.create_recurrent_phenotype(DUMMY_GENOME)


class Sandbox(Simulation):
    """ Extend the simualtion to inject arbitrary cell behavior. """
    def __init__(self):
        super(Sandbox, self).__init__(DUMMY_GENOME)

        for row in range(1, self.bounds[0]):
            self.create_cell((row, 0))

        for row in range(self.bounds[0] - 1):
            self.create_cell((row, 1))

        for col in range(1, self.bounds[1]):
            self.create_cell((5, col))