【发布时间】: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