关键是生成新的候选解以及依概率接受劣质解进而有效的避免了陷入局部最优的囧境,粒子群开局撒一把米并逐轮迭代而模拟退火随温度逐渐降低的同时每一轮撒一个进行迭代,相比前者收敛速度肯定慢了好多,并且还有概率接受劣质解(随温度增大撒米范围逐渐减小,除非你对收敛一无所求)。。。
模拟退火算法实现代码
import numpy as np
import matplotlib.pyplot as plt
# 定义目标函数
def objective_function(x):
return x[0]**2 + x[1]**2 # 简单的二次函数
# 生成新的候选解
def new_solution(x, bounds):
new_x = x + np.random.uniform(-1, 1, size=x.shape)
return np.clip(new_x, bounds[0], bounds[1])
# 模拟退火算法
def simulated_annealing(objective_function, dimensions, bounds, initial_temp, final_temp, alpha, max_iter):
current_solution = np.random.uniform(bounds[0], bounds[1], size=(dimensions,))
current_value = objective_function(current_solution)
best_solution = current_solution.copy()
best_value = current_value
temperature = initial_temp
# 用于可视化的准备
solutions = [current_solution]
values = [current_value]
for iteration in range(max_iter):
new_solution_candidate = new_solution(current_solution, bounds)
new_value = objective_function(new_solution_candidate)
delta = new_value - current_value
# 接受新的候选解
if delta < 0 or np.random.rand() < np.exp(-delta / temperature):
current_solution = new_solution_candidate
current_value = new_value
# 更新最佳解
if current_value < best_value:
best_value = current_value
best_solution = current_solution
# 降低温度
temperature = max(temperature * alpha, final_temp)
# 记录用于可视化
solutions.append(current_solution)
values.append(current_value)
# 实时绘图
plt.clf()
plt.scatter([s[0] for s in solutions], [s[1] for s in solutions], c='blue', s=10, label='Visited solutions')
plt.scatter(best_solution[0], best_solution[1], c='red', s=50, label='Best solution')
plt.xlim(bounds)
plt.ylim(bounds)
plt.title(f"Iteration: {iteration+1}/{max_iter}, Temperature: {temperature:.3f}, Best Value: {best_value:.3f}")
plt.xlabel("x0")
plt.ylabel("x1")
plt.pause(0.1)
plt.show()
return best_solution, best_value
# 参数设置
dimensions = 2
bounds = (-10, 10)
initial_temp = 1000
final_temp = 1
alpha = 0.99
max_iter = 1000
# 执行模拟退火算法
best_solution, best_value = simulated_annealing(objective_function, dimensions, bounds, initial_temp, final_temp, alpha, max_iter)
print(f"Best Solution: {best_solution}")
print(f"Best Value: {best_value}")