Skip to content

Instantly share code, notes, and snippets.

@jal278 jal278/ga.py
Created Dec 22, 2011

Embed
What would you like to do?
Simple ga
#### Simple genetic algorithm
#### Joel Lehman
import random
errors=[]
def equation_error(x):
left_side = 2.0*x-10.0
right_side = 3.0
return abs(left_side-right_side)
def score_dna(genes):
return [equation_error(x) for x in genes]
def make_next_generation(genes,scores):
together=zip(scores,genes)
together.sort()
next_gen=[]
for x in range(5):
for copies in range(2):
next_gen.append(together[x][1]+random.uniform(-0.1,0.1))
return next_gen
#make initial list of DNAs
DNAs=[]
#ten times add a random number between 0 and 20 to the list
for x in range(10):
DNAs.append(random.uniform(0.0,20.0))
generation=1
error=100000.0
while(error>0.01):
scores=score_dna(DNAs)
error=min(scores)
best=DNAs[scores.index(error)]
print "Loop #",generation, " Lowest error: %0.2f" %error, " Best DNA: %0.2f" %best
DNAs = make_next_generation(DNAs,scores)
generation+=1
errors.append(error)
#this part requires matplotlib be installed
#you can comment it out and still run the ga
from pylab import *
title("Error vs. Time")
xlabel("Times through loop")
ylabel("Lowest error")
plot(errors)
show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.