退火算法(Simulated Annealing, SA)是一种基于热力学模拟的优化算法,用于求解全局优化问题。它通过模拟物理退火过程来寻找全局最优解。以下是退火算法的基本原理和步骤:
退火算法的灵感来源于金属在高温下缓慢冷却至低温的过程,这一过程中,金属原子逐渐排列成能量最低的晶格结构。类似地,退火算法通过模拟这一过程,在解空间中逐渐收敛到全局最优解。
初始解与温度设定:
循环过程:
终止条件:
function SimulatedAnnealing(InitialSolution, InitialTemperature, CoolingRate, StoppingTemperature): currentSolution = InitialSolution currentTemperature = InitialTemperature while currentTemperature > StoppingTemperature: newSolution = GenerateNeighbor(currentSolution) deltaE = Evaluate(newSolution) - Evaluate(currentSolution) if deltaE < 0: currentSolution = newSolution else if exp(-deltaE / currentTemperature) > random(): currentSolution = newSolution currentTemperature = currentTemperature * CoolingRate return currentSolution
退火算法在许多领域得到了广泛应用,包括但不限于:
旅行商问题是经典的组合优化问题,描述的是一名旅行商需要访问若干城市并返回出发城市,要求访问每个城市一次且总距离最短。
给定若干城市和城市间的距离矩阵,找到一个访问所有城市的最短路径。
初始解与温度设定:
生成邻域解:
目标函数:
接受新解的准则:
import random import math def simulated_annealing(dist_matrix, initial_temp, cooling_rate, stopping_temp): def total_distance(path): return sum(dist_matrix[path[i]][path[i+1]] for i in range(len(path) - 1)) + dist_matrix[path[-1]][path[0]] def swap_two_cities(path): new_path = path[:] i, j = random.sample(range(len(path)), 2) new_path[i], new_path[j] = new_path[j], new_path[i] return new_path current_solution = list(range(len(dist_matrix))) random.shuffle(current_solution) current_distance = total_distance(current_solution) current_temp = initial_temp best_solution = current_solution[:] best_distance = current_distance while current_temp > stopping_temp: new_solution = swap_two_cities(current_solution) new_distance = total_distance(new_solution) delta_distance = new_distance - current_distance if delta_distance < 0 or math.exp(-delta_distance / current_temp) > random.random(): current_solution = new_solution current_distance = new_distance if new_distance < best_distance: best_solution = new_solution best_distance = new_distance current_temp *= cooling_rate return best_solution, best_distance # 示例距离矩阵 distance_matrix = [ [0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0] ] initial_temperature = 1000 cooling_rate = 0.95 stopping_temperature = 0.01 best_path, best_path_distance = simulated_annealing(distance_matrix, initial_temperature, cooling_rate, stopping_temperature) print("最短路径:", best_path) print("最短路径距离:", best_path_distance)
运行此代码将输出最短路径及其对应的总距离。
最短路径: [0, 2, 3, 1] 最短路径距离: 80
优点:
缺点:
总之,退火算法通过模拟物理退火过程,有效地解决了许多复杂的全局优化问题,是一种通用且强大的优化算法。