Created
December 22, 2011 17:35
-
-
Save jal278/1511130 to your computer and use it in GitHub Desktop.
Simple ga
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
#### 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