lolamontes69

Ch11 Ex4-Programming Collective Intelligence

Sep 15th, 2013
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.84 KB | None | 0 0
  1. """ Chapter 11 Exercise 4: Stopping evolution.
  2.  
  3.    Add an additional criteria to evolve that stops the process and returns the best result if the best score hasn't been improved within X generation
  4.  
  5.    Implemented with the variable stopnumber :)
  6.  
  7. """
  8.  
  9. def evolve(pc,popsize,rankfunction,stopnumber=12,maxgen=500,mutationrate=0.1,breedingrate=0.4,pexp=0.7,pnew=0.05):
  10.     def selectindex(lenscores):
  11.         while True:
  12.             # Stop selectindex() from returning numbers out of index.
  13.             ind =  int(log(random())/log(pexp))
  14.             if (ind-lenscores>(lenscores*2)-1) or (ind>lenscores): pass
  15.             else: return ind
  16.  
  17.     population=[makerandomtree(pc) for i in range(popsize)]
  18.  
  19.     # Add exit if no improvement within X generations
  20.     lastbestscore = 999999999
  21.     repeatcount=0
  22.  
  23.     for i in range(maxgen):
  24.         scores=rankfunction(population)
  25.         print scores[0][0]
  26.         if scores[0][0]==0: break
  27.  
  28.         # Add exit if no improvement within X generations
  29.         if (scores[0][0]==lastbestscore) and (repeatcount==stopnumber-1):
  30.             break
  31.         elif (scores[0][0]==lastbestscore) and (repeatcount!=stopnumber-1):
  32.             repeatcount+=1
  33.         else:
  34.             repeatcount=0
  35.         lastbestscore=scores[0][0]
  36.  
  37.         newpop=[scores[0][1],scores[1][1]]
  38.         while len(newpop)<popsize:
  39.             if random()>pnew:
  40.                 newpop.append(mutate(
  41.                                 crossover(scores[selectindex(len(scores))][1],
  42.                                         scores[selectindex(len(scores))][1],
  43.                                         probswap=breedingrate),
  44.                                 pc,probchange=mutationrate))
  45.             else:
  46.                 newpop.append(makerandomtree(pc))
  47.         population=newpop
  48.     scores[0][1].display()
  49.     return scores[0][1]
Advertisement
Add Comment
Please, Sign In to add comment