利用Python 实现 模拟退火算法

news2024/9/23 1:34:09

模拟退火算法

模拟退火算法流程图

  • 初始温度
    • 新温度值
      • 进入循环
        • 生成新的解
          • 按照 bound
          • 按照 constraint 
        • 计算新解与当前解的目标差异
        • 判断是否接受解
        • 判断是否更新解
      • 循环结束
    • 按照温度降低率降低温度
  • 温度小于最低温度
  • 输出结果

模拟退火算法示例代码1

min=x_1^2+2x_1-15+32x_2+4x_2^2

import numpy as np

def objective_function(x):
    return x[0]**2 + 2*x[0] - 15 + 4*4*2*x[1] + 4*x[1]**2

def simulated_annealing(objective_func, initial_solution = np.array([0, 0]), \
                        temperature = 100, min_temperature = 0.1, \
                        cooling_rate = 0.90, iter_max = 100, seed = 0):

    np.random.seed(seed)
    current_solution = initial_solution
    best_solution = current_solution

    while temperature > min_temperature:
        for j in range(iter_max):
            # 生成新的解
            new_solution = current_solution + np.random.uniform(-1, 1, len(current_solution))
            
            # 计算新解与当前解之间的目标函数值差异
            current_cost = objective_func(current_solution)
            new_cost = objective_func(new_solution)
            cost_diff = new_cost - current_cost
            
            # 判断是否接受新解
            if cost_diff < 0 or np.exp(-cost_diff / temperature) > np.random.random():
                current_solution = new_solution
            
            # 更新最优解
            if objective_func(current_solution) < objective_func(best_solution):
                best_solution = current_solution
        
        # 降低温度
        temperature *= cooling_rate
    
    return best_solution


# 调用退火算法求解最小值
best_solution = simulated_annealing(objective_function)

print(f"函数最小值: {objective_function(best_solution)} 自变量取值:{best_solution}")
  • 运行结果

模拟退火算法示例代码2

\begin{matrix} min=a_1((x_2^2-x_1^2)/3-a_1-a_2)+(a_2+a_3)(a_3+(x_1^2+x_2^2+x_2^3)/3)-(a_1+a_3)(a_3*x_1*x_2) \\ cons:5<a_1+a_2+a_3<10 \end{matrix}

import numpy as np

global x_bound 
global x_up 

x_bound = 3
x_up = 10

def fun1(p0, p1):
    return (x_up**2 - x_bound**2)/3 - p0 - p1 

def fun2(p2):
    return p2 + (x_up**2 + x_bound**2 + x_bound**3)/3

def fun3(p2):
    return (x_up**2 * x_bound**2)*p2
   
def cons(try_solution):
    return 5 < np.sum(try_solution) < 10
    
def objective_function(params):
    return params[0]*fun1(params[0], params[1]) + fun2(params[2])*(params[1] + params[2]) - fun3(params[2])*(params[0] + params[2])


def simulated_annealing(objective_func, initial_solution = np.array([0, 0, 9]), \
                        temperature = 100, min_temperature = 0.1, \
                        cooling_rate = 0.90, iter_max = 100, seed = 0):

    np.random.seed(seed)
    current_solution = initial_solution
    best_solution = current_solution

    while temperature > min_temperature:
        for j in range(iter_max):
            # 生成新的解
            FLAG = True
            
            for k in range(iter_max):
                try_solution = current_solution + np.random.uniform(-1, 1, len(current_solution))
                if cons(try_solution):
                    new_solution = try_solution
                    FLAG = False
                    break
            if FLAG:
                print(f"找不到满足约束的解 在温度{temperature}")
                break
            
            # 计算新解与当前解之间的目标函数值差异
            current_cost = objective_func(current_solution)
            new_cost = objective_func(new_solution)
            cost_diff = new_cost - current_cost
            
            # 判断是否接受新解
            if cost_diff < 0 or np.exp(-cost_diff / temperature) > np.random.random():
                current_solution = new_solution
            
            # 更新最优解
            if objective_func(current_solution) < objective_func(best_solution):
                best_solution = current_solution
        
        # 降低温度
        temperature *= cooling_rate
    
    return best_solution


# 调用退火算法求解最小值
best_solution = simulated_annealing(objective_function)

print(f"函数最小值: {objective_function(best_solution)} 自变量取值:{best_solution}")

模拟退火算法的可视化

import numpy as np
import matplotlib.pyplot as plt

global x_bound 
global x_up 

x_bound = 3
x_up = 10

def fun1(p0, p1):
    return (x_up**2 - x_bound**2)/3 - p0 - p1 

def fun2(p0, p1):
    return p1 + (p0**2 + x_bound**(p1-p0))/3

   
def cons(try_solution):
    return 5 < np.sum(try_solution) < 10
    
def objective_function(params):
    return params[0]*fun1(params[0], params[1]) + (params[0] + params[1])*fun2(params[0], params[1])

def simulated_annealing(objective_func, initial_solution = np.array([4, 4]), \
                        temperature = 100, min_temperature = 0.1, \
                        cooling_rate = 0.90, iter_max = 100, seed = 0):

    np.random.seed(seed)
    current_solution = initial_solution
    best_solution = current_solution
    RECODE_temp,RECODE_sol = [],[]
    raw_temperature = temperature
    
    while temperature > min_temperature:
        RECODE_temp.append(temperature)
        for j in range(iter_max):
            # 生成新的解
            FLAG = True
            
            for k in range(iter_max):
                try_solution = current_solution + np.random.uniform(-1, 1, len(current_solution))
                if cons(try_solution):
                    new_solution = try_solution
                    FLAG = False
                    break
            if FLAG:
                print(f"找不到满足约束的解 在温度{temperature}")
                break
            
            # 计算新解与当前解之间的目标函数值差异
            current_cost = objective_func(current_solution)
            new_cost = objective_func(new_solution)
            cost_diff = new_cost - current_cost
            
            # 判断是否接受新解
            if cost_diff < 0 or np.exp(-cost_diff / temperature) > np.random.random():
                current_solution = new_solution
            
            # 更新最优解
            if objective_func(current_solution) < objective_func(best_solution):
                best_solution = current_solution
        
        # 降低温度
        temperature *= cooling_rate
        RECODE_sol.append(best_solution)

    RECODE_temp = [raw_temperature - i for i in RECODE_temp]
    RECODE_sol = [objective_function(i) for i in RECODE_sol] 
    plt.plot(RECODE_temp, RECODE_sol)
    plt.title("sol-temp")
    plt.xlabel("temp count")
    plt.ylabel("sol")
    plt.pause(0.01)
    return best_solution


# 调用退火算法求解最小值
best_solution = simulated_annealing(objective_function)

print(f"函数最小值: {objective_function(best_solution)} 自变量取值:{best_solution}")
 

example 2sin(x)+cos(x)

import numpy as np
import matplotlib.pyplot as plt

def objective_function(params):
    return 2*np.sin(params[0]) + np.cos(params[0])

def cons(try_solution):
    return True

def simulated_annealing(objective_func, initial_solution = np.array([4, ]), \
                        temperature = 100, min_temperature = 0.1, \
                        cooling_rate = 0.90, iter_max = 100, seed = 0):

    np.random.seed(seed)
    current_solution = initial_solution
    best_solution = current_solution
    RECODE_temp,RECODE_sol = [],[]
    raw_temperature = temperature
    
    while temperature > min_temperature:
        RECODE_temp.append(temperature)
        for j in range(iter_max):
            # 生成新的解
            FLAG = True
            
            for k in range(iter_max):
                try_solution = current_solution + np.random.uniform(-1, 1, len(current_solution))
                if cons(try_solution):
                    new_solution = try_solution
                    FLAG = False
                    break
            if FLAG:
                print(f"找不到满足约束的解 在温度{temperature}")
                break
            
            # 计算新解与当前解之间的目标函数值差异
            current_cost = objective_func(current_solution)
            new_cost = objective_func(new_solution)
            cost_diff = new_cost - current_cost
            
            # 判断是否接受新解
            if cost_diff < 0 or np.exp(-cost_diff / temperature) > np.random.random():
                current_solution = new_solution
            
            # 更新最优解
            if objective_func(current_solution) < objective_func(best_solution):
                best_solution = current_solution
        
        # 降低温度
        temperature *= cooling_rate
        RECODE_sol.append(best_solution)

    RECODE_temp = [raw_temperature - i for i in RECODE_temp]
    RECODE_sol = [objective_function(i) for i in RECODE_sol] 
    plt.plot(RECODE_temp, RECODE_sol)
    plt.title("sol-temp")
    plt.xlabel("temp count")
    plt.ylabel("sol")
    plt.pause(0.01)
    return best_solution


