Skip to content

Instantly share code, notes, and snippets.

@iscadar
Created April 7, 2011 15:26
Show Gist options
  • Save iscadar/907998 to your computer and use it in GitHub Desktop.
Save iscadar/907998 to your computer and use it in GitHub Desktop.
A simple genetic algorithm
##A simple genetic algorithm
##by Alexandros Kourkoulas-Chondrorizos
##v0.1
##This is one of the simplest versions of a GA out there.
##You can use it to set up any kind of evolutionary experiment
##and it's a great starting point for designing more complex
##and sophisticated GAs. Note that the function eval_ind() that
##is called in the code below isn't a real function. It's only
##a placeholder for whatever your fitness function happens to be.
from scipy import *
from matplotlib.pyplot import *
gl=10 #genome length of each individual
pops=30 #population size
pop=rand(pops,gl).round() #initial population
E=100 #epochs
pop_fit=zeros([pops]) #population fitness storage
for ip in range(pops): #evaluate individuals and store their fitness
pop_fit[ip]=eval_ind(pop[ip]) #evaluate each individual
afit=zeros([E]) #average pop fitness storage
for ie in range(E): #run evolution for set number of epochs
w=pop_fit.argmax() #index of the highest scoring individual
m=round((pops-1)*rand()) #pick a random mate
l=pop_fit.argmin() #lowest scoring individual
rr=0.5 #recombination rate
mr=0.1 #mutation rate
o=zeros([gl]) #offspring template
for ig in range(gl): #recombination and mutation
if rand()<rr: o[ig]=pop[w][ig] #recombine parent genes
else: o[ig]=pop[m][ig]
if rand()<mr: o[ig]=abs(o[ig]-1) #mutate offspring's genes
ofit=eval_ind(o) #evaluate offspring
pop[l]=o #replace lowest scoring individual with offspring
pop_fit[l]=ofit #replace lowest fitness with offspring's
afit[ie]=pop_fit.mean() #storing average population fitness
plot(range(E),afit),grid(),show() #plot average fitness against epoch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment