import math
from random import random
import matplotlib.pyplot as plt
def func(x): #函数优化问题
res=bp1.predict()
return res
#x为公式里的x1,y为公式里面的x2
class SA:
self.func = func
self.iter = iter #内循环迭代次数,即为L =100
self.alpha = alpha #降温系数,alpha=0.99
self.T0 = T0 #初始温度T0为100
self.Tf = Tf #温度终值Tf为0.01
self.T = T0 #当前温度
self.x = [random() * 11 -5 for i in range(iter)] #随机生成100个x的值
self.y = [random() * 11 -5 for i in range(iter)] #随机生成100个y的值
self.most_best =[]
"""
random()这个函数取0到1之间的小数
如果你要取0-10之间的整数(包括0和10)就写成 (int)random()*11就可以了,11乘以零点多的数最大是10点多,最小是0点多
该实例中x1和x2的绝对值不超过5(包含整数5和-5),(random() * 11 -5)的结果是-6到6之间的任意值(不包括-6和6)
(random() * 10 -5)的结果是-5到5之间的任意值(不包括-5和5),所有先乘以11,取-6到6之间的值,产生新解过程中,用一个if条件语句把-5到5之间(包括整数5和-5)的筛选出来。
"""
self.history = {'f': [], 'T': []}
def generate_new(self, x, y): #扰动产生新解的过程
while True:
x_new = x + self.T * (random() - random())
y_new = y + self.T * (random() - random())
if (-5 <= x_new <= 5) & (-5 <= y_new <= 5):
break #重复得到新解,直到产生的新解满足约束条件
# 数组转矩阵
return x_new, y_new
def Metrospolis(self, f, f_new): #Metropolis准则
if f_new <= f:
return 1
else:
p = math.exp((f - f_new) / self.T)
if random() < p:
return 1
else:
return 0
def best(self): #获取最优目标函数值
f_list = [] #f_list数组保存每次迭代之后的值
for i in range(self.iter):
#加索引
f = self.func(self.x[i], self.y[i])
f_list.append(f)
f_best = min(f_list)
idx = f_list.index(f_best)
return f_best, idx #f_best,idx分别为在该温度下,迭代L次之后目标函数的最优解和
以下是使用模拟退火算法寻优的代码,其中我对原有的代码进行了一些修改和补充:
import math
from random import random
import matplotlib.pyplot as plt
def func(x, y): #函数优化问题
res = bp1.predict()
return res
class SA:
def __init__(self, iter=100, alpha=0.99, T0=100, Tf=0.01):
self.func = func
self.iter = iter #内循环迭代次数,即为L =100
self.alpha = alpha #降温系数,alpha=0.99
self.T0 = T0 #初始温度T0为100
self.Tf = Tf #温度终值Tf为0.01
self.T = T0 #当前温度
self.x = [random() * 11 - 5 for i in range(iter)] #随机生成100个x的值
self.y = [random() * 11 - 5 for i in range(iter)] #随机生成100个y的值
self.most_best = []
self.history = {'f': [], 'T': []}
def generate_new(self, x, y): #扰动产生新解的过程
while True:
x_new = x + self.T * (random() - random())
y_new = y + self.T * (random() - random())
if (-5 <= x_new <= 5) and (-5 <= y_new <= 5):
break #重复得到新解,直到产生的新解满足约束条件
return x_new, y_new
def Metrospolis(self, f, f_new): #Metropolis准则
if f_new <= f:
return 1
else:
p = math.exp((f - f_new) / self.T)
if random() < p:
return 1
else:
return 0
def best(self): #获取最优目标函数值
f_list = [] #f_list数组保存每次迭代之后的值
for i in range(self.iter):
f = self.func(self.x[i], self.y[i])
f_list.append(f)
f_best = min(f_list)
idx = f_list.index(f_best)
return f_best, idx
def anneal(self):
while self.T >= self.Tf:
for i in range(self.iter):
x_new, y_new = self.generate_new(self.x[i], self.y[i])
f = self.func(self.x[i], self.y[i])
f_new = self.func(x_new, y_new)
if self.Metrospolis(f, f_new):
self.x[i], self.y[i] = x_new, y_new
self.T *= self.alpha
f_best, idx = self.best()
self.most_best.append((self.x[idx], self.y[idx], f_best))
self.history['f'].append(f_best)
self.history['T'].append(self.T)
return self.most_best[-1]
if __name__ == '__main__':
sa = SA()
res = sa.anneal()
print('x:', res[0], 'y:', res[1], 'f:', res[2])
plt.plot(sa.history['T'], sa.history['f'])
plt.xlabel('Temperature')
plt.ylabel('Best f')
plt.show()
在这个代码中,我添加了一个 anneal
方法,用于实现模拟退火算法的主要逻辑。在这个方法中,我们首先对每个解进行扰动,得到新的解,然后根据 Metropolis 准则决定是否接受新解。接着,我们降低温度,更新最优解,并记录历史最优解和温度的变化情况。最后,返回最终的最优解。
在 if __name__ == '__main__':
中,我们创建了一个 SA
的实例,并调用 anneal
方法来运行模拟退火算法。最后,我们将历史最优解和温度的变化情况绘制成图表,以便于观察算法的收敛情况。
import matplotlib.pyplot as plt
我可以回答这个问题。 使用模拟退火算法进行寻优操作可以通过以下步骤实现:
以下是使用Python实现模拟退火算法的示例代码:
import random
import math
def simulatedAnnealing(objectiveFunc, initialState, tempFunc, maxIter):
currentCost = objectiveFunc(initialState)
bestState = initialState
bestCost = currentCost
currentState = initialState
for i in range(maxIter):
T = tempFunc(i)
newState = getRandomNeighbor(currentState)
newCost = objectiveFunc(newState)
deltaCost = newCost - currentCost
if (deltaCost < 0 or math.exp(-deltaCost / T) > random.random()):
currentState = newState
currentCost = newCost
if currentCost < bestCost:
bestState = currentState
bestCost = currentCost
return bestState, bestCost
def getRandomNeighbor(currentState):
# Returns a neighbor of the current state
pass
def tempFunc(i):
# Returns the temperature as a function of time
pass
def objectiveFunc(state):
# Returns the cost or objective function value of the given state
pass
# Example usage
initialState = [0, 0, 0]
bestState, bestCost = simulatedAnnealing(objectiveFunc, initialState, tempFunc, maxIter=1000)
print("Best state:", bestState)
print("Cost:", bestCost)
import math
import random
# 目标函数
def func(x, y):
# 该函数应返回可预测结果,需要根据你的优化问题实现
return ...
# 扰动函数
def perturb(x, y, T):
while True:
x_new = x + T * (random.random() - 0.5)
y_new = y + T * (random.random() - 0.5)
if (-5 <= x_new <= 5) and (-5 <= y_new <= 5):
break
return x_new, y_new
# Metropolis准则
def metropolis(f, f_new, T):
if f_new < f:
return 1
else:
p = math.exp((f - f_new) / T)
if random.random() < p:
return 1
else:
return 0
# 模拟退火算法
def simulated_annealing(T0, Tf, iter, alpha):
# 初始化状态
x = random.uniform(-5, 5)
y = random.uniform(-5, 5)
T = T0
f = func(x, y)
best_x, best_y, best_f = x, y, f
# 迭代过程
for i in range(iter):
# 产生新状态
x_new, y_new = perturb(x, y, T)
f_new = func(x_new, y_new)
# Metropolis准则决定是否接受新状态
if metropolis(f, f_new, T):
x, y, f = x_new, y_new, f_new
# 更新最优状态
if f < best_f:
best_x, best_y, best_f = x, y, f
# 降温
T = alpha * T
if T < Tf:
break
return best_x, best_y, best_f
# 其他参数
T0 = 100
Tf = 0.01
iter = 100
alpha = 0.99
# 调用模拟退火算法
best_x, best_y, best_f = simulated_annealing(T0, Tf, iter, alpha)
# 输出最优解
print("Best solution: x =", best_x, " y =", best_y, " f(x, y) =", best_f)