Пример #1
0
Файл: egt.py Проект: peihy/PyEGT
def cora():
    G = nx.barabasi_albert_graph(1000, 3)
    # G = nx.watts_strogatz_graph(1000, 5, 0.3)
    # G = nx.random_regular_graph(4, 1000)
    p = Population(G)
    e = Evolution()
    g = game.PDG(2)
    e.set_population(p).set_game(g)
    # p.strategy = np.ones(len(p), np.int)
    f, axs = plt.subplots(3, 4)
    axs = axs.reshape(12)
    for r in range(11):
        if r > 5:
            r_ = 10 - r
            p.strategy = np.zeros(len(p), dtype=np.int)
            s = 1
        else:
            r_ = r
            p.strategy = np.ones(len(p), dtype=np.int)
            s = 0
        n = int(round(len(p) / 10.0 * r_))
        selected_list = np.random.choice(range(len(p)), n)
        p.strategy[selected_list] = s
        # print p.strategy
        g.strategy = p.strategy
        g.play()
        p.show_degree(axs[r])
    plt.show()
Пример #2
0
    def __init__(self, dim, renderer, animation):
        self.dim = dim
        self.renderer = renderer
        self.animation = animation
        self.evolution = Evolution()
        self.grid = [[None for y in range(dim)] for x in range(dim)]
        for i in range(dim):
            for j in range(dim):
                self.grid[i][j] = Cell(i, j)

        for i in range(dim):
            for j in range(dim):
                cell = self.grid[i][j]

                cell.addNeighbor(self.grid[i - 1][j] if i - 1 >= 0 else None)
                cell.addNeighbor(self.grid[i + 1][j] if i + 1 < dim else None)
                cell.addNeighbor(self.grid[i][j - 1] if j - 1 >= 0 else None)
                cell.addNeighbor(self.grid[i][j + 1] if j + 1 < dim else None)
                cell.addNeighbor(self.grid[i - 1][j - 1] if i - 1 >= 0 and j -
                                 1 >= 0 else None)
                cell.addNeighbor(self.grid[i - 1][j + 1] if i - 1 >= 0 and j +
                                 1 < dim else None)
                cell.addNeighbor(self.grid[i + 1][j - 1] if i + 1 < dim and j -
                                 1 >= 0 else None)
                cell.addNeighbor(self.grid[i + 1][j + 1] if i + 1 < dim and j +
                                 1 < dim else None)
Пример #3
0
    def darwinLoop(self, maxLoops, parentCount=4, parentKept=2):
        ### Loop on world, evaluate n parents, keep only m best ones and replace others by evolution from kept best ones
        j = 0
        print "darwin loop started"
        while (j < maxLoops):
            print "--- Darwin in the while loop " + str(j)
            ### Store best Move and distance
            bestDistance = 0
            bestMove = 0

            evalMovesIndexes = random.sample(range(0, len(self.world)),
                                             parentCount)
            print "evalMoves="
            print evalMovesIndexes
            print "darwin after evalmoves"

            for i in evalMovesIndexes:
                print "darwin in the for loop"
                print self.world
                print self.world[str(i)]
                if (self.world[str(i)]._distance is None):
                    self.world[str(i)]._distance = self.executor.run(
                        self.world[str(i)])
                print "Executor done"
            # sort evalMoves
            print "evalMovesSorted="
            evalMovesSorted = sorted(
                evalMovesIndexes, key=lambda i: self.world[str(i)]._distance)
            print evalMovesSorted

            #keep 2 bests (2 last)
            # We dont need to do anything to keep them...

            # replace 2 worsts by children of 2 best ==> Verify the content of simpleCrossover execution
            e = Evolution()
            print("CrossingOver : last and last-1")
            pprint.pprint(str(self.world[str(evalMovesSorted[-1])]))
            pprint.pprint(str(self.world[str(evalMovesSorted[-2])]))
            print("CrossOver result : ")
            (A, B) = e.simpleCrossover(self.world[str(evalMovesSorted[-1])],
                                       self.world[str(evalMovesSorted[-2])])

            # Uncomment to use mutation (NOT TESTED YET)
            # A = mutation(0.05, 10, A)
            # B = mutation(0.05, 10, B)

            self.world[str(evalMovesSorted[0])] = A
            self.world[str(evalMovesSorted[1])] = B

            pprint.pprint(str(self.world[str(evalMovesSorted[0])]))
            pprint.pprint(str(self.world[str(evalMovesSorted[1])]))

            j += 1
Пример #4
0
def solve(problem, save=False, img_prefix=""):
    bests = []
    evolution = Evolution(
        generate_population(len(problem.world), problem.population),
        makefitness(problem.U, problem.T, problem.world),
        selection,
        crossover,
        mutation_simple,
        keep=min
    )
    before = evolution.stats()
    first = evolution.best(min)
    for i in range(problem.iterations):
        print(i)
        evolution.advance()
        bests.append(min(evolution.scores))

    after = evolution.stats()

    if(save):
        # representation.save_chart('results/' + img_prefix + 'chart.png', bests, problem.iterations)
        # representation.save_graph('results/' + img_prefix + 'first.png', problem, first)
        representation.save_graph('results2/' + img_prefix + '.png', problem, evolution.best(min))
    else:
        write_results(problem, before, after)
Пример #5
0
Файл: egt.py Проект: peihy/PyEGT
def lattice():
    l = 100

    def observe(s, f):
        plt.imshow(s.reshape((l, l)), interpolation='sinc', cmap='bwr')
        plt.show()

    G = nx.grid_2d_graph(l, l)
    # nx.draw(G, node_size=200, with_labels=True)
    # plt.show()
    p = Population(G)
    e = Evolution()
    e.set_population(p).set_game(g).set_rule(u)
    # e.evolve(1)
    observe(p.strategy, p.fitness)
Пример #6
0
    def __init__(self, races, statistics=None):
        self._creature_counter = 0
        self._races = races
        self._space = Space(ConfigPhysics.SPACE_SIZE)
        self._time = 0
        self.statistics = statistics
        for race in races:
            num_fathers = ConfigPhysics.NUM_FATHERS

            fathers_locations_i = np.random.choice(ConfigPhysics.SPACE_SIZE,
                                                   num_fathers)
            fathers_locations_j = np.random.choice(ConfigPhysics.SPACE_SIZE,
                                                   num_fathers)
            ages = np.random.randint(low=0,
                                     high=ConfigBiology.BASE_LIFE_EXPECTANCY,
                                     size=num_fathers)
            for n in range(num_fathers):
                dna = Evolution.mutate_dna(race.race_basic_dna())

                self.create_creature(race,
                                     id=self.allocate_id(),
                                     dna=dna,
                                     coord=(fathers_locations_i[n],
                                            fathers_locations_j[n]),
                                     age=ages[n],
                                     parents=None)

        self.give_food(ConfigPhysics.INITIAL_FOOD_AMOUNT)
Пример #7
0
 def next_generation(self):
     self.current_id = 0
     self.avg_fitness = 0
     if self.create:
         brains = [snake.brain for snake in self.snakes.values()]
         generation = Evolution(brains, self.selection, self.crossover,
                                self.mutation, self.seed, self.generation)
         brains = generation.evolve()
         self.snakes = dict()
         for snk_id in range(self.population):
             snake = Snake(snk_id, self.initial_pos, brains[snk_id])
             self.snakes[snk_id] = snake
     else:
         for snk_id in range(self.population):
             snake = Snake.load(self.generation, snk_id)
             self.snakes[snk_id] = snake
     self.reset_game()
Пример #8
0
def run_deap(X, y):
    popsize = 500
    mutRate = 0.4
    crRate = 0.6
    GenMax = 250

    # concatenate selected features with their target values
    dataset = np.column_stack((X, y))
    evo = Evolution(
        dataset=dataset.tolist(),  # data samples 
        popsize=popsize,  # initial population size
        hofsize=25,  # the number of best individual to track
        cx=crRate,  # crossover rate
        mut=mutRate,  # mutation rate
        maxgen=GenMax,  # max number of generations
    )

    pop, logbook, hof = evo.run(verbose=1)

    return evo, pop, logbook, hof
