Skip to content

Search: Update Genetic Algorithm To New Pseudocode #676

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 3, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 12 additions & 17 deletions search.py
Original file line number Diff line number Diff line change
Expand Up @@ -702,20 +702,11 @@ def genetic_search(problem, fitness_fn, ngen=1000, pmut=0.1, n=20):
return genetic_algorithm(states[:n], problem.value, ngen, pmut)


def genetic_algorithm(population, fitness_fn, gene_pool=[0, 1], f_thres=None, ngen=1000, pmut=0.1): # noqa
def genetic_algorithm(population, fitness_fn, gene_pool=[0, 1], f_thres=None, ngen=1000, pmut=0.1):
"""[Figure 4.8]"""
for i in range(ngen):
new_population = []
random_selection = selection_chances(fitness_fn, population)
for j in range(len(population)):
x = random_selection()
y = random_selection()
child = reproduce(x, y)
if random.uniform(0, 1) < pmut:
child = mutate(child, gene_pool)
new_population.append(child)

population = new_population
population = [mutate(recombine(*select(2, population, fitness_fn)), gene_pool, pmut)
for i in range(len(population))]

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


def selection_chances(fitness_fn, population):
def select(r, population, fitness_fn):
fitnesses = map(fitness_fn, population)
return weighted_sampler(population, fitnesses)
sampler = weighted_sampler(population, fitnesses)
return [sampler() for i in range(r)]


def reproduce(x, y):
def recombine(x, y):
n = len(x)
c = random.randrange(1, n)
c = random.randrange(0, n)
return x[:c] + y[c:]


def mutate(x, gene_pool):
def mutate(x, gene_pool, pmut):
if random.uniform(0, 1) >= pmut:
return x

n = len(x)
g = len(gene_pool)
c = random.randrange(0, n)
Expand Down
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy