【问题标题】:Simulated Annealing for string matching with Python使用 Python 进行字符串匹配的模拟退火
【发布时间】:2020-04-03 08:06:36
【问题描述】:

我在使用 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 时运行的代码示例

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

注意:类似的代码已经完成了爬山并且运行良好。

【问题讨论】:

    标签: python artificial-intelligence simulated-annealing


    【解决方案1】:
    t -= 0.5
    

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

    t = t * 0.95
    

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

    【讨论】:

    • 是的,我做到了,你是对的。你能解释一下为什么线性冷却在这里不起作用吗?
    • 在退火过程中,有一个温度 T,比其他温度好得多。这是大约 10% 被接受的温度(因此 90% 被拒绝)。你说的是舒适的 T。大部分进展都是在这个舒适的温带 T 期间完成的。当你走直线时,你有可能冲过这个阶段。
    猜你喜欢
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多