Armed with a measure of success and two methods of modifying the best programs, you're now ready to set up a competitive environment in which programs can evolve. The steps are shown in the flowchart in Figure 11-1. Essentially, you create a set of random programs and select the best ones for replication and modification, repeating this process until some stopping criteria is reached.
Create a new function called
evolve to carry out this procedure:
def evolve(pc,popsize,rankfunction,maxgen=500, mutationrate=0.1,breedingrate=0.4,pexp=0.7,pnew=0.05): # Returns a random number, tending towards lower numbers. The lower pexp # is, more lower numbers you will get def selectindex( ): return int(log(random( ))/log(pexp)) # Create a random initial population population=[makerandomtree(pc) for i in range(popsize)] for i in range(maxgen): scores=rankfunction(population) print scores if scores==0: break # The two best always make it newpop=[scores,scores] # Build the next generation while len(newpop)<popsize: if random( )>pnew: newpop.append(mutate( crossover(scores[selectindex( )], scores[selectindex( )], probswap=breedingrate), pc,probchange=mutationrate)) else: # Add a random node to mix things up newpop.append(makerandomtree(pc)) population=newpop scores.display( ) return scores
This function creates an initial random population. It then loops
maxgen times, each time calling
rankfunction to rank the programs from best ...