我有一个使用模拟退火(SA)实现字符串匹配算法的问题。所有的迭代完成后,我甚至没有接近我想要的字符串!我尝试降低温度变化,但没有任何变化。
我认为问题在于p
没有稳定地减少。我认为原因是de
在“随机”变化。我的想法对吗?如果是的话,该如何解决这个问题?
目标是在最后得分达到0。得分是所有随机字母与实际字母之间的距离之和。change_cur_solution
每次只改变一个随机字母。
def eval_current_sol(target,cur_sol): dist = 0 for i in range(len(target)): c = cur_sol[i] t = target[i] dist += abs(ord(c) - ord(t)) return dist t = 10000# loop until match the targetit = 0while True: if t == 0: break print('Current best score ', bestScore, 'Solution', "".join(bestSol)) if bestScore == 0: break newSol = list(bestSol) change_cur_solution(newSol) score = eval_current_sol(newSol,targetSol) de = score - bestScore if de < 0: ## score < bestScore i.e. (score of new solution < score of previous solution) ===> #better bestSol = newSol bestScore = score else: r = random.random() try: p = math.exp(-(de / t)) except: p = 0 print("p is %f de is %d t is %d" %(p, de,t)) if p > r: bestSol = newSol bestScore = score it += 1 t -= 0.5 print('Found after, ',it, 'Iterations' )
这是代码在温度大约为700时运行的示例
这是代码运行结束时的另一个示例
注意:使用爬山算法实现的类似代码运行良好。
回答:
t -= 0.5
这是一种线性冷却。通常这不是最好的方法。你有没有尝试过几何冷却?
t = t * 0.95
当然,0.95只是一个猜测,你需要探索不同的起始/停止温度组合和冷却因子。