简体   繁体   English

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

[英]Simulated Annealing for string matching with Python

I have a problem of implementing a string matching algorithm with SA.我有一个用 SA 实现字符串匹配算法的问题。 After all the iterations are done, I am not getting even closer to the string I want.完成所有迭代后,我并没有更接近我想要的字符串。 I tried to decrease the temperature change but nothing has changed.我试图减少温度变化,但没有任何改变。

For me, I think that the problem is because p is not decreasing steadily.对我来说,我认为问题在于p并没有稳步下降。 The reason I think is that de is changing "randomly".我认为的原因是de正在“随机”变化。 Am I right?我对吗? If so, how to fix it?如果是这样,如何解决?

The goal is that the score should reach 0 at the end.目标是最终得分应该达到0。 The score sums up all the distances between the random letters and the actual ones.分数总结了随机字母与实际字母之间的所有距离。 change_cur_solution changes only one random letter each time. 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' ) 

Here is a sample of the code running when t is about 700这是 t 约为 700 时运行的代码示例

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

Here is another sample run at the end:这是最后运行的另一个示例:

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

Note: a similar code was done with hill climbing and worked fine.注意:类似的代码是通过爬山完成的,并且运行良好。

t -= 0.5

Is a linear cooling.是线性冷却。 This is generally not the best.这通常不是最好的。 (?) Have you tried geometric? (?)你试过几何吗?

t = t * 0.95

Of course, 0.95 is a guess, and you want to explore difference start/stop temp combinations, and cooling factor.当然,0.95 是一个猜测,您想探索不同的启动/停止温度组合和冷却系数。

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

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