Пример #9
0
Файл: egt.py Проект: peihy/PyEGT
def repeat_b():
    # 博弈收益参数不同,合作率曲线
    e = Evolution(has_mut=False)
    G = nx.random_regular_graph(4, 1000)
    p = Population(G)
    b = 5
    for i in range(b):
        g = game.PDG(i * 2 + 2)
        e.set_population(p).set_game(g).set_rule(u)
        print('Control Variable b: %d' % (i * 2 + 2))
        e.evolve(100000, restart=True, quiet=True, autostop=False)
        e.show(fmt[i], label="b=%d" % (i * 2 + 2))
    plt.legend(loc='lower right')
    plt.show()
Пример #10
0
class Grid:
    def __init__(self, dim, renderer, animation):
        self.dim = dim
        self.renderer = renderer
        self.animation = animation
        self.evolution = Evolution()
        self.grid = [[None for y in range(dim)] for x in range(dim)]
        for i in range(dim):
            for j in range(dim):
                self.grid[i][j] = Cell(i, j)

        for i in range(dim):
            for j in range(dim):
                cell = self.grid[i][j]

                cell.addNeighbor(self.grid[i - 1][j] if i - 1 >= 0 else None)
                cell.addNeighbor(self.grid[i + 1][j] if i + 1 < dim else None)
                cell.addNeighbor(self.grid[i][j - 1] if j - 1 >= 0 else None)
                cell.addNeighbor(self.grid[i][j + 1] if j + 1 < dim else None)
                cell.addNeighbor(self.grid[i - 1][j - 1] if i - 1 >= 0 and j -
                                 1 >= 0 else None)
                cell.addNeighbor(self.grid[i - 1][j + 1] if i - 1 >= 0 and j +
                                 1 < dim else None)
                cell.addNeighbor(self.grid[i + 1][j - 1] if i + 1 < dim and j -
                                 1 >= 0 else None)
                cell.addNeighbor(self.grid[i + 1][j + 1] if i + 1 < dim and j +
                                 1 < dim else None)

    def alive(self, i, j):
        self.grid[i][j].value = True
        return self

    def render(self):
        self.renderer.render(self)

    def animate(self):
        self.animation.animate(self)

    def next(self):
        self.evolution.next(self)
Пример #11
0
def test():
    # Initialize
    darwinian = Evolution(10, 5)

    # Evolve
    darwinian.evolve(1000)

    # Get the best agent
    best_agent = darwinian.get_best_agent()

    # Visualize the performance
    for i_episode in range(10):
        observation = darwinian.env.reset()
        for t in range(500):
            darwinian.env.render()

            action = best_agent.action(observation)
            observation, reward, done, info = darwinian.env.step(action)
            if done:
                print("Episode finished after {} timesteps".format(t + 1))
                break

    # Plot the statistics
    stats = darwinian.getStats()
    plt.plot(stats[0], stats[1])
    plt.ylabel("Best Rewarded Genome")
    plt.xlabel("Generation")
    plt.show()

    # Sleep a bit
    time.sleep(1)
    darwinian.env.close()
Пример #12
0
def _get_next_evolution(p_name, p_lvl):
    evolutions = peds.get_level_up_evolutions(p_name)
    p_name = p_name.capitalize()
    if p_lvl == 100 or len(evolutions) == 0:
        return None
    # choose to evolve or not
    if len(evolutions) == 1:
        evo_name = evolutions[0][0]
        if _get_y_or_n_input('%s can evolve into %s, do you want ' %
                             (p_name, evo_name.capitalize()) +
                             'this evolution to occur (y/n)? ') == 'y':
            next_evo = evolutions[0]
        else:
            next_evo = None
    # choose from selection of evolutions
    elif len(evolutions) > 1:
        evos = {evo[0]: evo[1] for evo in evolutions}
        print(
            '%s can evolve into one of these forms while leveling up:' %
            p_name, ', '.join(evos.keys()))
        next_evo_name = _get_choice_from_options(
            'Which form should %s evolve into (or "none")? ' % p_name,
            list(evos.keys()) + ['none'])
        next_evo = ((next_evo_name,
                     evos[next_evo_name]) if next_evo_name != 'none' else None)
    # get desired level for evolution
    if next_evo is None:
        return None
    next_evo_name, next_evo_conditions = next_evo
    # if level is specified
    if 'min_level' in next_evo_conditions:
        evo_level = max(next_evo_conditions['min_level'], p_lvl + 1)
        print('The earliest level that this evolution can ' +
              'occur at is %i' % evo_level)
        if _get_y_or_n_input('Do you want %s ' % p_name +
                             'to evolve at this level (y/n)? ') == 'n':
            evo_level = _get_level_input('Which level should ' +
                                         '%s evolve at? ' % p_name,
                                         min_lvl=evo_level)
    # level not specified - happiness? time of day?
    else:
        print('A minimum level for this evolution is not specified. ' +
              'It is instead determined by special conditions')
        evo_level = _get_level_input('Which level should ' +
                                     '%s evolve at? ' % p_name,
                                     min_lvl=p_lvl + 1)
    return Evolution(p_name.lower(), next_evo_name, evo_level,
                     next_evo_conditions)
Пример #13
0
    def creature_divide(self, creature):
        if creature.age() < ConfigBiology.MATURITY_AGE:
            if creature.energy() < ConfigBiology.MOVE_ENERGY:
                self.kill_creature(creature)
                return
            creature.reduce_energy(ConfigBiology.MOVE_ENERGY)
            return

        self.create_creature(creature.get_race(),
                             self.allocate_id(),
                             dna=Evolution.mutate_dna(creature.dna()),
                             coord=creature.coord(),
                             energy=int(creature.energy() / 2) + 1,
                             parents=[creature])
        creature.reduce_energy(amount=int(creature.energy() / 2))
        creature._age = 1
Пример #14
0
Файл: egt.py Проект: peihy/PyEGT
def repeat_k():
    # 网络平均度不同,合作率曲线
    e = Evolution(has_mut=False)
    k = 5
    a = [0] * k
    for i in range(k):
        G = nx.random_regular_graph(i * 2 + 2, 1000)
        p = Population(G)
        e.set_population(p).set_game(g).set_rule(u)
        print('Control Variable k: %d' % (i * 2 + 2))
        e.evolve(100000, restart=True, quiet=True)
        # TODO: if e is CoEvolution, population need re-copy
        # a[i] = e.cooperate[-1]
        e.show(fmt[i], label="k=%d" % (i * 2 + 2))
    # plt.plot(range(2, k+1), a[1:], 'r-')
    # plt.plot([400+i*i for i in range(20)], 'ro--', label='k=4')
    # plt.plot([400 + i for i in range(20)], 'g^-.', label='k=6')
    # plt.plot([400 - i for i in range(20)], 'cx:', label='k=8')
    plt.legend(loc='lower right')
    plt.show()
Пример #15
0
Файл: egt.py Проект: peihy/PyEGT
def repeat_start_pc():
    # 初始Pc不同的合作变化曲线
    # G = nx.watts_strogatz_graph(1000, 4, 0.2)
    G = nx.barabasi_albert_graph(1000, 3)
    p = Population(G)
    g = game.PDG(b=10)
    u = rule.DeathBirth()
    e = Evolution(has_mut=False)
    e.set_population(p).set_game(g).set_rule(u)
    for i in range(5):
        pc = (2 * i + 1) / 10.0
        p.init_strategies(g, [pc, 1 - pc])
        print('Initial P(C) is %.2f' % pc)
        e.evolve(100000, restart=True, quiet=True, autostop=False)
        e.show(fmt[i], label=r'start $P_C$=%.2f' % pc)
    plt.legend(loc='lower right')
    plt.title(r'Evolution under Different Start $P_C$')
    plt.xlabel('Number of generations')
    plt.ylabel(r'Fraction of cooperations, $\rho_c$')
    plt.show()
Пример #16
0
    def creature_mate(self, creature):
        if creature.age() < ConfigBiology.MATURITY_AGE:
            if creature.energy() < ConfigBiology.MOVE_ENERGY:
                self.kill_creature(creature)
                return
            creature.reduce_energy(ConfigBiology.MOVE_ENERGY)
            return

        if creature.energy() < ConfigBiology.MATE_ENERGY:
            self.kill_creature(creature)
            return

        creature.reduce_energy(ConfigBiology.MATE_ENERGY)
        potential_spouses = self.space().get_nearby_creatures_from_same_race(
            creature)
        spouse = creature.select_spouse(potential_spouses)
        if spouse is None:
            return
        new_dna = Evolution.mix_dna(creature.dna(), spouse.dna())
        self.create_creature(creature.get_race(),
                             self.allocate_id(),
                             new_dna,
                             creature.coord(),
                             parents=[creature, spouse])
Пример #17
0
Файл: egt.py Проект: peihy/PyEGT
def repeat2d():
    e = Evolution()
    bs = np.linspace(1, 10, 3)
    # fig, axes = plt.subplots()
    colors = 'brgcmykwa'
    symbs = '.ox+*sdph-'
    for i in range(1, 10):
        i = 4
        G = nx.random_regular_graph(i + 1, 1000)
        p = Population(G)
        a = [0] * len(bs)
        for j, b in enumerate(bs):
            g = game.PDG(b)
            e.set_population(p).set_game(g).set_rule(u)
            e.evolve(10000)
            a[j] = e.cooperate[-1]
            plt.plot(bs, a, colors[j] + symbs[j], label='b=%f' % b)
        break
    plt.show()
Пример #18
0
def run():
    # Initialize
    darwinian = Evolution(15, 6)

    # Evolve
    darwinian.evolve(150)

    # Get the best agent
    best_genome = darwinian.get_best_genome()

    # Visualize the performance
    for i_episode in range(10):
        observation = darwinian.env.reset()
        for t in range(500):
            darwinian.env.render()

            action = best_genome.action(observation)
            observation, reward, done, info = darwinian.env.step(action)
            if done:
                print("Episode finished after {} timesteps".format(t+1))
                break

    # Display the network architecture
    visualize(best_genome.get_inputs(),
        best_genome.get_outputs(), best_genome.get_connections())

    # Plot the statistics
    stats = darwinian.get_statistics()
    plt.plot(stats[0], stats[1]) # average
    plt.plot(stats[0], stats[2]) # best
    plt.ylabel("Reward")
    plt.xlabel("Generation")
    plt.legend(['average', 'best'], loc='upper left')
    plt.show()

    # Sleep a bit
    time.sleep(1)
    darwinian.env.close()
Пример #19
0
from evolution import Evolution
from file_loader import loadData

X = []
Y = []
loadData('randomdata_4_500_500_3_30.txt', X, Y)

evolutionAlgorithm = Evolution(20, 20, 20, 0.9, 3, X, Y)
wyr = evolutionAlgorithm.evolving(40, False, True)
Пример #20
0
from evolution import Evolution, Species

# define a species (gene pool, gene length)
species = Species()

# define a set of 10 organisms of species `Species`
organisms = Evolution(species, pop_size=10)

organims.create()
fittest_organism = organisms.evolve(evolve_until_thresh_reached=True)
Пример #21
0
        self.CAN_SAVE = can_save
        # additional config options for database connection or fukebane(s)
        self.HAS_CONFIG = has_config

    def parse(self, addressbook, conf):
        '''load file / open database connection'''
        # XXX: set addressbook in __init__?
        self.ab = addressbook
        pass

    def add(self, name, birthday):
        '''save new birthday to file/database (only if CAN_SAVE == true)'''
        pass

    def save_config(self, conf):
        '''record current entries in config menu into configuration'''
        pass
    
    def create_config(self, vbox, conf):
        '''create additional pygtk config in config menu'''
        pass

from csv import CSV
from evolution import Evolution
from lightning import Lightning
from mysql import MySQL
from sunbird import Sunbird

mysql_db = MySQL()
DATABASES = [CSV(), Evolution(), Lightning(), mysql_db, Sunbird()]
Пример #22
0
batch_size = 4
sizes = [784, 30, 10]
train_iterations = 100
test_iterations = 10

all_params = pop_size * [{
    'weights': [np.random.randn(m, n) for m, n in zip(sizes[1:], sizes)],
    'biases': [np.random.randn(m, 1) for m in sizes[1:]],
    'learning_rate':
    .1,
    'regularization':
    .01
}]

