模拟退火算法 Simulated Annealing

模拟退火算法 Simulated Annealing

1. 介绍

模拟退火算法(Simulated Annealing, SA)是一种启发式的优化算法。它适用于在大型离散或连续复杂问题中寻找全局最优解,例如组合优化,约束优化,图问题等。模拟退火是一种随机(概率性)搜索算法,基于物理中固体晶体退火过程的模拟。退火过程中,晶体内部由高能状态向低能状态演化,最终在足够低的温度时稳定在能量最低的状态。

模拟退火算法的主要思想是在搜索过程中接受比当前解差的解,以跳出局部最优。具体来说,模拟退火算法过程如下:

  1. 初始化设置:设置初始解、初始温度、温度衰减系数,最低温度等参数。

  2. 在当前温度下,随机选取一个邻近解并计算其能量变化量。

  3. 如果能量降低(对于最小化问题),则接受该解作为当前解;如果能量增加,则以一定的概率(通常依赖于温度和能量变化量)接受该解。

  4. 更新温度(通常为当前温度乘以衰减系数)。

  5. 重复步骤2-4,直到温度降至最低温度并稳定。

  6. 输出最佳解。

模拟退火算法的关键在于选择合适的初始温度、衰减系数和结束条件,以及针对问题的邻近解生成策略和概率接受函数。

2. 经典应用

接下来,我们将以三个经典问题为例,展示如何使用模拟退火算法求解。

2.1 旅行商问题(TSP)

旅行商问题即求解在给定城市、距离的情况下,找到一条道路,使得从起点出发,经过所有城市后回到起点,且总距离最短。

import random
import math
import numpy as np

# 计算路径长度
def calculate_distance(path, distance_matrix):
    distance = 0
    for i in range(len(path)-1):
        distance += distance_matrix[path[i]][path[i+1]]
    distance += distance_matrix[path[-1]][path[0]]
    return distance

# 邻近解生成策略:交换两个城市的位置
def generate_neighbor(path):
    new_path = path.copy()
    i, j = random.sample(range(len(path)), 2)
    new_path[i], new_path[j] = new_path[j], new_path[i]
    return new_path

# 模拟退火算法求解TSP问题
def simulated_annealing_tsp(distance_matrix, initial_temperature, min_temperature, cooling_factor, max_iteration):
    n = len(distance_matrix)
    current_path = list(range(n))
    random.shuffle(current_path)
    current_distance = calculate_distance(current_path, distance_matrix)

    temperature = initial_temperature
    best_path = current_path[:]
    best_distance = current_distance

    for it in range(max_iteration):
        if temperature < min_temperature:
            break

        new_path = generate_neighbor(current_path)
        new_distance = calculate_distance(new_path, distance_matrix)

        delta_distance = new_distance - current_distance
        if delta_distance < 0:
            current_path = new_path
            current_distance = new_distance

            if new_distance < best_distance:
                best_path = new_path[:]
                best_distance = new_distance
        else:
            prob = math.exp(-delta_distance / temperature)
            if random.random() < prob:
                current_path = new_path
                current_distance = new_distance

        temperature *= cooling_factor

    return best_path, best_distance

# 用随机距离矩阵测试
n = 10
distance_matrix = np.random.randint(1, 100, size=(n, n))
initial_temperature = 1000
min_temperature = 1e-6
cooling_factor = 0.99
max_iteration = 10000

best_path, best_distance = simulated_annealing_tsp(distance_matrix, initial_temperature, min_temperature, cooling_factor, max_iteration)
print('Best path:', best_path)
print('Best distance:', best_distance)
2.2 函数寻优

给定一个连续空间的实数函数f(x),求解其在给定区间上的最小值。

import random
import math

# 定义函数
def f(x):
    return x * x - 4 * x + 4

def generate_neighbor(x, step):
    return x + random.uniform(-step, step)

