模拟退火(Simulated Annealing, SA)
来历
模拟退火算法(Simulated Annealing, SA)最早由S. Kirkpatrick等人在1983年提出。该算法受到了金属退火过程的启发,通过模拟物理系统在退火过程中的逐步冷却,找到全局最优解。
自然界中的原型
在自然界中,金属材料通过加热到高温后逐渐冷却的过程,能够消除内部应力,达到更稳定的状态。这一过程被称为退火。模拟退火算法通过模拟这一物理过程,在搜索空间中逐步降低“温度”,以避免陷入局部最优解。
原理
模拟退火算法通过以下步骤实现优化:
- 初始化:生成一个初始解,设置初始温度。
- 邻域搜索:从当前解的邻域中随机选择一个新解。
- 接受准则:根据Metropolis准则决定是否接受新解,即使新解比当前解差也有一定概率接受,以避免陷入局部最优。
- 温度下降:逐步降低温度,减少接受差解的概率。
- 重复:重复邻域搜索和温度下降过程,直到满足停止条件。
Metropolis准则的数学表达式为:
[ P(e, e’) =
\begin{cases}
1 & \text{if } e’ < e \
\exp\left(\frac{-(e’ - e)}{T}\right) & \text{if } e’ \geq e
\end{cases}
]
其中,( e )和( e’ )分别为当前解和新解的能量值,( T )为当前温度。
实现方法
以下是一个简单的Python实现:
import numpy as np
# 适应度函数
def fitness_function(x):
return x**2 # 示例:目标是找到最小值,即x的平方
# 邻域搜索函数
def neighbor(x):
return x + np.random.uniform(-1, 1)
# 模拟退火算法
def simulated_annealing(initial_temp, min_temp, alpha, max_iter):
current_solution = np.random.uniform(-10, 10) # 初始化解在[-10, 10]范围内
current_fitness = fitness_function(current_solution)
best_solution = current_solution
best_fitness = current_fitness
temp = initial_temp
for _ in range(max_iter):
if temp < min_temp:
break
new_solution = neighbor(current_solution)
new_fitness = fitness_function(new_solution)
if new_fitness < current_fitness or np.exp((current_fitness - new_fitness) / temp) > np.random.rand():
current_solution = new_solution
current_fitness = new_fitness
if current_fitness < best_fitness:
best_solution = current_solution
best_fitness = current_fitness
temp *= alpha # 降低温度
return best_solution, best_fitness
# 参数设置
initial_temp = 1000
min_temp = 1
alpha = 0.9
max_iter = 1000
best_solution, best_fitness = simulated_annealing(initial_temp, min_temp, alpha, max_iter)
print(f"Best solution: {best_solution}, Best fitness: {best_fitness}")
适用的情况
- 多峰优化:适用于具有多个局部最优解的复杂问题。
- 组合优化问题:如旅行商问题(TSP)、背包问题等。
- 全局优化问题:适用于需要全局搜索能力的优化问题。
优势
- 全局搜索能力强:通过接受差解的机制,有效避免陷入局部最优解。
- 实现简单:算法简单,易于实现和理解。
- 适用范围广:适用于连续和离散优化问题。
劣势
- 计算复杂度高:需要较长时间找到最优解,尤其是在温度下降过程较慢时。
- 参数敏感性:对初始温度、降温速率等参数较为敏感,需要进行参数调优。
- 收敛速度慢:在某些情况下,收敛速度可能较慢,影响计算效率。
通过上述介绍,我们可以看到模拟退火算法作为一种自然启发式优化算法,通过模拟金属退火过程,在解决复杂优化问题方面展现了出色的性能。合理设置参数并结合具体问题的特点,模拟退火算法可以在大规模搜索空间中高效地找到全局最优解。