模拟退火算法(Simulated Annealing, SA)是一种通用的概率优化算法,用于在给定的大搜索空间内寻找问题的近似全局最优解。该算法灵感来源于物理中固体物质的退火过程,通过逐渐降低系统的温度来寻找能量最低的状态。
在Python中实现模拟退火算法,我们首先需要定义目标函数(即我们想要最小化的函数),然后设置初始解、初始温度、温度下降策略、迭代次数等参数。下面是一个简单的模拟退火算法实现示例,用于解决一个简单的优化问题:
import random | |
import math | |
def objective_function(x): | |
""" 目标函数,例如求 x^2 的最小值 """ | |
return x**2 | |
def simulated_annealing(objective, initial_guess, temp=10000, temp_min=1, alpha=0.99, max_iter=10000): | |
""" | |
模拟退火算法 | |
:param objective: 目标函数 | |
:param initial_guess: 初始解 | |
:param temp: 初始温度 | |
:param temp_min: 最低温度 | |
:param alpha: 温度衰减系数 | |
:param max_iter: 最大迭代次数 | |
:return: 近似最优解 | |
""" | |
current = initial_guess | |
current_value = objective(current) | |
best = current | |
best_value = current_value | |
for i in range(max_iter): | |
# 随机生成新的解 | |
neighbor = current + random.uniform(-1, 1) | |
neighbor_value = objective(neighbor) | |
# 计算增量 | |
delta = neighbor_value - current_value | |
# 接受准则 | |
if delta < 0: | |
# 如果新解更优,则无条件接受 | |
current = neighbor | |
current_value = neighbor_value | |
if neighbor_value < best_value: | |
best = neighbor | |
best_value = neighbor_value | |
else: | |
# 如果新解不优,则以一定概率接受 | |
if random.random() < math.exp(-delta / temp): | |
current = neighbor | |
current_value = neighbor_value | |
# 降温 | |
temp *= alpha | |
# 检查是否达到最低温度 | |
if temp < temp_min: | |
break | |
return best | |
# 使用模拟退火算法寻找 x^2 的最小值 | |
initial_guess = 10 | |
best_solution = simulated_annealing(objective_function, initial_guess) | |
print(f"Best solution: {best_solution}, Objective value: {objective_function(best_solution)}") |
说明
- 目标函数 (
objective_function
): 定义了我们要优化的函数。在这个例子中,我们试图找到x^2
的最小值。 - 模拟退火函数 (
simulated_annealing
): 实现了模拟退火算法的核心逻辑。它接受目标函数、初始猜测、初始温度、最低温度、温度衰减系数和最大迭代次数作为参数。 - 接受准则: 如果新解更优,则无条件接受;如果新解不优,则以
exp(-delta / temp)
的概率接受,其中delta
是新旧解之间的目标函数值差,temp
是当前温度。 - 降温过程: 每次迭代后,温度按
alpha
系数递减。
注意
- 模拟退火算法的性能高度依赖于初始温度、温度衰减系数和最大迭代次数等参数。
- 算法可能不总是找到全局最优解,但通常能找到足够好的近似解。
- 对于复杂问题,可能需要调整算法参数或目标函数以适应特定情况。