Advertisement
Guest User

Untitled

a guest
Dec 12th, 2018
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.50 KB | None | 0 0
  1. def anneal(start_temp=1.0, n=10000, advent=None, scurve_k=10.0, scurve_bias=0.3):
  2.     import math
  3.     temp = start_temp
  4.     cooling_rate = (start_temp / float(n))
  5.     if advent is None:
  6.         advent = randcal()
  7.     else:
  8.         advent = advent.copy()
  9.     bestscore = current_score = score(advent)
  10.     best = advent.copy()
  11.     count = 0
  12.  
  13.     step = 1.0 / n
  14.     try:
  15.         while count < n:
  16.             i = np.random.randint(0,24)
  17.             j = np.random.randint(0,24)
  18.             advent[i/6,i%6], advent[j/6,j%6] = advent[j/6,j%6], advent[i/6,i%6]
  19.             newscore = score(advent)
  20.             if newscore < current_score or np.random.rand() < temp:
  21.                 current_score = newscore
  22.             else:
  23.                 advent[i/6,i%6], advent[j/6,j%6] = advent[j/6,j%6], advent[i/6,i%6]
  24.  
  25.             # Cool temperature along s-curve (needs a more robust sigmoid func!)
  26.             # Seems to perform better than a linear decrease.
  27.             sigmoid = 1 - 1.0 / (
  28.                 1 + math.e ** (
  29.                     -scurve_k * (step * count - scurve_bias)
  30.                 )
  31.             )
  32.             temp = start_temp * sigmoid
  33.  
  34.             if current_score < bestscore:
  35.                 best = advent.copy()
  36.                 bestscore = current_score
  37.  
  38.             count += 1
  39.             if count % 100 == 0:
  40.                 print count, temp, bestscore, current_score
  41.     except:
  42.         print 'Error. Best so far was:', (best, bestscore)
  43.         raise
  44.  
  45.     return (best, bestscore)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement