上一篇
在解决复杂的组合优化问题时,传统的穷举法往往效率低下。这时,模拟退火算法(Simulated Annealing, SA)作为一种受物理退火过程启发的智能优化方法,能够有效跳出局部最优解,找到全局近似最优解。本文将带你从零开始,用Python优化算法实现一个完整的模拟退火算法。
模拟退火算法灵感来源于金属热处理中的“退火”过程:高温下原子自由移动,随着温度缓慢下降,原子逐渐趋于低能态,最终形成规则晶体结构。在算法中:
下面是一个求解函数 f(x) = x² + 10*sin(5x) 最小值的完整示例(x ∈ [-10, 10]):
import mathimport randomdef objective_function(x): """目标函数:需要最小化的函数""" return x ** 2 + 10 * math.sin(5 * x)def simulated_annealing(): # 参数设置 initial_temp = 100 # 初始温度 final_temp = 1e-3 # 终止温度 alpha = 0.95 # 降温系数 current_x = random.uniform(-10, 10) # 随机初始解 current_energy = objective_function(current_x) best_x = current_x best_energy = current_energy temp = initial_temp while temp > final_temp: # 在当前解附近生成新解(步长与温度相关) new_x = current_x + random.uniform(-1, 1) * temp # 确保新解在定义域内 new_x = max(-10, min(10, new_x)) new_energy = objective_function(new_x) # 计算能量差 delta_energy = new_energy - current_energy # Metropolis准则:接受更优解或以概率接受劣解 if delta_energy < 0 or random.random() < math.exp(-delta_energy / temp): current_x = new_x current_energy = new_energy # 更新全局最优解 if current_energy < best_energy: best_x = current_x best_energy = current_energy # 降温 temp *= alpha return best_x, best_energy# 运行算法best_x, best_energy = simulated_annealing()print(f"最优解: x = {best_x:.4f}, f(x) = {best_energy:.4f}") | 参数 | 作用 | 建议值 |
|---|---|---|
| 初始温度 | 控制初期接受劣解的概率 | 足够高(如50-1000) |
| 降温系数α | 控制降温速度 | 0.8~0.99(常用0.95) |
| 终止温度 | 算法停止条件 | 1e-3 ~ 1e-8 |
相比梯度下降等局部搜索算法,模拟退火算法具有以下优势:
该智能优化方法广泛应用于:
通过本教程,你已掌握用Python优化算法实现模拟退火的核心思想。尝试修改目标函数和参数,观察不同设置对结果的影响吧!
本文由主机测评网于2025-12-15发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://vpshk.cn/2025127972.html