-
Notifications
You must be signed in to change notification settings - Fork 0
/
evolution.py
239 lines (186 loc) · 7.88 KB
/
evolution.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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import copy
import json
import random
from random import choice, randint, seed
import numpy as np
from numpy import shape
from player import Player
"""
getting the fitness of an element.
"""
def get_fitness(elem):
return elem.fitness
"""
evolution class
"""
class Evolution:
"""
constructor
"""
def __init__(self):
self.game_mode = "Neuroevolution"
self.write = False
"""
Roulette wheel
"""
def roulette_wheel(self, items, num_items):
probabilities = self.get_probability_list(items)
chosen = []
for n in range(num_items):
r = random.random()
for (i, individual) in enumerate(items):
if r <= probabilities[i]:
chosen.append(individual)
break
return chosen
"""
SUS
"""
def sus(self, items, num_items):
points = self.generate_points(items, num_items)
chosen = []
while len(chosen) < num_items:
random.shuffle(items)
i = 0
while i < len(points) and len(chosen) < num_items:
j = 0
sm = 0
while j < len(items):
sm += items[j].fitness
if sm > points[i]:
chosen.append(items[j])
break
j += 1
i += 1
return chosen
"""
Top-k
"""
def top_k(self, items, num_items, k=2):
chosen = []
for iteration in range(num_items):
best = None
for i in range(k):
r = randint(0, len(items) - 1)
if best is None or (items[r].fitness > items[best].fitness):
best = r
chosen.append(items[best])
return chosen
@staticmethod
def generate_points(items, num_items):
total_fitness = float(sum([item.fitness for item in items]))
point_distance = total_fitness / num_items
start_point = random.uniform(0, point_distance)
points = [start_point + i * point_distance for i in range(num_items)]
return points
def next_population_selection(self, players, num_players, file_to_write, type_of_selection='sort'):
"""
Gets list of previous and current players (μ + λ) and returns num_players number of players based on their
fitness value.
:param type_of_selection: type of selection(top-k, roulette wheel, SUS, sort)
:param players: list of players in the previous generation
:param num_players: number of players that we return
"""
# copy the list of the players
copy_players = [self.clone_player(player) for player in players]
ret = copy_players
# based on the type of selection, choose
if type_of_selection == 'sort':
copy_players.sort(key=get_fitness, reverse=True)
ret = copy_players
if type_of_selection == 'roulette wheel':
ret = self.roulette_wheel(copy_players, num_players)
elif type_of_selection == 'SUS':
ret = self.sus(copy_players, num_players)
elif type_of_selection == 'top-k':
ret = self.top_k(copy_players, num_items=num_players, k=len(copy_players) // 2)
# sorting based on the score
temp = (sorted(ret, key=get_fitness, reverse=True))
sm_fitness = sum([pl.fitness for pl in ret])
# write into histories file
if self.write:
file_to_write.write(',' + str([temp[0].fitness, temp[len(temp) - 1].fitness, sm_fitness / num_players]))
else:
file_to_write.write(str([temp[0].fitness, temp[len(temp) - 1].fitness, sm_fitness / num_players]))
self.write = True
return ret
def generate_new_population(self, num_players, prev_players=None, type_of_selection='random'):
"""
Gets survivors and returns a list containing num_players number of children.
:param type_of_selection: type of parent selection(top-k, roulette wheel, SUS, random)
:param num_players: Length of returning list
:param prev_players: List of survivors
:return: A list of children
"""
first_generation = prev_players is None
if first_generation:
ret_players = [Player(self.game_mode) for _ in range(num_players)]
return ret_players
else:
print(str(max(prev_players, key=get_fitness).fitness) + '\n')
new_players = []
for iteration in range(num_players):
par_a, par_b = self.select_parents(prev_players, type_of_selection=type_of_selection)
child_a, child_b = self.generate_children(par_a, par_b)
new_players.append(child_a)
new_players.append(child_b)
return new_players
def clone_player(self, player):
"""
Gets a player as an input and produces a clone of that player.
"""
new_player = Player(self.game_mode)
new_player.nn = copy.deepcopy(player.nn)
new_player.fitness = player.fitness
return new_player
def select_parents(self, prev_players, type_of_selection='random'):
par_a = choice(prev_players)
par_b = choice(prev_players)
if type_of_selection == 'roulette wheel':
par_a, par_b = self.roulette_wheel(prev_players, 2)
elif type_of_selection == 'SUS':
par_a, par_b = self.sus(prev_players, 2)
elif type_of_selection == 'top-k':
par_a, par_b = self.top_k(prev_players, 2, k=25)
return par_a, par_b
def generate_children(self, par_a, par_b):
value = randint(0, len(par_a.nn.layer_sizes) - 1)
child_a = self.clone_player(par_a)
child_b = self.clone_player(par_b)
for i in range(len(par_a.nn.layer_sizes) - 1):
num = i + 1
shape_1 = par_a.nn.layer_sizes[i + 1]
value = randint(0, shape_1)
W_b = np.concatenate((par_a.nn.parameters['W' + str(num)][:value, :],
par_b.nn.parameters['W' + str(num)][value:, :]), axis=0)
W_a = np.concatenate((par_b.nn.parameters['W' + str(num)][:value, :],
par_a.nn.parameters['W' + str(num)][value:, :]), axis=0)
B_a = np.concatenate((par_a.nn.parameters['b' + str(num)][:value, :],
par_b.nn.parameters['b' + str(num)][value:, :]), axis=0)
B_b = np.concatenate((par_b.nn.parameters['b' + str(num)][:value, :],
par_a.nn.parameters['b' + str(num)][value:, :]), axis=0)
params_a = {'W': W_b, 'b': B_b}
params_b = {'W': W_a, 'b': B_a}
child_a.nn.change_layer_parameters(new_layer_parameters=params_a, layer_num=num)
child_b.nn.change_layer_parameters(new_layer_parameters=params_b, layer_num=num)
child_a.fitness = 0
child_b.fitness = 0
self.mutate(child_a)
self.mutate(child_b)
return child_a, child_b
@staticmethod
def mutate(child):
for i in range(1, len(child.nn.layer_sizes)):
val = randint(0, 100)
if val > 80:
params = {'W': np.random.normal(size=(child.nn.layer_sizes[i], child.nn.layer_sizes[i - 1])),
'b': np.zeros((child.nn.layer_sizes[i], 1))}
child.nn.change_layer_parameters(new_layer_parameters=params, layer_num=i)
@staticmethod
def get_probability_list(items):
fitness = [item.fitness for item in items]
total_fit = float(sum(fitness))
relative_fitness = [f / total_fit for f in fitness]
probabilities = [sum(relative_fitness[:i + 1])
for i in range(len(relative_fitness))]
return probabilities