lolamontes69

Ch11 Ex2- Programming Collective Intelligence

Sep 14th, 2013
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.71 KB | None | 0 0
  1. """ Chapter 11 Exercise 2: Replacement mutation.
  2.  
  3.    Implement a mutation proceedure that chooses a random node on the tree and changes it.
  4.    Make sure it deals with function, constant and parameter nodes.
  5.    How is evolution affected by using this function instead of the branch replacement?
  6.    *see end
  7.  
  8. """
  9.  
  10. import gp as gp
  11. from random import random,randint
  12. from copy import deepcopy
  13.  
  14.  
  15. def mutateRandomNode(t,pc,probchange):
  16.     if not hasattr(t,"children") or random.random() < probchange:
  17.         if isinstance(t,paramnode):
  18.             a=random.randint(0,pc-1)
  19.             return paramnode(a)
  20.         elif isinstance(t,constnode):
  21.             a=random.randint(0,10)  
  22.             return constnode(a)
  23.         else:
  24.             return makerandomtree(pc)
  25.     else:
  26.         c = random.randint(0,len(t.children)-1)
  27.         t.children[c]=mutateRandomNode(t.children[c],pc,probchange)
  28.     return t
  29.  
  30. def newMutate(t,pc,probchange):
  31.     t1=deepcopy(t)
  32.     mutateRandomNode(t1,2,probchange)
  33.     return t1
  34.  
  35. exampletree=gp.exampletree()
  36. test=newMutate(exampletree,2,0.1)
  37. test.display()
  38.  
  39. """
  40.  
  41.    The newMutate() function in general do not mutate programs to a much greater length
  42.    precentagewise because there is less chance of a new function node being created.
  43.    Sometimes it seems to get stuck on a certain level, probably because not
  44.    enough diversity is being introduced, especially if it is trying to mutate long
  45.    programs only changing one parameter at a time... easily corrected by highering
  46.    the pnew parameter. Conversely though if it finds the beginnings of a good program sometimes
  47.    it is likely to find the solution faster for the same reason.
  48.         -lolamontes69
  49.  
  50. """
Advertisement
Add Comment
Please, Sign In to add comment