优化算法.模拟退火算法

关键是生成新的候选解以及依概率接受劣质解进而有效的避免了陷入局部最优的囧境,粒子群开局撒一把米并逐轮迭代而模拟退火随温度逐渐降低的同时每一轮撒一个进行迭代,相比前者收敛速度肯定慢了好多,并且还有概率接受劣质解(随温度增大撒米范围逐渐减小,除非你对收敛一无所求)。。。

模拟退火算法实现代码

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}")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值