Python实战开发及案例分析(12)—— 模拟退火算法

        模拟退火算法(Simulated Annealing)是一种概率搜索算法,源自于金属退火过程。在金属退火中,通过缓慢降低温度,金属内部的原子能够从高能态逐步达到较低能态。模拟退火算法利用类似的原理,通过随机搜索和概率接受策略来找到近似最优解。

模拟退火算法的原理

  • 目标:寻找最小化或最大化目标函数的近似最优解。
  • 温度:从高温逐渐降到低温。
  • 状态变换:通过随机变换产生邻域解。
  • 接受概率:以一定概率接受当前解,概率与温度和能量变化相关。

伪代码

1. 初始化当前解 s0,并设定初始温度 T0
2. while 当前温度 T > Tmin:
    3. 随机产生新的解 s'(当前解的邻域解)
    4. 计算能量差 ΔE = f(s') - f(s)
    5. if ΔE < 0:
        6. 接受新的解 s = s'
    7. else:
        8. 以概率 P(ΔE, T) = exp(-ΔE / T) 接受新的解 s = s'
    9. 降低温度 T = T * α
10. 返回最优解

Python 实现:模拟退火算法

示例问题:求解最小化 Rastrigin 函数

Rastrigin 函数是一个常见的多峰函数,用于测试优化算法的全局搜索能力。函数公式如下:

𝑓(𝑥,𝑦)=10×2+(𝑥2−10×cos⁡(2𝜋𝑥))+(𝑦2−10×cos⁡(2𝜋𝑦))

Python 实现:

import math
import random
import numpy as np
import matplotlib.pyplot as plt

# Rastrigin 函数
def rastrigin(x):
    A = 10
    return A * len(x) + sum([(xi**2 - A * math.cos(2 * math.pi * xi)) for xi in x])

# 邻域解生成函数
def random_neighbor(x, bounds, step_size=0.5):
    return [min(max(xi + random.uniform(-step_size, step_size), bounds[i][0]), bounds[i][1]) for i, xi in enumerate(x)]

# 模拟退火算法
def simulated_annealing(objective, bounds, T0=1000, Tmin=1e-5, alpha=0.9, max_iter=1000):
    # 随机初始化起点
    x = [random.uniform(b[0], b[1]) for b in bounds]
    best_solution = x
    best_score = objective(x)
    current_solution = x
    current_score = best_score
    T = T0
    scores = []

    for _ in range(max_iter):
        if T < Tmin:
            break

        # 生成新邻域解
        neighbor = random_neighbor(current_solution, bounds)
        neighbor_score = objective(neighbor)

        # 接受概率计算
        if neighbor_score < current_score:
            current_solution = neighbor
            current_score = neighbor_score
        else:
            p = math.exp((current_score - neighbor_score) / T)
            if random.random() < p:
                current_solution = neighbor
                current_score = neighbor_score

        # 更新最优解
        if current_score < best_score:
            best_solution = current_solution
            best_score = current_score

        scores.append(best_score)

        # 降低温度
        T *= alpha

    return best_solution, best_score, scores

# 定义搜索空间(x 和 y 的范围)
bounds = [(-5.12, 5.12), (-5.12, 5.12)]

# 使用模拟退火算法最小化 Rastrigin 函数
best_solution, best_score, scores = simulated_annealing(rastrigin, bounds)

print("Best solution:", best_solution)
print("Best score:", best_score)

# 绘制优化过程中的得分变化
plt.plot(scores)
plt.xlabel("Iteration")
plt.ylabel("Best Score")
plt.title("Simulated Annealing Optimization Process")
plt.show()

结果分析

        通过运行以上代码,我们可以观察到模拟退火算法的搜索过程,并找到接近最优解的结果:

  • 最优解Best solution
  • 最优值Best score
  • 优化过程scores 显示了得分随迭代次数的变化趋势。

结论

        模拟退火算法是一种用于全局优化的启发式搜索方法,能够有效地找到复杂多峰函数的近似最优解。它的成功取决于温度衰减率和接受概率策略等参数的选择。通过调整这些参数,可以提高算法的搜索效率和性能。

模拟退火算法参数调优

模拟退火算法的性能很大程度上取决于温度衰减率、初始温度和步长的选择。下面是这些参数的常见选择策略:

  1. 初始温度 (T0)

    • 设定得足够高,以确保在开始时接受不好的解,从而允许算法进行全局搜索。
    • 常见值:1000、5000等。
  2. 温度衰减率 (alpha)

    • 温度每次迭代后的衰减比率。
    • 常见值:0.9 ~ 0.99。
  3. 终止温度 (Tmin)

    • 温度降低到何值以下停止搜索。
    • 常见值:1e-5 ~ 1e-8。
  4. 步长 (step_size)

    • 用于生成新邻域解的随机步长。
    • 常见值:0.1 ~ 1.0。

多目标优化问题

        多目标优化问题(Multi-objective Optimization Problem,MOP)是指同时优化多个相互冲突的目标。在模拟退火算法中,常见的多目标优化方法包括:

  • 权重和法:为每个目标设置权重,将多个目标组合成一个加权目标函数。
  • 帕累托优化:寻找帕累托最优解集,并通过模拟退火进行搜索。

案例分析:求解多目标优化问题

示例问题:双目标优化的 ZDT1 问题

        ZDT1 问题是双目标优化问题的一个经典例子。目标函数如下:

                ​​​​​​​        f_{1}\left ( x \right )=x_{1}

                        f_{2}\left ( x \right )=g\left ( x \right )\cdot \left ( 1-\sqrt{\frac{x_{1}}{g\left ( x \right )}} \right )

                        g\left ( x \right )=1+9\cdot \frac{\sum_{i=2}^{n}x_{i}}{n-1}

        约束条件:

        ​​​​​​​        ​​​​​​​        0\leq x_{i}\leq 1

Python 实现:

import math
import random
import numpy as np
import matplotlib.pyplot as plt

# ZDT1 问题
def zdt1(x):
    f1 = x[0]
    g = 1 + 9 * sum(x[1:]) / (len(x) - 1)
    f2 = g * (1 - math.sqrt(f1 / g))
    return f1, f2

# 权重和目标函数
def weighted_sum(x, w):
    f1, f2 = zdt1(x)
    return w[0] * f1 + w[1] * f2

# 邻域解生成函数
def random_neighbor_multi(x, bounds, step_size=0.1):
    return [min(max(xi + random.uniform(-step_size, step_size), bounds[i][0]), bounds[i][1]) for i, xi in enumerate(x)]

# 多目标模拟退火算法
def simulated_annealing_multi(objective, bounds, w, T0=1000, Tmin=1e-5, alpha=0.9, max_iter=1000):
    # 随机初始化起点
    x = [random.uniform(b[0], b[1]) for b in bounds]
    best_solution = x
    best_score = objective(x, w)
    current_solution = x
    current_score = best_score
    T = T0
    scores = []

    for _ in range(max_iter):
        if T < Tmin:
            break

        # 生成新邻域解
        neighbor = random_neighbor_multi(current_solution, bounds)
        neighbor_score = objective(neighbor, w)

        # 接受概率计算
        if neighbor_score < current_score:
            current_solution = neighbor
            current_score = neighbor_score
        else:
            p = math.exp((current_score - neighbor_score) / T)
            if random.random() < p:
                current_solution = neighbor
                current_score = neighbor_score

        # 更新最优解
        if current_score < best_score:
            best_solution = current_solution
            best_score = current_score

        scores.append(best_score)

        # 降低温度
        T *= alpha

    return best_solution, scores

# 定义搜索空间
bounds = [(0, 1) for _ in range(30)]
weights = [0.5, 0.5]

# 使用多目标模拟退火算法最小化 ZDT1 问题
best_solution, scores = simulated_annealing_multi(weighted_sum, bounds, weights)

# 打印结果
f1, f2 = zdt1(best_solution)
print("Best solution:", best_solution)
print("Objective values:", (f1, f2))

# 绘制优化过程中的得分变化
plt.plot(scores)
plt.xlabel("Iteration")
plt.ylabel("Best Weighted Score")
plt.title("Simulated Annealing Multi-objective Optimization Process")
plt.show()

结论

        通过优化 ZDT1 问题,我们了解到模拟退火算法在多目标优化问题上的适用性。重要的是选择适当的参数和策略,包括权重分配、温度衰减和步长等。模拟退火算法在全局搜索上具有广泛的应用潜力,可以有效地应对高维优化问题。

        在继续深入探讨模拟退火算法的优化和应用过程中,让我们进一步扩展内容,包括:

  1. 非线性函数优化:优化非线性函数以显示模拟退火算法的多功能性。
  2. 组合优化问题:应用模拟退火算法于旅行商问题(TSP)。
  3. 参数调优:展示如何通过调优参数来改善算法性能。

非线性函数优化

        在非线性函数优化问题中,我们可以尝试优化 Himmelblau 函数,这是一个常见的多极值函数,定义如下:

                        f\left ( x,y \right )=\left ( x^{2}+y-11 \right )^{2}+\left (x+y^{2}-7 \right )^{2}

Python 实现:
import random
import math
import numpy as np
import matplotlib.pyplot as plt

# Himmelblau 函数
def himmelblau(x):
    return (x[0]**2 + x[1] - 11)**2 + (x[0] + x[1]**2 - 7)**2

# 邻域解生成函数
def random_neighbor(x, bounds, step_size=0.5):
    return [min(max(xi + random.uniform(-step_size, step_size), bounds[i][0]), bounds[i][1]) for i, xi in enumerate(x)]

# 模拟退火算法
def simulated_annealing(objective, bounds, T0=1000, Tmin=1e-5, alpha=0.9, max_iter=1000):
    # 随机初始化起点
    x = [random.uniform(b[0], b[1]) for b in bounds]
    best_solution = x
    best_score = objective(x)
    current_solution = x
    current_score = best_score
    T = T0
    scores = []

    for _ in range(max_iter):
        if T < Tmin:
            break

        # 生成新邻域解
        neighbor = random_neighbor(current_solution, bounds)
        neighbor_score = objective(neighbor)

        # 接受概率计算
        if neighbor_score < current_score:
            current_solution = neighbor
            current_score = neighbor_score
        else:
            p = math.exp((current_score - neighbor_score) / T)
            if random.random() < p:
                current_solution = neighbor
                current_score = neighbor_score

        # 更新最优解
        if current_score < best_score:
            best_solution = current_solution
            best_score = current_score

        scores.append(best_score)

        # 降低温度
        T *= alpha

    return best_solution, best_score, scores

# 定义搜索空间
bounds = [(-5, 5), (-5, 5)]

# 使用模拟退火算法最小化 Himmelblau 函数
best_solution, best_score, scores = simulated_annealing(himmelblau, bounds)

print("Best solution:", best_solution)
print("Best score:", best_score)

# 绘制优化过程中的得分变化
plt.plot(scores)
plt.xlabel("Iteration")
plt.ylabel("Best Score")
plt.title("Simulated Annealing Optimization Process (Himmelblau)")
plt.show()

组合优化问题:旅行商问题(TSP)

        旅行商问题(Traveling Salesman Problem,TSP)是组合优化问题中的经典问题。目标是在给定的城市集合中,找到访问所有城市且回到出发点的最短路径。

Python 实现:
import random
import math
import matplotlib.pyplot as plt

# 计算两城市之间的距离
def distance(city1, city2):
    return math.sqrt((city1[0] - city2[0])**2 + (city1[1] - city2[1])**2)

# 计算总路径长度
def total_distance(tour, cities):
    return sum(distance(cities[tour[i]], cities[tour[i + 1]]) for i in range(len(tour) - 1)) + distance(cities[tour[0]], cities[tour[-1]])

# 邻域解生成函数
def random_neighbor_tsp(tour):
    new_tour = tour[:]
    i, j = random.sample(range(len(tour)), 2)
    new_tour[i], new_tour[j] = new_tour[j], new_tour[i]
    return new_tour

# 模拟退火算法
def simulated_annealing_tsp(cities, T0=1000, Tmin=1e-5, alpha=0.99, max_iter=1000):
    tour = list(range(len(cities)))
    random.shuffle(tour)
    best_solution = tour
    best_score = total_distance(tour, cities)
    current_solution = tour
    current_score = best_score
    T = T0
    scores = []

    for _ in range(max_iter):
        if T < Tmin:
            break

        # 生成新邻域解
        neighbor = random_neighbor_tsp(current_solution)
        neighbor_score = total_distance(neighbor, cities)

        # 接受概率计算
        if neighbor_score < current_score:
            current_solution = neighbor
            current_score = neighbor_score
        else:
            p = math.exp((current_score - neighbor_score) / T)
            if random.random() < p:
                current_solution = neighbor
                current_score = neighbor_score

        # 更新最优解
        if current_score < best_score:
            best_solution = current_solution
            best_score = current_score

        scores.append(best_score)

        # 降低温度
        T *= alpha

    return best_solution, best_score, scores

# 随机生成城市坐标
random.seed(0)
num_cities = 20
cities = [(random.uniform(0, 100), random.uniform(0, 100)) for _ in range(num_cities)]

# 使用模拟退火算法解决 TSP
best_solution, best_score, scores = simulated_annealing_tsp(cities)

print("Best solution:", best_solution)
print("Best score:", best_score)

# 绘制优化过程中的得分变化
plt.plot(scores)
plt.xlabel("Iteration")
plt.ylabel("Best Score")
plt.title("Simulated Annealing Optimization Process (TSP)")
plt.show()

# 绘制 TSP 最优路径
x = [cities[i][0] for i in best_solution] + [cities[best_solution[0]][0]]
y = [cities[i][1] for i in best_solution] + [cities[best_solution[0]][1]]
plt.plot(x, y, marker='o')
plt.xlabel("X Coordinate")
plt.ylabel("Y Coordinate")
plt.title("Optimal Tour (TSP)")
plt.show()

结论

        模拟退火算法通过不断地接受或拒绝新解来达到全局优化的目标。我们展示了如何使用模拟退火算法优化非线性函数、组合优化问题,并且通过参数调优进一步优化了算法性能。对于特定问题来说,模拟退火算法的成功取决于参数设置以及随机搜索策略的选择。

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

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

相关文章

Samtec连接器应用科普 | 连接智能工厂中的AI

【摘要/前言】 本文是系列的第一部分&#xff0c;我们将探讨人工智能在工业领域的作用。 人工智能&#xff08;AI&#xff09;的话题最近成为头条新闻&#xff0c;因为最新一代基于云的人工智能工具有望为机器的力量带来重大飞跃。在所有关于人工智能将如何影响我们的讨论中&…

Android内核之Binder消息处理:binder_transaction用法实例(七十三)

简介&#xff1a; CSDN博客专家&#xff0c;专注Android/Linux系统&#xff0c;分享多mic语音方案、音视频、编解码等技术&#xff0c;与大家一起成长&#xff01; 优质专栏&#xff1a;Audio工程师进阶系列【原创干货持续更新中……】&#x1f680; 优质专栏&#xff1a;多媒…

overflow:hidden对解决外边距塌陷的个人理解

外边距塌陷&#xff1a; 子元素的上外边距大于父元素的上外边距&#xff0c;导致边距折叠&#xff0c;取两者之间最大值&#xff0c;即子元素外边距&#xff0c;导致父元素上外边距失效。 解决办法&#xff1a;在父元素样式添加overflow:hidden;或者border:1px solid black;(不…

Python数据分析实战

文章目录 第1关&#xff1a;读取MoMA数据集第2关&#xff1a;计算艺术家年龄第3关&#xff1a;把年龄换算成年代第4关&#xff1a;总结年代数据第5关&#xff1a;将变量插入字符串第6关&#xff1a;创建艺术家频率表第7关&#xff1a;创建显示艺术家信息的函数第8关&#xff1a…

Ubuntu下halcon软件的下载安装

由于工作需求&#xff0c;点云配准需要使用halcon进行实现&#xff0c;并且将该功能放入QT界面中 1.下载halcon 进入halcon官网进行下载 官网链接&#xff1a;https://www.mvtec.com/products/halcon/ 注意&#xff1a;要注册登陆之后才能进行下载 接着点击Downloads->H…

SOCKET编程(3):相关结构体与函数

相关结构体与函数 sockaddr、sockaddr_in结构体 sockaddr和sockaddr_in详解 struct sockaddr共16字节&#xff0c;协议族(family)占2字节&#xff0c;IP地址和端口号在sa_data字符数组中 /* Structure describing a generic socket address. */ struct sockaddr {__SOCKADDR…

Apache POI入门学习

Apache POI入门学习 官网地址 excel中使用到的类读取excel表格内容表格内容maven依赖方式一测试结果 方式二测试结果 向excel中写入数据方式一方式二方式三测试结果 从 Excel 工作表中的公式单元格读取数据测试结果 Excel 工作表中写入公式单元格从受密码保护的Excel中读取数据…

Apple 发布新款 iPad Pro 和 iPad Air:性能和设计的巨大飞跃

Apple 发布新款 iPad Pro 和 iPad Air&#xff1a;性能和设计的巨大飞跃 概述 苹果公司最近的“Let Loose”活动在科技界掀起了轩然大波&#xff0c;推出了最新的 iPad Pro 和 iPad Air 型号&#xff0c;在性能、设计和功能方面取得了前所未有的改进。在本文中&#xff0c;我…

【XR806开发板试用】使用FDCM操作Flash记录开机次数

一、寻找系统分配的自定义用户数据地址 &#xff08;1&#xff09;XR806的Flash布局 如图1所示&#xff0c;FLASH的布局有两种&#xff1a; 1、没有开启OTA模式&#xff1b;Image1PaddingSysinfo 2、开启OTA模式&#xff1b;Image1PaddingSysinfoOTA area Image2 Padding 如图…

智算中心“火”了?引领算力发展新潮流

去年大模型的空前发展&#xff0c;人工智能也终于迎来了属于自己的“文艺复兴”&#xff0c;众多的模型相继发布&#xff0c;继而催生了整个行业对于智能算力需求的激增。 市场需求与技术驱动仿佛现实世界的左右脚&#xff0c;催动着世界文明的齿轮向前滚动。在全球经济角逐日…

django中的cookie与session

获取cookie request.COOKIE.GET 使用cookie response.set-cookie views.py from django.http import HttpResponse from django.shortcuts import render# Create your views here. def cookie_test(request):r HttpResponse("hello world")r.set_cookie(lan, py…

AQ6360 横河 光谱分析仪精华帖,收藏保存

AQ6360是一款由日本横河&#xff08;YOKOGAWA&#xff09;生产的光谱分析仪&#xff0c;其主要技术参数包括波长范围、波长精度和波长线性度等。AQ6360的波长范围为1200~1650nm &#xff0c;具有较高的波长精度&#xff0c;在1520~1580nm范围内为0.02nm&#xff0c;在1580~1620…

Colab/PyTorch - 001 PyTorch Basics

Colab/PyTorch - 001 PyTorch Basics 1. 源由2. PyTorch库概览3. 处理过程2.1 数据加载与处理2.2 构建神经网络2.3 模型推断2.4 兼容性 3. 张量介绍3.1 构建张量3.2 访问张量元素3.3 张量元素类型3.4 张量转换&#xff08;NumPy Array&#xff09;3.5 张量运算3.6 CPU v/s GPU …

从0开始学习python(六)

目录 前言 1、循环结构 1.1 遍历循环结构for 1.2 无限循环结构while 总结 前言 上一篇文章我们讲到了python的顺序结构和分支结构。这一章继续往下讲。 1、循环结构 在python中&#xff0c;循环结构分为两类&#xff0c;一类是遍历循环结构for&#xff0c;一类是无限循环结…

【工具推荐定制开发】一款轻量的批量web请求命令行工具支持全平台:hey,基本安装、配置、使用

背景 在开发 Web 应用的过程中&#xff0c;作为开发人员&#xff0c;为了确认接口的性能能够达到要求&#xff0c;我们往往需要一个接口压测工具&#xff0c;帮助我们快速地对我们所提供的 Web 服务发起批量请求。在接口联调的过程中&#xff0c;我们通常会用 Postman 等图形化…

气死!又被数据骗了!

做数据分析的人做的久了&#xff0c;就会自然而然产生一种想法&#xff0c;认为数据展示出来的东西一定是正确的。毕竟如果连我们自己都质疑数据分析的权威性和说服力&#xff0c;那我们数据分析人的工作不就成了白费功夫了嘛。 一开始&#xff0c;我也认为这是一条不可撼动的…

JVM认识之垃圾收集算法

一、标记-清除算法 1、定义 标记-清除算法是最基础的垃圾收集算法。它分为标记和清除两个阶段。先标记出所有需要回收的对象&#xff08;即垃圾&#xff09;&#xff0c;在标记完成后再统一回收所有垃圾对象。 2、优点和缺点 优点&#xff1a;实现简单缺点&#xff1a; 可能…

C++类和对象详解(一)

目录 面向过程和面向对象初步认识类的引入类的定义类的两种定义方式声明和定义全部放在类体中 声名定义分离 类的作用域成员变量命名规则建议访问限定符 类的封装类的实例化类对象模型类的对象大小的计算扩展 结构体内存对齐规则 感谢各位大佬对我的支持,如果我的文章对你有用,…

Linux系统一步一脚印式学习

Linux操作系统具有许多特点和优势。首先&#xff0c;它是开放源代码的&#xff0c;也就意味着任何人都可以对源代码进行查看和修改。其次&#xff0c;可以同时支持多个用户且可以同时执行多个任务&#xff0c;此外&#xff0c;Linux操作系统也非常稳定和安全。相对于其他操作系…

MyBatis认识

一、定义 MyBatis是一款优秀的持久层框架&#xff0c;它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO&#xff08;Plain Old Java O…