如何将每次迭代中每轮的结果也输出
时间: 2024-03-09 09:48:28 浏览: 188
好的,您希望在每轮迭代结束后,输出该轮迭代的结果。为了实现这个功能,您需要在每轮迭代结束后,循环遍历种群中的每个个体,将它们的目标函数值和解向量都打印出来。可以在每次迭代结束后添加以下代码:
```python
# 输出本轮迭代的结果
print("Iteration", rounds, "result:")
for solution in optimizer.ask():
print(" Value:", solution.value, " Parameters:", solution.params)
```
这段代码将输出当前迭代的轮数,然后循环遍历种群中的每个个体,将它们的目标函数值和解向量都打印出来。`solution.value`表示个体的目标函数值,`solution.params`表示个体的解向量。将它们输出即可。完整代码如下所示:
```python
rounds = 0
while True:
rounds += 1
# 生成一个新的种群,每个个体是一个解向量
solutions = []
for _ in range(optimizer.population_size):
x = optimizer.ask()
x[0] = int(x[0])
x[1] = int(x[1])
if (x[0] == 1 and x[1] in [1, 51]) or (x[0] == 51 and x[1] in [1, 51]) or (x[0] == 26 and x[1] == 26):
pass
else:
value = quadratic(x[0], x[1], x[2], x[3])
if (x[0] == 1 and x[1] in [1, 51]) or (x[0] == 51 and x[1] in [1, 51]) or (x[0] == 26 and x[1] == 26):
pass
else:
solutions.append((x, value))
# 检查解向量个数是否等于种群大小
if len(solutions) != optimizer.population_size:
# 随机生成一些解向量,补足不足的部分
while len(solutions) < optimizer.population_size:
x = [random.randint(Min_pump_zcjj, Max_pump_zcjj), random.randint(Min_pump_bdljd, Max_pump_bdljd), random.uniform(Min_pump_bdwz, Max_pump_bdwz), random.uniform(Min_pump_skhd, Max_pump_skhd)]
value = quadratic(x[0], x[1], x[2], x[3])
solutions.append((x, value))
# 计算每个个体的目标函数值,并存储在solutions列表中
optimizer.tell(solutions)
# 输出本轮迭代的结果
print("Iteration", rounds, "result:")
for solution in optimizer.ask():
print(" Value:", solution.value, " Parameters:", solution.params)
```
现在,每轮迭代结束后,都会输出该轮迭代的结果。请注意,我将原来的`optimizer.ask()`改为了`optimizer.ask(return_dict=True)`,这是因为返回字典格式可以更方便地遍历个体的目标函数值和解向量。
阅读全文