算法原理
模拟退火算法来源于固体退火原理,将固体加温至充分高,再让其徐徐冷却,加温时,固体内部粒子随温升变为无序状,内能增大,而徐徐冷却时粒子渐趋有序,在每个温度都达到平衡态,最后在常温时达到基态,内能减为最小。
模型的物理背景
模型的迭代步骤
(1) 初始化:初始温度T(充分大),初始解状态S(是算法迭代的起点),每个T值的迭代次数L
(2) 对k=1, …, L做第(3)至第(6)步:
(3) 产生新解S′
(4) 计算增量ΔC=C(S′)-C(S),其中C(S)为评价函数
(5) 若ΔC<0则接受S′作为新的当前解,否则以概率exp(-ΔC/T)接受S′作为新的当前解.
(6) 如果满足终止条件则输出当前解作为最优解,结束程序。
终止条件通常取为连续若干个新解都没有被接受时终止算法。
一段代码用来理解
import random
import math
def simulated_annealing(objective_function, initial_solution, temperature, cooling_rate, num_iterations):
current_solution = initial_solution
current_cost = objective_function(current_solution)
for i in range(num_iterations):
# 生成新的候选解
new_solution = generate_neighbor(current_solution)
new_cost = objective_function(new_solution)
# 计算成本的差异
cost_difference = new_cost - current_cost
# 如果新解更好,总是接受
if cost_difference < 0:
current_solution = new_solution
current_cost = new_cost
else:
# 否则以一定概率接受较差的解
acceptance_probability = math.exp(-cost_difference / temperature)
if random.random() < acceptance_probability:
current_solution = new_solution
current_cost = new_cost
# 降低温度
temperature *= cooling_rate
return current_solution, current_cost
# 示例目标函数(求解一个简单的二次函数的最小值)
def objective_function(solution):
x = solution
return x**2 - 5*x + 6
# 生成邻域解的函数(这里简单地在当前解上加一个小的随机数)
def generate_neighbor(solution):
delta = random.uniform(-0.1, 0.1)
return solution + delta
# 初始解、初始温度、冷却率和迭代次数
initial_solution = 10
temperature = 100
cooling_rate = 0.95
num_iterations = 1000
best_solution, best_cost = simulated_annealing(objective_function, initial_solution, temperature, cooling_rate, num_iterations)
print("Best solution:", best_solution)
print("Best cost:", best_cost)
针对小数据集的使用代码
下面代码中使用的数据集已在文章顶部显示~~
import json
import random
import math
# 读取 JSON 文件
with open('vegetable_data.json', 'r') as f:
data = json.load(f)
# 定义成本加成定价函数
def calculate_price(cost, loss):
return (cost + loss) * 1.2
# 定义模拟退火算法的参数
initial_temperature = 1000
cooling_rate = 0.99
min_temperature = 0.1
# 初始随机选择蔬菜
current_selection = random.sample(list(data.keys()), 50)
# 计算初始总价格
current_price = sum(calculate_price(data[item]['Cost'], data[item]['Loss']) for item in current_selection)
# 模拟退火算法的主循环
temperature = initial_temperature
while temperature > min_temperature:
# 随机生成新的选择
new_selection = random.sample(list(data.keys()), 50)
# 计算新的总价格
new_price = sum(calculate_price(data[item]['Cost'], data[item]['Loss']) for item in new_selection)
# 计算价格差
price_difference = new_price - current_price
# 如果新的价格更低,或者以一定概率接受更差的解
if price_difference < 0 or random.random() < math.exp(-price_difference / temperature):
current_selection = new_selection
current_price = new_price
# 降低温度
temperature *= cooling_rate
# 输出最优选择方案
print("最优蔬菜选择方案:")
for item in current_selection:
print(item)