模拟退火算法(Simulated Annealing)python的简单实现

本文介绍了一种启发式全局优化算法——模拟退火算法。该算法通过不断迭代找到问题的近似全局最优解,避免陷入局部最优解。文章详细解释了算法流程,并提供了一个用Python实现的例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 模拟退火算法简介

           模拟退火算法是一种启发式算法。 通过不断的迭代当前解在周围找到问题的最优解。( 个人理解是在简单的爬坡法加上了概率的因素,防止陷入局部最优解。)     完整的模拟退火过程是模拟热力学的退火过程,随着温度的不断下降(本质上是随着迭代次数的增多,发生跳转的概率越来越小的过程),算法将在多项式的时间内找到问题的近似全局最优解(有可能还是局部最优解)。

 

2  算法流程

  1. 初始化温度 T 和每个 T = t_{i} 时,进行迭代次数的L, 时间衰减率\eta, 初始化一个解 x_{0} ;
  2.  while $ $ $ $t>MinT
  3.     for$ $ $ $ $ $ l=1:L
  4.            计算函数值 value\_old = f(x\_old)
  5.            在 x\_old 周围随机试探产生新的x\_newx\_new = x\_old + (random()-0.5)
  6.            value\_new = f(x\_new)value\_old作比较
  7.           if   value\_newvalue\_old更接近目标函数值
  8.                  x\_old = x\_new
  9.          else
  10.                以一定的概率接受x\_new, 条件式$\exp(-(value\_new-value\_old)/k*t)$ > random()
  11.   t = t * \eta

这里面与爬坡法最大的区别是在算法步骤10中, 当不满足爬坡条件的时候,仍然以一定的概率接受接受到新值;当温度较高的时候概率越大,也就更容易跳出局部极值点,而随着温度慢慢下降,慢慢的也收敛到全局极值点。

3 python代码实现

import numpy as np
import matplotlib.pyplot as plt
import math
def function(x):
    return -(10*math.sin(5*x)+7*math.cos(4*x))

initT = 1000
minT = 1
iterL = 1000
eta = 0.95
k = 1

x0 = 1.5#10*(2*np.random.rand()-1)

t = initT
print("init solution :",x0)
yy=[]
xx = np.linspace(0,10,300)
for i in range(len(xx)):
    yy.append(function(xx[i]))
plt.figure()
plt.plot(xx,yy)
plt.plot(x0,function(x0),'o')

x_old = x0
while t > minT:
    for i in range(iterL):#MonteCarlo method reject propblity
        value_old = function(x_old)
        x_new = x_old+np.random.rand()-0.5
        if x_new>=0 and x_new<=10:
            value_new = function(x_new)
            res = value_new-value_old
            if res<0 or np.exp(-res/(k*t))>np.random.rand():
                x_old = x_new
    t = t*eta

print("最优解: ",x_old)
print("最优值:",function(x_old))
plt.plot(x_old,function(x_old),'or')
plt.show()

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值