使用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 targetit = 0while 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' ) 

这是代码在温度大约为700时运行的示例

这是代码在温度大约为700时运行的示例

这是代码运行结束时的另一个示例

这是代码运行结束时的另一个示例

注意:使用爬山算法实现的类似代码运行良好。


回答:

t -= 0.5

这是一种线性冷却。通常这不是最好的方法。你有没有尝试过几何冷却?

t = t * 0.95

当然,0.95只是一个猜测,你需要探索不同的起始/停止温度组合和冷却因子。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注