[英]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 -= 0.5
是線性冷卻。 這通常不是最好的。 (?)你試過幾何嗎?
t = t * 0.95
當然,0.95 是一個猜測,您想探索不同的啟動/停止溫度組合和冷卻系數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.