Created
April 16, 2012 12:21
-
-
Save cornchz/2398353 to your computer and use it in GitHub Desktop.
GA version "Hello World!" in Python
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
#!/usr/bin/env python | |
# -*- encoding: utf-8 -*- | |
from itertools import izip | |
from random import randint | |
from random import random as rand | |
GA_POPSIZE = 2048 | |
GA_MAXITER = 16384 | |
GA_ELITERATE = 0.1 | |
GA_ELITESIZE = int(GA_POPSIZE * GA_ELITERATE) | |
GA_MUTATIONRATE = 0.25 | |
GA_TARGET = 'hello world!' | |
GA_TARGETSIZE = len(GA_TARGET) | |
class Candidate: | |
def __init__(self, str_): | |
self.str = str_ | |
@property | |
def fitness(self): | |
fitness = 0 | |
for c1, c2 in izip(self.str, GA_TARGET): | |
fitness += abs(ord(c1) - ord(c2)) | |
return fitness | |
def randchar(): | |
return chr(randint(32, 121)) | |
def init_population(): | |
population = [] | |
for _ in xrange(GA_POPSIZE): | |
str_ = ''.join((randchar() for _ in xrange(GA_TARGETSIZE))) | |
member = Candidate(str_) | |
population.append(member) | |
return population | |
def mutate_char(char): | |
delta = randint(1, 90) | |
return chr((ord(char) - 32 + delta) % 90 + 32) | |
def mutate(member): | |
pos = randint(0, GA_TARGETSIZE - 1) | |
newchr = mutate_char(member.str[pos]) | |
member.str = member.str[:pos] + newchr + member.str[pos+1:] | |
return member | |
def mate(member1, member2): | |
spos = randint(1, GA_TARGETSIZE - 1) | |
newstr = member1.str[:spos] + member2.str[spos:] | |
member = Candidate(newstr) | |
if rand() < GA_MUTATIONRATE: | |
member = mutate(member) | |
return member | |
def new_generation(population): | |
population.sort(key=lambda c: c.fitness) | |
for _ in xrange(GA_POPSIZE - GA_ELITESIZE): | |
i1 = randint(0, GA_POPSIZE - 1) | |
i2 = randint(0, GA_POPSIZE - 1) | |
member = mate(population[i1], population[i2]) | |
population.append(member) | |
population = population[:GA_ELITESIZE] + population[GA_POPSIZE:] | |
return population | |
def main(): | |
population = init_population() | |
for _ in xrange(GA_MAXITER): | |
population = new_generation(population) | |
print population[0].str | |
if not population[0].fitness: break | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment