Skip to content

Instantly share code, notes, and snippets.

@glorion13
Last active March 1, 2021 19:59
Show Gist options
  • Save glorion13/c2415082deb0ef47a5382793fcb27918 to your computer and use it in GitHub Desktop.
Save glorion13/c2415082deb0ef47a5382793fcb27918 to your computer and use it in GitHub Desktop.
import random
import numpy
LOW_BOUND = -10.0
HIGH_BOUND = 10.0
POPULATION_SIZE = 100
MAX_GENERATIONS = 1000
def calculate_fitness(gene):
variables = [6, -1, 4, 3, 19, -3]
return numpy.sum(numpy.multiply(gene, variables))
def crossover(gene1, gene2):
position = numpy.random.randint(len(gene1))
new_gene1 = gene1[:position] + gene2[position:]
new_gene2 = gene2[:position] + gene1[position:]
return new_gene1, new_gene2
def mutate(gene):
position = numpy.random.randint(len(gene))
new_gene = gene
new_gene[position] = numpy.random.uniform(low=LOW_BOUND, high=HIGH_BOUND)
return new_gene
def run_evolution():
fittest_gene = None
genes = numpy.random.uniform(
low=LOW_BOUND, high=HIGH_BOUND, size=(POPULATION_SIZE, 6),
).tolist()
for generation in xrange(MAX_GENERATIONS):
# Evaluate fitness of genes
fitnesses = map(calculate_fitness, genes)
ranked_genes = sorted(zip(fitnesses, genes))
generation_fittest = ranked_genes[-1]
if not fittest_gene or generation_fittest[0] > fittest_gene[0]:
fittest_gene = generation_fittest
print "Generation {0}: {1}".format(generation, fittest_gene)
# Survival of the fittest, get the top half of the population
survivors = ranked_genes[len(ranked_genes) // 2:]
genes = [survivor[1] for survivor in survivors]
survivor_count = len(survivors)
for _ in xrange(survivor_count // 2):
# Crossover
gene1 = random.choice(survivors)[1]
gene2 = random.choice(survivors)[1]
new_genes = crossover(gene1, gene2)
for new_gene in new_genes:
roll = random.random()
# Mutation
if roll > 0.1:
new_gene = mutate(new_gene)
genes.append(new_gene)
return fittest_gene
if __name__ == "__main__":
print run_evolution()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment