Genetic Algorithm in Python: Data Mining Lab 6
Genetic Algorithm in Python: Data Mining Lab 6
Basically, all this does it goes through each member of the population and compares it
with the target string. It adds up the differences between the characters and uses the
cumulative sum as the fitness value (therefore, the lower the value, the better).
For comparison: random optimizer
from ga_helloworld import *
string_population=init_strings_population(204800)
best_rand=randomoptimize( string_population,
string_fitness )
print best_rand[1]
print " score = %d" % best_rand[0]
0:ipos ipos+1:
random character
Mate operation (crossover) for GA
def string_crossover(p1,p2):
ipos=random.randint(1,target_length-2)
return p1[0:ipos]+p2[ipos:]
+
Genetic algorithm I
def genetic_optimize(population,fitness_function,mutation_function,
mate_function, mutation_probability, elite, maxiterations):
# How many winners from each generation?
original_population_size=len(population)
top_elite=int(elite*original_population_size)
# Main loop
for i in range(maxiterations):
individual_scores=[(fitness_function(v),v)
for v in population]
individual_scores.sort( )
ranked_individuals=[v for (s,v) in individual_scores]
# Start with the pure winners
population=ranked_individuals[0:top_elite]
Genetic algorithm II
# Add mutated and bred forms of the winners
while len(population)<original_population_size:
if random.random( )<mutation_probability:
# Mutation
c=random.randint(0,top_elite)
population.append( mutation_function
(ranked_individuals[c]))
else:
# Crossover
c1=random.randint(0,top_elite)
c2=random.randint(0,top_elite)
if individual_scores[0][0]==0:
return individual_scores[0][1]
return individual_scores[0][1]
Running genetic optimizer
from ga_helloworld import *
string_population=init_strings_population(2048)
genetic_optimize(string_population, string_fitness,
mutate_string, string_crossover, 0.25,0.1,100)
totalprice=0
people John Mary Laura Abe Greg Lee
latestarrival=0
earliestdep=24*60
solution out in
for d in range(len(sol)/2):
origin=people[d][1]
outbound = flights[(origin,destination)][int(sol[2*d])]
returnf = flights[(destination,origin)][int(sol[2*d+1])]
totalprice+=outbound[2]
totalprice+=returnf[2]
if latestarrival<getminutes(outbound[1]):
latestarrival =getminutes(outbound[1])
if earliestdep>getminutes(returnf[0]):
earliestdep=getminutes(returnf[0])
Fitness function II
# Every person must wait at the airport until the latest person arrives.
# They also must arrive at the same time and wait for their flights on the way
back.
totalwait=0
for d in range(len(sol)/2):
origin=people[d][1]
outbound = flights[(origin,destination)][int(sol[2*d])]
returnf = flights[(destination,origin)][int(sol[2*d+1])]
totalwait+=latestarrival-getminutes(outbound[1])
totalwait+=getminutes(returnf[0])-earliestdep
# Does this solution require an extra day of car rental? That'll be $50!
execfile ("ga_schedule.py")