Last active
August 29, 2015 14:00
-
-
Save thiagopnts/11253500 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
from random import random, randint | |
class Individual: | |
def __init__(self, size): | |
self.size = size | |
self.genes = map(lambda x: 1 if random() < 0.50 else 0, [0] * self.size) | |
def fitness(self): | |
return abs((sum([1 + i for i in range(len(self.genes)) if self.genes[i] == 0]) - 36.0) / 36.0) | |
def print_info(self): | |
values = [i + 1 for i in range(self.size) if self.genes[i] == 0] | |
print 'Card values:' | |
print ' + '.join(map(str, values)) + ' = %d' % sum(values) | |
class Population: | |
def __init__(self, size, genes_size): | |
self.size = size | |
self.individuals = [Individual(genes_size) for i in range(size)] | |
def pick(self): | |
return self.individuals[randint(0, self.size - 1)] | |
class Nature: | |
def __init__(self, population, rounds=500, mutation=0.4, recombination=0.1): | |
self.mutation = mutation | |
self.recombination = recombination | |
self.population = population | |
self.rounds = rounds | |
def do_the_evolution(self): | |
for i in range(self.rounds): | |
winner, loser = self.match(self.population.pick(), self.population.pick()) | |
for i in range(len(winner.genes)): | |
if random() < self.recombination: | |
loser.genes[i] = loser.genes[i] ^ 1 | |
if random() < self.mutation: | |
loser.genes[i] = winner.genes[i] | |
if loser.fitness() == 0: | |
print "\nit's evolution baby!!" | |
loser.print_info() | |
def match(self, ind1, ind2): | |
return (ind1, ind2) if ind1.fitness() < ind2.fitness() else (ind2, ind1) | |
population = Population(50, 10) | |
nature = Nature(population) | |
nature.do_the_evolution() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment