-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsingle.py
More file actions
48 lines (39 loc) · 1.6 KB
/
single.py
File metadata and controls
48 lines (39 loc) · 1.6 KB
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
import numpy as np
class Single:
params = None
def __init__(self, params):
self.params = params
self.params['tourn_size'] = None # must be less than par_size and pop_size
def get_functions(self):
return ['rank-based', 'tournament']
def rank_based(self, pop, pop_size, sel_size):
if self.params['objs'][0] == min:
return np.array(sorted(pop,
key=lambda sol: sol['fitness'][0])[:sel_size])
else:
return np.array(sorted(pop,
key=lambda sol: sol['fitness'][0],
reverse=True)[:sel_size])
def tournament(self, pop, pop_size, sel_size):
winners = []
for i in range(sel_size):
indices = np.random.choice(a=pop_size, size=self.params['tourn_size'], replace=False)
index = self.play(pop, indices)
winners.append(pop[index])
return np.array(winners)
def play(self, pop, indices):
if len(indices) == 1:
return indices[0]
else:
left = self.play(pop, indices[int(len(indices) / 2):])
right = self.play(pop, indices[:int(len(indices) / 2)])
if self.params['objs'][0] == min:
if pop[left]['fitness'][0] < pop[right]['fitness'][0]:
return left
else:
return right
else:
if pop[left]['fitness'][0] > pop[right]['fitness'][0]:
return left
else:
return right