task = Task(batch_size)
evolution = Evolution()

for i in itertools.count():
    agents = [
        Agent(params['weights'], params['biases'], params['learning_rate'],
              params['regularization']) for params in all_params
    ]

    for j in range(train_iterations):
        x, y = task.train_input()
        costs = [np.average(a.costs) for a in agents]
        print('Ite {}: Avg cost: {}. Best cost {}'.format(
            j, np.average(costs), max(costs)))
        for agent in agents:
            agent.train(x, y)
Пример #23
0
                verticals+=1
            
            photos.append(Photo(len(photos), line[0], set(line[2:])))
        return n, photos, verticals
    
if __name__ == "__main__":
    """
    uso:

    python3 main.py nombre-entrada
    """
    filename = sys.argv[1]

    n, photos, verticals = get_info('input/{}'.format(filename))
    print("file " + filename)
    e = Evolution(population, photos)
    if verticals <=1:
        vertical_mutation = 0
    else:
        vertical_mutation = mutate_vertical_percent
    
    e.init_params(vertical_mutation, mutate_random_percent, parent_percent)
    
    for i in range(generations):
        print ("generation "+ str(i))
        e.run_generation()

    best = e.best_ever

    fingerprint = "{}-{}-{}-{}-{}".format(population,generations, mutate_vertical_percent, mutate_random_percent, parent_percent )
    with open("output/{}-{}.out".format(filename, fingerprint), "w") as f:
Пример #24
0
        return 0


if __name__ == '__main__':
    results = []
    labels = [2, 4, 6, 8]
    epochs = 100
    for i in labels:
        evo = Evolution(size=i,
                        fitness=fitness,
                        combine_params=0.5,
                        mutate_params={
                            "std": 0.5,
                            "dim": 1,
                            "min": 0,
                            "max": 5
                        },
                        pop_params={
                            "min": 0,
                            "max": 5,
                            "dim": 1
                        },
                        method="combine")
        evo.run(epochs)
        results.append(evo.result)
    for i in labels:
        evo = Evolution(size=i,
                        fitness=fitness,
                        combine_params=0.1,
                        mutate_params={
                            "std": 0.5,
Пример #25
0
    # concatenate selected features with their target values
    dataset = np.column_stack((X, y))
    
    popsize = [100, 250, 500, 1000]
    GenMax = [50, 100, 250, 500]
    mutRate = [0.01, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
    crRate = [0.01, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6]# 0.7, 0.8, 0.9]
    reps = 5
    states = 1

    i = 6
    evo = Evolution(
        dataset = dataset.tolist(),      # data samples 
        popsize = popsize[3],            # initial population size
        hofsize = 10,                    # the number of best individual to track
        cx = crRate[i],                  # crossover rate
        mut = mutRate[6],                # mutation rate
        maxgen = GenMax[2],              # max number of generations
        )
            
    logs = pd.DataFrame()

    gen = np.zeros((reps, GenMax[2]+1))
    nevals = np.zeros((reps, GenMax[2]+1))
    avg = np.zeros((reps, GenMax[2]+1))
    mini = np.zeros((reps, GenMax[2]+1))    
    maxi = np.zeros((reps, GenMax[2]+1))
    
    for l in range(reps):
        np.random.seed(reps)
Пример #26
0
from world import World
from creature import Creature
from evolution import Evolution

import time

if __name__ == "__main__":
    size = 35
    population_size = 10
    evolution_steps = 20
    default_creatures_spec = {"max_step_size": 3, "steps_before_die": 10}

    world = World(size)
    evolution = Evolution(world, population_size, default_creatures_spec)
    for step in range(evolution_steps):
        world.draw_world()
        world.draw_creatures(evolution.creatures)
        world.redraw()
        evolution.make_step()
        time.sleep(0.3)
Пример #27
0
for i, filename in enumerate(filenames):
    tsp = Tsp(filename)
    print(filename, ans[i])
    with open('log/test1/{}.txt'.format(filename), 'w') as f:
        start = time.time()

        f.write('{}, {}\n\n'.format(filename, ans[i]))
        for size in sizes:
            for generation in generations:
                for solution in solutions:
                    selection = selections[solution[0]]
                    crossover = crossovers[solution[1]]
                    mutation = mutations[solution[2]]
                    evolution = Evolution(tsp, size, generation, selection,
                                          crossover, mutation, select_rate,
                                          mutation_rate)
                    f.write(
                        'size: {}, generation: {}, selection: {}, crossover: {}, mutation: {}\n'
                        .format(size, generation, solution[0], solution[1],
                                solution[2]))
                    print(
                        'size: {}, generation: {}, selection: {}, crossover: {}, mutation: {}'
                        .format(size, generation, solution[0], solution[1],
                                solution[2]))

                    dis_log = []
                    for g in range(generation):
                        evolution.forward()
                        min_dis, _ = evolution.get_population().min()
                        if g % 1000 == 0:
Пример #28
0
def main():

    #Create config builder values
    #Game Parameters
    HEIGHT = config_values.HEIGHT
    WIDTH = config_values.WIDTH
    WALL_DENSITY = config_values.WALL_DENSITY
    PILL_DENSITY = config_values.WALL_DENSITY
    FRUIT_CHANCE = config_values.FRUIT_CHANCE
    FRUIT_SCORE = config_values.FRUIT_SCORE
    TIME_MULT = config_values.TIME_MULT

    #Paramters
    RUNS = config_values.RUNS
    EVALS = config_values.EVALS

    #EA Parameters
    MAX_DEPTH = config_values.MAX_DEPTH
    PAC_POP_SIZE = config_values.pac_population_size
    GHOST_POP_SIZE = config_values.ghost_population_size
    PAC_GEN_STEP = config_values.pac_generation_step
    GHOST_GEN_STEP = config_values.ghost_generation_step
    P_SELECT = config_values.parent_selection
    OVER_S = config_values.over_sel
    S_SELECT = config_values.survival_selection
    T_SELECT = config_values.termination
    PAC_SUR_K = config_values.pac_survival_k
    GHOST_SUR_K = config_values.ghost_survival_k
    PAC_P_COEFF = config_values.pac_parsimony
    GHOST_P_COEFF = config_values.ghost_parsimony
    TERM_EVALS = config_values.term_evals
    CONVERGE = config_values.convergence
    MUT_RATE = config_values.mutation_rate
    P_UPPER = config_values.p_upper

    #Paths
    LOG = config_values.LOG
    GAME = config_values.BEST_GAME
    PAC_CONTROLLER = config_values.PAC
    GHOST_CONTOLLER = config_values.GHOST


    best_pac_fitness_all_runs = -1
    best_ghost_fitness_all_runs = 1

    #Starting logging
    logger.log_start(config_values)

    #Create the Game dictinary. Add 2 to compensate for border.
    game_dict = {
                "height" : HEIGHT+2,
                "width" : WIDTH+2,
                "wall_density" : WALL_DENSITY,
                "pill_density" : PILL_DENSITY,
                "fruit_chance" : FRUIT_CHANCE,
                "fruit_score" : FRUIT_SCORE,
                "time_mult" : TIME_MULT,
                }

    for i in range(RUNS):
        #Starting this Run
        print("Starting run {}".format(i+1))
        #Insert now log block...
        logger.log_new_run(LOG, i)

        #Create the EA instance
        EA = Evolution(PAC_POP_SIZE, GHOST_POP_SIZE, PAC_GEN_STEP, GHOST_GEN_STEP, P_SELECT, S_SELECT, T_SELECT, PAC_SUR_K, GHOST_SUR_K, PAC_P_COEFF, GHOST_P_COEFF, OVER_S, TERM_EVALS, CONVERGE, MUT_RATE, game_dict, MAX_DEPTH, P_UPPER)

        best_pac_this_run = EA.get_best_fitness()
        best_ghost_this_run = EA.get_best_ghost_fitness()

        #Better fitnesses may have emerged this run's inital population
        if best_pac_this_run > best_pac_fitness_all_runs:
            #print the game and assign
            print_game(EA.best_world_string())
            #Game contoller
            EA.get_best_member().print_controller(PAC_CONTROLLER)
            best_pac_fitness_all_runs = best_pac_this_run

        #Now for chost
        if best_ghost_this_run < best_ghost_fitness_all_runs:
            #Just print contoller and assign
            worst_game(EA.worst_world_string())
            EA.get_best_ghost().print_controller(GHOST_CONTOLLER)
            best_ghost_fitness_all_runes = best_ghost_this_run

        #Start this runs log
        logger.log_new_entry(LOG, max(PAC_POP_SIZE, GHOST_POP_SIZE), best_pac_this_run, EA.get_average_fitness())

        #Since a fitness evaluation is new defined as a game being player, when creating generations the number of
        #games played is max(pacman_lambda, ghost_lambda)
        for j in range((max(PAC_POP_SIZE, GHOST_POP_SIZE)+max(PAC_GEN_STEP, GHOST_GEN_STEP)), EVALS+1, max(PAC_GEN_STEP, GHOST_GEN_STEP)):
            #Main evolution loop

            #Create the next generation
            EA.create_generation()

            #Dump pools into their poplation
            EA.pac_dump_pool()
            EA.ghost_dump_pool()

            #Do the survival selection for both populations
            EA.do_pac_survival_selection()
            EA.do_ghost_survival_selection()

            #Log entry
            best_pac_this_run = EA.get_best_fitness()
            best_ghost_this_run = EA.get_best_ghost_fitness()

            #Check to see if any better controllers have emerged from the next generation
            #log entry
            logger.log_new_entry(LOG, j, best_pac_this_run, EA.get_average_fitness())

            if best_pac_this_run > best_pac_fitness_all_runs:
                #print the game and assign
                print_game(EA.best_world_string())
                #Game contoller
                EA.get_best_member().print_controller(PAC_CONTROLLER)
                best_pac_fitness_all_runs = best_pac_this_run

            if best_ghost_this_run <= best_ghost_fitness_all_runs:
                #Just print contoller and assign
                #Print the worst game for testing
                worst_game(EA.worst_world_string())
                EA.get_best_ghost().print_controller(GHOST_CONTOLLER)
                best_ghost_fitness_all_runs = best_ghost_this_run

            if EA.determine_termination():
                break
Пример #29
0
def f2(x):
    m = len(x)
    g = 1.0 + 10.0 * (m - 1)
    for i in range(1, m):
        g += (x[i]**2 - 10.0 * np.cos(4.0 * np.pi * x[i]))

    h = 1.0 - np.sqrt(x[0] / g)

    result = g * h

    return result


problem = Problem(num_of_variables=10,
                  objectives=[f1, f2],
                  variables_range=[(-5, 5)],
                  same_range=True,
                  expand=False)
problem.variables_range[0] = (0, 1)
print(problem.variables_range)
evo = Evolution(problem, mutation_param=5)
func = [i.objectives for i in evo.evolve()]

function1 = [i[0] for i in func]
function2 = [i[1] for i in func]
plt.xlabel('Function 1', fontsize=15)
plt.ylabel('Function 2', fontsize=15)
plt.plot(function1, function2, 'bo')
plt.show()

np.save('zdt4', func)
Пример #30
0
    avg = t / len(networks)
    return avg


if __name__ == '__main__':
    generations, population = 40, 30

    parameters = {
        "no_neurons": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],  # 4,
        "momentum_rate": [0.001, 0.01, 0.1, 0.2, 0.4, 0.6],  #0.01,
        "lambda_rate": [0.001, 0.01, 0.1, 0.2, 0.4, 0.6],  #0.001,
        "learning_rate": [0.1, 0.2, 0.4, 0.5, 0.6],  #0.5,
    }
    history_of_errors = []
    evolution_obj = Evolution(parameters)
    networks = evolution_obj.generate_population(population)

    for generations_idx in range(1, generations + 1):
        print("Generation - {} / {} :".format(generations_idx, generations))

        for network in networks:
            network.fit()

        average_loss = find_average_loss(networks)
        history_of_errors.append(average_loss)

        print("Average Loss : {}".format(average_loss))
        print("----------------------------------------------------")

        if (generations_idx != generations):