目錄
1.算法流程簡介
2.算法核心代碼
3.算法效果展示文章來源:http://www.zghlxwxcb.cn/news/detail-707149.html
1.算法流程簡介
"""
1.設(shè)定退火算法的基礎(chǔ)參數(shù)
2.設(shè)定需要優(yōu)化的函數(shù),求解該函數(shù)的最小值/最大值
3.進行退火過程,隨機產(chǎn)生退火解并且糾正,直到冷卻
4.繪制可視化圖片進行了解退火整體過程
"""
2.算法核心代碼
#利用退火算法求解函數(shù)的極值(優(yōu)化問題)
import numpy as np
from random import random
import random
import math
import matplotlib.pyplot as plt
#設(shè)定退火算法的基礎(chǔ)參數(shù)
x_min,x_max=(-3,3)#x的取值范圍
alpha=0.99#降溫系數(shù)為0.99
bg_temp=100#起始溫度
ed_temp=0.01#最終溫度(可設(shè)可不設(shè))
cycle_number=500#循環(huán)次數(shù)
#設(shè)定需要優(yōu)化的函數(shù),求解該函數(shù)的最小值
"""
需要運用的化直接修改函數(shù)即可.
不過需要注意定義域的問題,主動修改一下定義域就行
"""
def opt_fun(x):
y=11*np.sin(2*x)+7*np.cos(5*x)
return y
#由于沒有具體的數(shù)據(jù),我們直接隨機設(shè)置值就行隨機產(chǎn)生初始值
#隨機產(chǎn)生本次退火解
def new_result(x):
x1=x+bg_temp*random.uniform(-1,1)
#退火解的合理性檢查并且糾正:
if x_min<=x1<=x_max:
return x1
elif x1<x_min:
add_min=random.uniform(-1,1)
return add_min*x_min+(1-add_min)*x
else:
add_max=random.uniform(-1,1)
return add_max*x_max+(1-add_max)*x
def draw_picture(x):
plt.cla()
#繪圖的時候這里可以進行修改
#注意這里y的取值范圍[-25,25]要大體預(yù)估一下
plt.axis([x_min-1,x_max+1,-25,25])
m=np.arange(x_min,x_max,0.0001)
plt.plot(m,opt_fun(m),color='red')
plt.plot(x,opt_fun(x),marker='*',color='b',markersize='8')
plt.title('Current Temperature={}'.format(T))
plt.pause(0.1)
#設(shè)定接受概率函數(shù)
def p(x,x1):
return math.exp(-abs(opt_fun(x)-opt_fun(x1))/T)
#循環(huán)退火過程,直到冷卻求出最優(yōu)解
def Annealing_cycle():
global T
count_number=0
T=bg_temp
x=random.uniform(x_min,x_max)
print("*******************************************************************************************************************")
while T>ed_temp:
draw_picture(x)
for i in range(cycle_number):
x1=new_result(x)
#求解最小值的過程
if opt_fun(x)>=opt_fun(x1):
x=x1
else:
if random.random()<=p(x,x1):
x=x1
else:
continue
T=T*alpha
count_number=count_number+1
print("當前執(zhí)行第{}".format(count_number),"次退火過程"," 當前退火溫度為:{}".format(T)," 當前最優(yōu)值:{}".format(opt_fun(x)))
print("*******************************************************************************************************************")
print("本次退火優(yōu)化過程共執(zhí)行{}".format(count_number),"次求得的最優(yōu)解為:{}".format(opt_fun(x)))
print("*******************************************************************************************************************")
Annealing_cycle()
3.算法效果展示
文章來源地址http://www.zghlxwxcb.cn/news/detail-707149.html
到了這里,關(guān)于數(shù)學建模--退火算法求解最值的Python實現(xiàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!