# 调用退火算法求解最小值
best_solution = simulated_annealing(objective_function)

print(f"函数最小值: {objective_function(best_solution)} 自变量取值:{best_solution}")

 

 

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【ESP32】调试IIC功能

1.创建示例项目i2c_simple&#xff1a;VSCODE中->“查看”->”命令面板“->输入&#xff1a;Show Examples projects->选择Use current ESP-IDF(C:\Espressif\frameworks\esp-idf-v5.1)->弹出示例ESP-IDF Examples&#xff0c;选择peripherals->i2c->i2c_…

<findbugs>静态代码分析工具

背景&#xff1a; IDEA安装的findbug插件目前无法和jenkins的扫描结果保持一致&#xff0c;因为&#xff1a;没有对应jenkins上findbug的版本&#xff1b; 原理&#xff1a; 将jenkins服务器上的findbugs插件&#xff0c;拷贝到本地&#xff0c;修改build.xml内容以匹配目录…

代码随想录算法训练营第五天| 242. 有效的字母异位词,349. 两个数组的交集,202快乐数,1. 两数之和

哈希表 首先什么是 哈希表&#xff0c;哈希表&#xff08;英文名字为Hash table&#xff0c;国内也有一些算法书籍翻译为散列表&#xff0c;大家看到这两个名称知道都是指hash table就可以了&#xff09;。 那么哈希表能解决什么问题呢&#xff0c;一般哈希表都是用来快速判断…

cypress 教程

cypress 教程 cypress是一个用于Web应用程序的端到端测试框架。它是一个开源的js测试工具&#xff0c;设计的目的是Web应用程序的测试能更快速、简单和可靠。赛普斯允许开发人员编写模拟用户交互和验证应用程序行为的自动测试。 我们可以使用js或者ts来开发&#xff0c;但是j…

用牛鲨水豚赚取SUI的机会又来喽,500万SUI奖励等你来领!

刚刚结束的第一轮Bullshark Quest真是一次惊心动魄的体验&#xff01;我们非常感激社区成员的积极参与以及对Sui生态系统的关注。此轮获奖者的奖励已于美国时间2023年7月28日&#xff0c;在Quest门户网站上公布。参与者点击“Claim”即可将奖励领取至Sui钱包。请注意&#xff0…

猿创征文|弃文从工,从小白到蚂蚁工程师,我的 Java 成长之路

一、前言 1.1 背景 最近 CSDN 开展了猿创征文&#xff0c;希望博主写文章讲述自己在某个领域的技术成长历程。 之前也曾想找个机会写篇文章&#xff0c;记录下自己的成长历程。 因此&#xff0c;借着这个机会写下这篇文章。 在回顾自己的成长历程的同时&#xff0c;希望对一…

红队打靶:FourAndSix2.01打靶思路详解(vulnhub)

目录 写在开头 第一步&#xff1a;主机发现与端口扫描 第二步&#xff1a;NFS渗透 第三步&#xff1a;7z压缩包的密码破解 第四步&#xff1a;ssh私钥登录 第五步&#xff1a;lessvi提权 总结与思考 写在开头 本篇博客根据大佬红队笔记的视频进行打靶&#xff0c;详述了…

基于Caffe的静默活体检测识别分析系统

周末的时候看到一个好玩的项目就想着实际拿来使用一下&#xff0c;这个项目主要是做的是开源的跟人脸活体检测相关的内容&#xff0c;这里主要采用的是静默活体检测的方式。 人脸静默活体检测是一种用于验证人脸是真实、活体的技术&#xff0c;而不需要进行任何口头指令或特定…

13.7 CentOS 7 环境下大量创建帐号的方法

13.7.1 一些帐号相关的检查工具 pwck pwck 这个指令在检查 /etc/passwd 这个帐号配置文件内的信息&#xff0c;与实际的主文件夹是否存在等信息&#xff0c; 还可以比对 /etc/passwd /etc/shadow 的信息是否一致&#xff0c;另外&#xff0c;如果 /etc/passwd 内的数据字段错…

Linux 给用户 赋某个文件夹操作的权限(实现三权分立)

Linux 给用户 赋某个文件夹操作的权限 这里用的ubuntu16.04 一、配置网站管理员 linux文件或目录的权限分为&#xff0c;读、写、可执行三种权限。文件访问的用户类别分为&#xff0c;文件创建者、与文件创建者同组的用户、其他用户三类。 添加用户 useradd -d /var/www/htm…

解密低价正规渠道的来源:影视会员肯德基点餐直充api接口

话费充值 接口已经整合移动、联通、电信三网话费充值渠道。话费可以说是全民所需&#xff0c;对于平台引流&#xff0c;增强平台日活跃度可以提供不小的帮助。 肯德基在线点餐 接口整合了各大城市的肯德基门店&#xff0c;支持门店选择&#xff0c;在线点餐 提前点餐领取&a…

linux系统编程重点复习--线程同步

目录 复习目标&#xff1a; 1 互斥锁 1.1互斥锁的使用步骤 1.2 练习 1.3 死锁 2 读写锁 3 条件变量 4 信号量 复习目标&#xff1a; 熟练掌握互斥量的使用说出什么叫死锁以及解决方案熟练掌握读写锁的使用熟练掌握条件变量的使用理解条件变量实现的生产消费者模型理解…

Java基础篇_1.2——保留关键字、基本数据类型、基本数据类型之间的转换

​​​​​​​目录 一、保留关键字 二、Java的基本数据类型 三、引用数据类型 四、基本数据类型间的转换 隐含强制类型转换 一、保留关键字 Java该语言是用 Unicode 字符集编写的。 Java关键字是预先定义的具有特别意义的标识符&#xff0c;也被称为Java保留字&#xff0…

在k8s集群内搭建Prometheus监控平台

基本架构 Prometheus由SoundCloud发布&#xff0c;是一套由go语言开发的开源的监控&报警&时间序列数据库的组合。 Prometheus的基本原理是通过HTTP协议周期性抓取被监控组件的状态&#xff0c;任意组件只要提供对应的HTTP接口就可以接入监控。不需要任何SDK或者其他的…

YOLOv8教程系列:三、使用YOLOv8模型进行自定义数据集半自动标注

YOLOv8半自动标注 目标检测半自动标注的优点包括&#xff1a; 1.提高标注效率&#xff1a;算法能够自动标注部分数据&#xff0c;减少了人工标注的工作量&#xff0c;节省时间和资源。 2.降低成本&#xff1a;自动标注可以减少人工标注的成本&#xff0c;特别是对于大规模数据…

如何在线制作闪图?手把手教你快速生成GIF闪图

网上那种卟玲卟领的闪动GIF图片效果非常的炫丽&#xff0c;这种GIF闪图是怎么制作的呢&#xff1f;很简单&#xff0c;只需要使用专业的gif制作&#xff08;https://www.gif.cn/&#xff09;工具-GIF中文网&#xff0c;上传多张颜色、大小不同&#xff0c;内容相同的jpg、png格…

ORB-SLAM3数据集配置与评价

在ORB-SLAM3运行EuRoC和TUM-VI数据集并作以评价。EuRoC利用微型飞行器(MAV ) 收集的视觉惯性数据集&#xff0c;TUM-VI 是由实验人员手持视觉-惯性传感器收集的数据集。这两个是在视觉SLAM中比较常用的公开数据集&#xff0c;所以测试并加以记录。 文章目录 一、EuRoC数据集测…

音频转文字软件免费版让你快速完成转换

音频转文字技术是一种将音频文件转换为文本形式的技术&#xff0c;它可以帮助人们更方便地获取和处理音频信息。在实际生活和工作中&#xff0c;我们可能会遇到需要将音频转换为文字的情况&#xff0c;比如听取会议录音、收听讲座、学习外语等等。那么&#xff0c;你知道音频转…

Tinkercad 建模21个小技巧

21个Tinkercad 建模小技巧 原文 参考文章&#xff1a;在 Tinkercad 中加快设计的 22 个技巧 一起来了解一下21个Tinkercad 3D建模小技巧&#xff0c;让你快人一步。 技巧1 Copy & Paste 文件&#xff0c;整合设计 想把文件A里面的模型拷贝到文件B里面&#xff1f; 很容…

【Linux命令200例】mren一个用于重命名文件或目录的命令行工具

&#x1f3c6;作者简介&#xff0c;黑夜开发者&#xff0c;全栈领域新星创作者✌&#xff0c;2023年6月csdn上海赛道top4。 &#x1f3c6;本文已收录于专栏&#xff1a;Linux命令大全。 &#x1f3c6;本专栏我们会通过具体的系统的命令讲解加上鲜活的实操案例对各个命令进行深入…