def simulated_annealing_function_optimization(f, initial_temperature, min_temperature, cooling_factor, max_iteration, search_interval, neighbor_step):
    current_x = random.uniform(search_interval[0], search_interval[1])
    current_y = f(current_x)

    temperature = initial_temperature

    best_x = current_x
    best_y = current_y

    for it in range(max_iteration):
        if temperature < min_temperature:
            break

        new_x = generate_neighbor(current_x, neighbor_step)
        if new_x < search_interval[0] or new_x > search_interval[1]:
            continue

        new_y = f(new_x)
        delta_y = new_y - current_y

        if delta_y < 0:
            current_x = new_x
            current_y = new_y

            if new_y < best_y:
                best_x = new_x
                best_y = new_y
        else:
            prob = math.exp(-delta_y / temperature)
            if random.random() < prob:
                current_x = new_x
                current_y = new_y

        temperature *= cooling_factor

    return best_x, best_y

initial_temperature = 1000
min_temperature = 1e-6
cooling_factor = 0.99
max_iteration = 10000
search_interval = [0, 5]
neighbor_step = 0.1

best_x, best_y = simulated_annealing_function_optimization(f, initial_temperature, min_temperature, cooling_factor, max_iteration, search_interval, neighbor_step)
print('Best x:', best_x)
print('Best y:', best_y)
2.3 定点覆盖问题

给定一个二维平面,有若干个点和一定数量的覆盖盒。要求通过移动覆盖盒的位置使得尽可能多的点被覆盖。覆盖盒的形状为边长为1的正方形。

import random
import math

def point_covered(points, box):
    # 判断点是否在覆盖盒内
    return sum([1 for p in points if box[0] <= p[0] <= box[0]+1 and box[1] <= p[1] <= box[1]+1])

def generate_neighbor(box, step):
    # 随机生成一个相邻覆盖盒
    return (box[0] + random.uniform(-step, step), box[1] + random.uniform(-step, step))

def simulated_annealing_point_cover(points, n_boxes, initial_temperature, min_temperature, cooling_factor, max_iteration, neighbor_step):
    boxes = [(random.uniform(0, 5), random.uniform(0, 5)) for _ in range(n_boxes)]
    
    temperature = initial_temperature

    # 当前解:覆盖的点数量和覆盖盒集合
    current_cover = sum([point_covered(points, box) for box in boxes])
    current_boxes = boxes

    # 迭代过程
    for it in range(max_iteration):
        if temperature < min_temperature:
            break

        # 随机选择一个覆盖盒生成相邻解
        idx = random.randrange(len(boxes))
        new_box = generate_neighbor(boxes[idx], neighbor_step)
        new_boxes = boxes[:]
        new_boxes[idx] = new_box

        new_cover = sum([point_covered(points, box) for box in new_boxes])
        delta_cover = new_cover - current_cover

        if delta_cover > 0:
            current_boxes = new_boxes
            current_cover = new_cover
        else:
            prob = math.exp(delta_cover / temperature)
            if random.random() < prob:
                current_boxes = new_boxes
                current_cover = new_cover

        temperature *= cooling_factor

    return current_boxes

# 生成点集
points = [(random.uniform(0, 5), random.uniform(0, 5)) for _ in range(50)]
n_boxes = 5

initial_temperature = 1000
min_temperature = 1e-6
cooling_factor = 0.99
max_iteration = 10000
neighbor_step = 0.1

result = simulated_annealing_point_cover(points, n_boxes, initial_temperature, min_temperature, cooling_factor, max_iteration, neighbor_step)
print(result)

以上三个案例展示了如何使用模拟退火算法求解旅行商问题、函数寻优以及定点问题。请注意,模拟退火算法在每个问题中的效果取决于选择的初始参数和邻近解生成策略。

如果你想更深入地了解人工智能的其他方面,比如机器学习、深度学习、自然语言处理等等,也可以点击这个链接,我按照如下图所示的学习路线为大家整理了100多G的学习资源,基本涵盖了人工智能学习的所有内容,包括了目前人工智能领域最新顶会论文合集和丰富详细的项目实战资料,可以帮助你入门和进阶。

链接: 人工智能交流群(大量资料)

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/211074.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

string的模拟

> 作者简介&#xff1a;დ旧言~&#xff0c;目前大二&#xff0c;现在学习Java&#xff0c;c&#xff0c;c&#xff0c;Python等 > 座右铭&#xff1a;松树千年终是朽&#xff0c;槿花一日自为荣。 > 目标&#xff1a;能手撕模拟string类 > 毒鸡汤&#xff1a;时间…

IDC MarketScape2023年分布式数据库报告:OceanBase位列“领导者”类别,产品能力突出

12 月 1 日&#xff0c;全球领先的IT市场研究和咨询公司 IDC 发布《IDC MarketScape:中国分布式关系型数据库2023年厂商评估》&#xff08;Document number:# CHC50734323&#xff09;。报告认为&#xff0c;头部厂商的优势正在扩大&#xff0c;OceanBase 位列“领导者”类别。…

基于算能的国产AI边缘计算盒子,8核心A53丨10.6Tops算力

边缘计算盒子 8核心A53丨10.6Tops算力 ● 算力高达10.6TOPS,单芯片最高支持8路H.264 & H.265的实时解码能力。 ● 可扩展4G/5G/WIFI无线网络方式&#xff0c;为边缘化业务部署提供便利。 ● 支持RS232/RS485/USB2.0/USB3.0/HDMI OUT/双千兆以太网等。 ● 低功耗设计&a…

在 ArcGIS 软件中添加左斜宋体(东体)的方法与步骤

河流水系在作图时一般设置为左斜宋体&#xff08;东体&#xff09;、蓝色&#xff0c;比如黄河、青海湖等&#xff0c;如下图所示&#xff1a; 标准地图水系注记 下面讲解如何在 ArcGIS 软件中添加左斜宋体&#xff08;东体&#xff09;&#xff0c;首先需要下载左斜宋体&#…

如何在 Ubuntu 22.04中安装 Docker Compose

1 安装 pip # 下载get-pip.py脚本 wget https://bootstrap.pypa.io/pip/3.10/get-pip.py 或者 # 下载最新版本 curl https://bootstrap.pypa.io/get-pip.py --output get-pip.py# 为 Python 3 安装 pip sudo python3 get-pip.py2 安装 Pip 后&#xff0c;运行以下命令安装 Doc…

模板方法设计模式

