Hi everyone, I want to share a genetic evolutionary algorithm in Python. Made on a series of Coding Train: Genetic algorithm https://www.youtube.com/watch?v=9zfeTw-uFCw
Unfortunately, the last character always loops, it seems to be lucky / unlucky. I can not understand why, and increased the total number of the population and changed the percentage of mutations, unfortunately all the same one character is searched for a very long time.
Here is a simple listing of my code:
class DNA(object): def __init__(self,string="",length=0): import random if string: self.string = string self.length = len(string) elif length: self.string = "".join([chr(random.randrange(32,122)) for x in range(length)]) class Population(object): def __init__(self): self.generation = [] def make_generation(self,word_len,cnt=1): self.generation = [DNA(length=word_len) for i in range(cnt)] def clear_generation(self): self.generation = [] def fit_func(goal,element): fit = 0 for i in range(len(goal)): if element.string[i] == goal[i]: fit += 1 return round(fit/len(goal),3) def crossover(a,b): x1 = a.string[:len(a.string)//2] y1 = b.string[len(b.string)//2:] return DNA(string=x1+y1) def mutate(dna): import random for i in dna.string: if random.randint(1,100) < 4: dna.string = dna.string.replace(i,chr(random.randrange(32,122)),1) def main(): import random g = "To be or not to be" new_pop = Population() new_pop.make_generation(len(g),1000) while True: good_el = {} for i in new_pop.generation: ff = fit_func(g,i) if i.string == g: print("Done") if ff > 0: good_el[ff] = i print(max(good_el.keys()),"\t",good_el[max(good_el.keys())].string) new_pop.clear_generation() while len(new_pop.generation) < 1000: parents = random.choices(list(good_el.values()),weights=list(good_el.keys()),k=2) new_element = crossover(parents[0],parents[1]) mutate(new_element) new_pop.generation.append(new_element)