-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgenome.py
172 lines (133 loc) · 5.42 KB
/
genome.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
from collections import OrderedDict
import numpy as np
import tensorflow as tf
from perceptron_2l import Perceptron
from Dino import Dino
import random
import logging
logger = logging.getLogger('genome')
class Genome(object):
def __init__(self, numGenes, mutationProb, selection, folder, generations):
if selection > numGenes:
self.numGenes = numGenes
self.selection = numGenes
else:
self.numGenes = numGenes
self.selection = selection
self.mutationProb = mutationProb
self.genes = []
self.generation = 0
self.only_mutation = 0.2
self.scores = []
self.folder = folder
self.num_Generations = generations
self.delta = 0.1*self.num_Generations/(self.generation+1)
self.build_genome()
#Build the network
def build_genome(self):
while len(self.genes) < self.numGenes:
print(len(self.genes))
network = Perceptron(self.folder, len(self.genes))
self.genes.append(network)
network = None
def execute_generation(self, game):
self.gen = 0
self.scores = []
self.generation += 1
self.delta = 0.1 * self.num_Generations / self.generation
while self.gen < self.numGenes:
self.execute_gene(game)
self.gen += 1
def execute_gene(self, game):
gene = self.genes[self.gen]
#If stopped, restart
if game.get_crashed():
game.restart()
dinosaur = Dino(game)
#current_score = dinosaur.play(gene)
#Play a game a return the score.
self.genes[self.gen].fitness = dinosaur.play(gene, self.gen, self.generation, self.folder)
#self.scores.append(current_score)
def select_best_genes(self): #Sort genes by score and take the best
d = dict(enumerate(self.genes))
f = []
s = []
selected = OrderedDict(sorted(d.items(), key=lambda t: t[1].fitness, reverse=True)).values()
selected_list = list(selected)
selected = selected_list[:self.selection]
tf.reset_default_graph()
for select in selected:
fit = select.copy()
fit.reload()
s.append(fit)
f.append(select.fitness)
selected = None
logger.info('Fitness: #### %s' % (str(f),))
return s, f
def kill_and_reproduce(self):
#Kill
self.genes, scores = self.select_best_genes()
logger.info("Renumbering...")
#Renumber
for gen in self.genes:
gen.n_gen = self.genes.index(gen)
logger.info(f"{self.selection} genes have been renumbered.")
best = self.genes.copy()
#Best genes have to get more chances of reproduction, so it makes a probability distribution
prob = self.get_probability_distribution(scores)
#Crossover
while len(self.genes) < self.numGenes - int(self.only_mutation*self.numGenes):
genA = random.choices(best, k=1, weights = prob)[0].copy()
genB = random.choices(best, k=1, weights = prob)[0].copy()
newGen = self.mutation(self.crossover(genA, genB))
newGen.n_gen = len(self.genes)
self.genes.append(newGen)
#Mutation
while len(self.genes) < self.numGenes:
gen = random.choices(best, k=1, weights = prob)[0].copy()
newGen = self.mutation(gen)
newGen.n_gen = len(self.genes)
self.genes.append(newGen)
logger.info(f'Generación completada {self.generation}')
def get_probability_distribution(self, scores):
p = [i / np.sum(scores) for i in scores]
logger.info(f'The probabilities are {p}')
return p
def crossover(self, gen1, gen2):
#Flip them at random
if random.random() > 0.5:
temp = gen1
gen1 = gen2
gen2 = temp
try:
gen1_dict = gen1.as_dict
except:
gen1_dict = gen1.get_dict
try:
gen2_dict = gen2.as_dict
except:
gen2_dict = gen2.get_dict
for par in ['biases']: #Crossover only for biases (better results)
gen1_par = gen1_dict[par]
gen2_par = gen2_dict[par]
cut_loc = int(len(gen1_par) * random.random())
gen1_updated = np.append(gen1_par[(range(0, cut_loc)),], gen2_par[(range(cut_loc, len(gen2_par))),])
gen1_dict[par] = gen1_updated
gen1.reload()
return gen1
def mutation(self, gen1): #Mutation for weights and biases
gen1_dict = gen1.as_dict
self.mutate_data(gen1_dict, self.mutationProb, 'biases')
self.mutate_data(gen1_dict, self.mutationProb, 'weights')
gen1.reload()
return gen1
def mutate_data(self, gen_dict, mutationRate, key):
for k in range(0, len(gen_dict[key])):
if random.random() < mutationRate:
#gen_dict[key][k] += random.uniform(-self.delta, self.delta)
gen_dict[key][k] += gen_dict[key][k] * (random.random() - 0.5) * random.random() + (random.random() - 0.5)
def save_all(self):
logger.info("Saving all genomes.")
for gen in self.genes:
#gen.saver = tf.train.Saver()
gen.save_net()