繁体   English   中英

与 Python 进行字符串匹配的模拟退火

[英]Simulated Annealing for string matching with Python

我有一个用 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 target
it = 0
while 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' ) 

这是 t 约为 700 时运行的代码示例

这是 t 约为 700 时运行的代码示例

这是最后运行的另一个示例:

这是最后运行的另一个示例

注意:类似的代码是通过爬山完成的,并且运行良好。

t -= 0.5

是线性冷却。 这通常不是最好的。 (?)你试过几何吗?

t = t * 0.95

当然,0.95 是一个猜测,您想探索不同的启动/停止温度组合和冷却系数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM