Created
January 2, 2020 20:48
-
-
Save joc32/c605889bdd0c70391f56e2c3aa81b2d8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import time | |
chars = [] | |
for i in range(32, 127): | |
chars.append(chr(i)) | |
def randomString(): | |
"""Generate a random string of fixed length """ | |
return ''.join(random.choice(chars) for i in range(28)) | |
def initialise_population(population_size:int): | |
population = [] | |
for i in range(0, population_size): | |
population.append(randomString()) | |
return population | |
def fitness_eval(member:str): | |
string = 'methinks it is like a weasel' | |
fitness = 0 | |
split = list(string) | |
for i in range(0, 28): | |
if member[i] == split[i]: | |
fitness = fitness+1 | |
return fitness | |
def mutation(parent: str, mutation_rate=70): | |
parent = list(parent) | |
child = [0] * 28 | |
for i in range(0, 28): | |
p = random.uniform(0, 1) | |
if (p) < (1/mutation_rate): | |
child[i] = random.choice(chars) | |
else: | |
child[i] = parent[i] | |
return child | |
def crossover(parentA,parentB): | |
child = [0] * 28 | |
for i in range(0,28): | |
if random.uniform(0,1) < 0.5: | |
child[i] = parentA[i] | |
else: | |
child[i] = parentB[i] | |
return child | |
def choose_parent(pop): | |
A = random.choice(pop) | |
B = random.choice(pop) | |
if fitness_eval(A) > fitness_eval(B): | |
parent = A | |
else: | |
parent = B | |
return parent | |
def genetic_algorithm_crossover(population_size): | |
pop = initialise_population(population_size) | |
fitness,counter = 0,0 | |
while(fitness<28): | |
print(counter) | |
A = random.choice(pop) | |
B = random.choice(pop) | |
if fitness_eval(A) > fitness_eval(B): | |
parent1 = A | |
else: | |
parent1 = B | |
A = random.choice(pop) | |
B = random.choice(pop) | |
if fitness_eval(A) > fitness_eval(B): | |
parent2 = A | |
else: | |
parent2 = B | |
res = crossover(parent1, parent2) #create a child | |
child = mutation(res) | |
A = random.choice(pop) | |
B = random.choice(pop) | |
iA = pop.index(A) | |
iB = pop.index(B) | |
if (fitness_eval(A) > fitness_eval(B)): # if A is better than B | |
pop[iB] = child # B is child | |
else: | |
pop[iA] = child | |
if fitness_eval(child) > fitness: | |
fitness = fitness_eval(child) | |
print(fitness,child) | |
counter+=1 | |
genetic_algorithm_crossover(500) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment