请在上述提供的几段代码的基础上,继续写代码,求出最优解和最优解向量
时间: 2024-03-12 11:44:15 浏览: 62
并行计算最优解
4星 · 用户满意度95%
好的,接下来我给出完整代码来求解最优解和最优解向量:
```
import numpy as np
import pickle
from cma import CMAEvolutionStrategy as CMA
def quadratic(bd_X, bd_Y, x3, x4):
x1 = 0.25*(((DX*(bd_X-1))**2 + (DY*(bd_Y-1))**2)**0.5+ ((DX*(51-bd_X))**2 + (DY*(bd_Y-1))**2)**0.5 + ((DX*(bd_X-1))**2 + (DY*(51-bd_Y))**2)**0.5 + ((DX*(51-bd_X))**2 + (DY*(51-bd_Y))**2)**0.5)
x2 = (((bd_X-mbjx)**2 + (bd_Y-mbjy)**2 )**0.5)*DX
x5 = train_optimize2[4]
x6 = train_optimize2[5]
x7 = train_optimize2[6]
x8 = train_optimize2[7]
x9 = train_optimize2[8]
x10 = train_optimize2[9]
x11 = train_optimize2[10]
x12 = train_optimize2[11]
x13 = train_optimize2[12]
x14 = train_optimize2[13]
x15 = train_optimize2[14]
x16 = train_optimize2[15]
x17 = train_optimize2[16]
x18 = train_optimize2[17]
x19 = train_optimize2[18]
with open('regressor_model.pkl', 'rb') as f:
model = pickle.load(f)
x_train = np.array([[x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14,x15,x16,x17,x18,x19]])
y_predict = model.predict(x_train)
Y = y_predict
return -Y
def main():
# X坐标束条件
Min_pump_zcjj = 26
Max_pump_zcjj = 51
# Y坐标约束条件
Min_pump_bdljd = 26
Max_pump_bdljd = 51
# 靶点位置约束条件
Min_pump_bdwz = 0
Max_pump_bdwz = 1
# 射孔厚度约束条件
Min_pump_skhd = 1
Max_pump_skhd = 5
bounds = np.array([[Min_pump_zcjj, Max_pump_zcjj], [Min_pump_bdljd, Max_pump_bdljd],[Min_pump_bdwz, Max_pump_bdwz],[Min_pump_skhd, Max_pump_skhd]])
target = -(train_optimize2[19])
# 定义你的优化时间限制,输入是一个数值,表示你想要优化的最长时间(秒)
timeout = 30
optimizer = CMA(mean=np.mean(bounds, axis=1), sigma=1, bounds=bounds, seed=0)
while True:
solutions = optimizer.ask()
fitness_list = []
for s in solutions:
fitness_list.append(quadratic(*s))
optimizer.tell(solutions, fitness_list)
best_index = np.argmin(fitness_list)
best_fit = fitness_list[best_index]
best_sol = solutions[best_index]
if -best_fit < target or optimizer.countiter >= timeout:
break
return best_sol, -best_fit
if __name__ == '__main__':
train_optimize2 = [26.0, 26.0, 0.0, 1.0, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.735]
DX = 0.5
DY = 0.5
mbjx = 30.5
mbjy = 30.5
best_sol, best_fit = main()
print("最优解向量为:", best_sol)
print("最优解为:", best_fit)
```
在这段代码中,首先我们导入了必要的库,然后定义了目标函数quadratic()和优化函数main(),其中目标函数的参数和实现与之前一致,而main()函数则是将目标函数与优化算法结合起来,求出最优解和最优解向量。在main()函数中,我们首先定义了X坐标、Y坐标、靶点位置和射孔厚度的约束条件,并将它们组成一个二维数组bounds;然后定义了目标函数的值target和优化时间限制timeout;最后创建了一个CMA对象optimizer,并在while循环中进行迭代,直到找到满足目标函数要求或达到时间限制为止。在每次迭代中,我们通过调用ask()方法获取一组新的解,并调用目标函数计算它们的适应度,然后将解和适应度传递给tell()方法,让优化算法进行更新。在每次迭代结束后,我们通过调用np.argmin()方法找到当前最优解的索引,然后保存最优解和最优解向量,并检查是否满足终止条件。最后,我们在if语句中返回最优解向量和最优解的负数值。最后,在代码的最后一行,我们输出最优解向量和最优解的负数值。
阅读全文