lolamontes69

Ch5 Ex2-Programming Collective Intelligence

Jul 6th, 2013
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.49 KB | None | 0 0
  1. """ Chapter 5 Exercise 2: Annealing Starting Points.
  2.  
  3.    The outcome of simulated annealing depends heavily on the starting point. Build a new optimization function that does simulated annealing from multiple starting solutions and returns the best one.
  4.  
  5. """
  6.  
  7. def randomrestart_annealing(domain,costf,T1=10000.0,cool=0.95,step=1,maxiter=100):
  8.     T = T1
  9.     best=999999999
  10.     bestr=None
  11.     for i in range(maxiter):
  12.         # Initialize the values randomly
  13.         vec=[(random.randint(domain[i][0],domain[i][1])) for i in range(len(domain))]
  14.         while T>0.1:
  15.             # Choose one of the indices
  16.             i=random.randint(0,len(domain)-1)
  17.  
  18.             # Choose a direction to change it
  19.             dir=random.randint(-step,step)
  20.  
  21.             # Create a new list with one of the values changed
  22.             vecb=vec[:]
  23.             vecb[i]+=dir
  24.             if vecb[i]<domain[i][0]: vecb[i]=domain[i][0]
  25.             elif vecb[i]>domain[i][1]: vecb[i]=domain[i][1]
  26.  
  27.             # Calculate the current cost and the new cost
  28.             ea=costf(vec)
  29.             eb=costf(vecb)
  30.             p=pow(math.e,(-eb-ea)/T)
  31.  
  32.             # Is it better, or does it make the probability cutoff?
  33.             if (eb<ea or random.random()<p):
  34.                 vec=vecb
  35.  
  36.             # Decrease the temperature
  37.             T=T*cool
  38.         cost = costf(vec)
  39.  
  40.         # reinitialize the variable T
  41.         T = T1
  42.         if cost<best:
  43.             best=cost
  44.             bestr=vec
  45.     return bestr
Advertisement
Add Comment
Please, Sign In to add comment