-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathga.py
194 lines (153 loc) · 6.62 KB
/
ga.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
from optimise import ObjectiveFunction
import random
import logging
class Individual(object):
'''
an individual in the population
'''
def __init__(self, solution, objective_function, move_operator, recombine_operator):
self.solution=solution
self.objective_function=objective_function
self.move_operator=move_operator
self.recombine_operator=recombine_operator
self._score=None
def _new_from_solution(self,solution):
return Individual(solution, self.objective_function, self.move_operator, self.recombine_operator)
def breed(self,parent):
if random.random() < 1:
solution=self.recombine_operator(self.solution, parent.solution)
return self._new_from_solution(solution)
return self
def mutate(self):
if random.random() < 1:
solution=self.move_operator(self.solution).next()
return self._new_from_solution(solution)
return self
def score(self):
if self._score is None:
self._score=self.objective_function(self.solution)
return self._score
#def __hash__(self):
# return hash(self.solution)
#
#def __eq__(self, other):
# return self.solution == other.solution
def __repr__(self):
return "Individual(%d)" % self.score()
def __cmp__(self, other):
if self.score() < other.score():
return 1
elif self.score() > other.score():
return -1
return 0
def pop_stats(population):
pop_size=len(population)
scores=[p.score() for p in population]
avg=sum(scores)/float(pop_size)
var=sum((score-avg)**2 for score in scores)/float(pop_size)
logging.info("avg: %f var: %f", avg, var)
def tournament(population, size, reverse=False):
population=list(population)
selected=[random.choice(population) for i in xrange(size)]
selected.sort()
return selected
def replace_if_better(population, parent, child):
if parent.score() < child.score():
replace(population, parent, child)
def replace(population, parent, child):
population.remove(parent)
population.add(child)
def select_worst(population, tournament_size=None):
if tournament_size is None:
tournament_size=len(population)
return tournament(population, tournament_size, reverse=True)
def replace_worst(population, child, tournament_size=None):
worst=select_worst(population, tournament_size)
replace(population, worst, child)
def replace_worst_if_better(population, child, tournament_size=None):
worst=select_worst(population, tournament_size)
replace_if_better(population, worst, child)
def replace_worst_parent(population, p1, p2, child):
worst=p1
if p2.score() < p1.score():
worst=p2
replace(population, worst, child)
def steady_state(init_function,move_operator,objective_function,max_evaluations,recombine_operator,pop_size,breed_size=50,replace_size=2):
objective_function=ObjectiveFunction(objective_function)
insert=lambda population, child: replace_worst_if_better(population, child, replace_size)
population=set([Individual(init_function(),objective_function,move_operator,recombine_operator) for i in xrange(pop_size)])
while objective_function.num_evaluations < max_evaluations:
competitors=tournament(population, breed_size)
p1,p2,worst=competitors[0],competitors[1],competitors[-1]
child=p1.breed(p2)
child=child.mutate()
replace(population, worst, child)
if objective_function.num_evaluations % 1000 == 0:
pop_stats(population)
return (objective_function.num_evaluations,objective_function.best_score,objective_function.best)
def cull(population, pop_size):
return set(list(sorted(population,reverse=True))[:pop_size])
def generational(init_function,move_operator,objective_function,max_evaluations,recombine_operator,pop_size):
objective_function=ObjectiveFunction(objective_function)
insert=lambda population, child: replace_worst_if_better(population, child, replace_size)
population=set([Individual(init_function(),objective_function,move_operator,recombine_operator) for i in xrange(pop_size)])
while objective_function.num_evaluations < max_evaluations:
next_population=set()
#while len(next_population) < pop_size and objective_function.num_evaluations < max_evaluations:
# p1=tournament(population, 2)
#p2=tournament(population, 2)
#child=p1.breed(p2)
#if random.random() < 0.1:
for p1 in population:
#p2=tournament(population, 2)
#child=p1.breed(p2)
child=p1.mutate()
child.score()
next_population.add(child)
if objective_function.num_evaluations % 1000 == 0:
pop_stats(population)
else:
# swap population over
population.update(next_population)
population=cull(population,pop_size)
#print len(population)
return (objective_function.num_evaluations,objective_function.best_score,objective_function.best)
def roulette_selection(population):
total_fitness=sum(i.score() for i in population)
r=random.random()
s=0
for i in population:
s += i.score()
p=((total_fitness-s)/total_fitness)
if r <= p:
return i
return i # or return last one
def hillclimb(i):
while True:
i1=i.mutate()
if i1.score() > i.score():
i=i1
if random.random() < 0.5:
break
return i
def generational2(init_function,move_operator,objective_function,max_evaluations,recombine_operator,pop_size):
objective_function=ObjectiveFunction(objective_function)
population=[Individual(init_function(),objective_function,move_operator,recombine_operator) for i in xrange(pop_size)]
population.sort()
next_population=[]
elite_size=1
while objective_function.num_evaluations < max_evaluations:
if len(next_population)+elite_size < len(population):
p1=roulette_selection(population)
p2=roulette_selection(population)
child=p1.breed(p2).mutate()
#child=p1.mutate()
#child=hillclimb(child)
next_population.append(child)
else:
# keep some of the fittest individuals from last time
population=population[:elite_size] + next_population
population.sort()
next_population=[]
return (objective_function.num_evaluations,objective_function.best_score,objective_function.best)
evolve=steady_state