package com.jmj.pattern.template;public abstract class AbstractClass {//模板方法定义public final void cookProcess(){pourOil();heatoil();pourVegetable();pourSauce();fry();}public void pourOil(){System.out.println("倒油");}public void heatoil(){Sys…

HarmonyOS——UI开展前的阶段总结

当足够的了解了HarmonyOS的相关特性之后&#xff0c;再去介入UI&#xff0c;你会发现无比的轻松&#xff0c;特别当你有着其他的声明式UI开发的经验时&#xff0c;对于HarmonyOS的UI&#xff0c;大致一扫&#xff0c;也就会了。 如何把UI阐述的简单易懂&#xff0c;又能方便大…

前端入门(五)Vue3组合式API特性

文章目录 Vue3简介创建Vue3工程使用vite创建vue-cli方式 常用 Composition API启动项 - setup()setup的执行时机与参数 响应式原理vue2中的响应式vue3中的响应式ref函数reactive函数reactive与ref对比 计算属性 - computed监视属性 - watchwatchEffect Vue3生命周期自定义hook函…

io基础入门

压缩的封装 参考&#xff1a;https://blog.csdn.net/qq_29897369/article/details/120407125?utm_mediumdistribute.pc_relevant.none-task-blog-2defaultbaidujs_baidulandingword~default-0-120407125-blog-120163063.235v38pc_relevant_sort_base3&spm1001.2101.3001.…

Socket 编程

1&#xff1a;针对 TCP 应该如何 Socket 编程&#xff1f; 服务端和客户端初始化 socket&#xff0c;得到文件描述符&#xff1b; 服务端调用 bind&#xff0c;将 socket 绑定在指定的 IP 地址和端口; 服务端调用 listen&#xff0c;进行监听&#xff1b; 服务端调用 accept&am…

vue3中自定义hook函数

使用Vue3的组合API封装的可复用的功能函数 自定义hook的作用类似于vue2中的mixin技术 自定义Hook的优势: 很清楚复用功能代码的来源, 更清楚易懂 案例: 收集用户鼠标点击的页面坐标 hooks/useMousePosition.ts文件代码&#xff1a; import { ref, onMounted, onUnmounted …

hbase Master is initializing

问题如下&#xff1a; ERROR: org.apache.hadoop.hbase.PleaseHoldException: Master is initializing ERROR: org.apache.hadoop.hbase.PleaseHoldException: Master is initializingat org.apache.hadoop.hbase.master.HMaster.checkInitialized(HMaster.java:2452)at org.…

第十一届蓝桥杯青少组省赛Python中高级组真题及赏析

练习最好的办法就是实战。拿真题来做&#xff0c;不是解析是赏析。带着欣赏的眼光看&#xff0c;题目不但不难&#xff0c;反倒增加不少乐趣。接下来揭开第十一届蓝桥杯青少组省赛python编程题的神秘面纱&#xff0c;我们来一一赏析&#xff0c;看难不难。 选择题 选择题都比较…

解决Linux的端口占用报错问题

文章目录 1 Linux报错2 解决方式 1 Linux报错 Port 6006 is in use. If a gradio.Blocks is running on the port, you can close() it or gradio.close_all(). 想起之前运行Gradio 6006&#xff0c;端口被占用 2 解决方式 输入 netstat -tpl查看当前一些端口号的占用号&a…

【智能家居】二、添加火灾检测模块(烟雾报警功能点)

可燃气体传感器 MQ-2 和 蜂鸣器 代码段 controlDevice.h&#xff08;设备控制&#xff09;smokeAlarm.c&#xff08;烟雾报警器&#xff09;buzzer.c&#xff08;蜂鸣器&#xff09;mainPro.c&#xff08;主函数&#xff09;运行结果 可燃气体传感器 MQ-2 和 蜂鸣器 代码段 …

知识蒸馏测试(使用ImageNet中的1000类dog数据,Resnet101和Resnet18分别做教师模型和学生模型)

当教师网络为resnet101,学生网络为resnet18时&#xff1a; 使用蒸馏方法训练的resnet18训练准确率都小于单独训练resnet18&#xff0c;使用蒸馏方法反而导致了下降。当hard_loss的alpha为0.7时&#xff0c;下降了1.1 当hard_loss的alpha为0.6时&#xff0c;下降了1.7说明当学生…

Unity--互动组件(Input Field)||Unity--互动组件(Scroll View)

Unity--互动组件&#xff08;Input Field&#xff09; 一个输入字段是一种方法&#xff0c;使文本控件可编辑&#xff1b; 此组件中的&#xff0c;交互&#xff0c;过渡&#xff0c;导航与文章&#xff08;Unity--互动组件&#xff08;Button&#xff09;&#xff09;中的介绍…

【数据中台】开源项目(3)-Linkis

关于 Linkis Linkis 在上层应用程序和底层引擎之间构建了一层计算中间件。通过使用Linkis 提供的REST/WebSocket/JDBC 等标准接口&#xff0c;上层应用可以方便地连接访问MySQL/Spark/Hive/Presto/Flink 等底层引擎&#xff0c;同时实现统一变量、脚本、用户定义函数和资源文件…

TCA9548A I2C 多路复用器 Arduino 使用相同地址 I2C 设备

在本教程中&#xff0c;我们将学习如何将 TCA9548A I2C 多路复用器与 Arduino 结合使用。我们将讨论如何通过整合硬件解决方案来使用多个具有相同地址的 Arduino 的 I2C 设备。通过使用 TCA9548A I2C 多路复用器&#xff0c;我们将能够增加 Arduino 的 I2C 地址范围&#xff0c…

12.1平衡树(splay),旋转操作及代码

平衡树 变量定义 tot表示结点数量&#xff0c;rt表示根的编号 v[i]表示结点i的权值 fa[i]表示结点i的父亲节点 chi[i][2]表示结点i的左右孩子 cnt[i]表示结点i的权值存在数量&#xff0c;如1123&#xff0c;v[3]1&#xff0c;则cnt[3]2;就是说i3的三号结点的权值为1&…
最新文章