Skip to content

Commit 72f29f5

Browse files
antmarakisnorvig
authored andcommitted
update genetic algorithm (aimacode#676)
1 parent b6cf600 commit 72f29f5

File tree

1 file changed

+12
-17
lines changed

1 file changed

+12
-17
lines changed

search.py

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -702,20 +702,11 @@ def genetic_search(problem, fitness_fn, ngen=1000, pmut=0.1, n=20):
702702
return genetic_algorithm(states[:n], problem.value, ngen, pmut)
703703

704704

705-
def genetic_algorithm(population, fitness_fn, gene_pool=[0, 1], f_thres=None, ngen=1000, pmut=0.1): # noqa
705+
def genetic_algorithm(population, fitness_fn, gene_pool=[0, 1], f_thres=None, ngen=1000, pmut=0.1):
706706
"""[Figure 4.8]"""
707707
for i in range(ngen):
708-
new_population = []
709-
random_selection = selection_chances(fitness_fn, population)
710-
for j in range(len(population)):
711-
x = random_selection()
712-
y = random_selection()
713-
child = reproduce(x, y)
714-
if random.uniform(0, 1) < pmut:
715-
child = mutate(child, gene_pool)
716-
new_population.append(child)
717-
718-
population = new_population
708+
population = [mutate(recombine(*select(2, population, fitness_fn)), gene_pool, pmut)
709+
for i in range(len(population))]
719710

720711
if f_thres:
721712
fittest_individual = argmax(population, key=fitness_fn)
@@ -739,18 +730,22 @@ def init_population(pop_number, gene_pool, state_length):
739730
return population
740731

741732

742-
def selection_chances(fitness_fn, population):
733+
def select(r, population, fitness_fn):
743734
fitnesses = map(fitness_fn, population)
744-
return weighted_sampler(population, fitnesses)
735+
sampler = weighted_sampler(population, fitnesses)
736+
return [sampler() for i in range(r)]
745737

746738

747-
def reproduce(x, y):
739+
def recombine(x, y):
748740
n = len(x)
749-
c = random.randrange(1, n)
741+
c = random.randrange(0, n)
750742
return x[:c] + y[c:]
751743

752744

753-
def mutate(x, gene_pool):
745+
def mutate(x, gene_pool, pmut):
746+
if random.uniform(0, 1) >= pmut:
747+
return x
748+
754749
n = len(x)
755750
g = len(gene_pool)
756751
c = random.randrange(0, n)

0 commit comments

Comments
 (0)