I have a problem of implementing a string matching algorithm with 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. The reason I think is that de
is changing "randomly". Am I right? If so, how to fix it?
The goal is that the score should reach 0 at the end.
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.
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
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.