模拟退火算法(Simulated Annealing)是一种概率搜索算法,源自于金属退火过程。在金属退火中,通过缓慢降低温度,金属内部的原子能够从高能态逐步达到较低能态。模拟退火算法利用类似的原理,通过随机搜索和概率接受策略来找到近似最优解。
模拟退火算法的原理
- 目标:寻找最小化或最大化目标函数的近似最优解。
- 温度:从高温逐渐降到低温。
- 状态变换:通过随机变换产生邻域解。
- 接受概率:以一定概率接受当前解,概率与温度和能量变化相关。
伪代码
1. 初始化当前解 s0,并设定初始温度 T0
2. while 当前温度 T > Tmin:
3. 随机产生新的解 s'(当前解的邻域解)
4. 计算能量差 ΔE = f(s') - f(s)
5. if ΔE < 0:
6. 接受新的解 s = s'
7. else:
8. 以概率 P(ΔE, T) = exp(-ΔE / T) 接受新的解 s = s'
9. 降低温度 T = T * α
10. 返回最优解
Python 实现:模拟退火算法
示例问题:求解最小化 Rastrigin 函数
Rastrigin 函数是一个常见的多峰函数,用于测试优化算法的全局搜索能力。函数公式如下:
𝑓(𝑥,𝑦)=10×2+(𝑥2−10×cos(2𝜋𝑥))+(𝑦2−10×cos(2𝜋𝑦))
Python 实现:
import math
import random
import numpy as np
import matplotlib.pyplot as plt
# Rastrigin 函数
def rastrigin(x):
A = 10
return A * len(x) + sum([(xi**2 - A * math.cos(2 * math.pi * xi)) for xi in x])
# 邻域解生成函数
def random_neighbor(x, bounds, step_size=0.5):
return [min(max(xi + random.uniform(-step_size, step_size), bounds[i][0]), bounds[i][1]) for i, xi in enumerate(x)]
# 模拟退火算法
def simulated_annealing(objective, bounds, T0=1000, Tmin=1e-5, alpha=0.9, max_iter=1000):
# 随机初始化起点
x = [random.uniform(b[0], b[1]) for b in bounds]
best_solution = x
best_score = objective(x)
current_solution = x
current_score = best_score
T = T0
scores = []
for _ in range(max_iter):
if T < Tmin:
break
# 生成新邻域解
neighbor = random_neighbor(current_solution, bounds)
neighbor_score = objective(neighbor)
# 接受概率计算
if neighbor_score < current_score:
current_solution = neighbor
current_score = neighbor_score
else:
p = math.exp((current_score - neighbor_score) / T)
if random.random() < p:
current_solution = neighbor
current_score = neighbor_score
# 更新最优解
if current_score < best_score:
best_solution = current_solution
best_score = current_score
scores.append(best_score)
# 降低温度
T *= alpha
return best_solution, best_score, scores
# 定义搜索空间(x 和 y 的范围)
bounds = [(-5.12, 5.12), (-5.