Traceback (most recent call last): File "D:\untitled\优化算法.py", line 58, in <module> if fitness > particles[i]['pbest']['fitness']: KeyError: 'fitness' Process finished with exit code 1
时间: 2024-03-21 10:41:19 浏览: 68
Mac下anaconda中Spyder打开报错Traceback(most recent call last)…问题
5星 · 资源好评率100%
这个错误一般是由于 `particles[i]['pbest']` 字典中没有 'fitness' 键导致的。可以在初始化粒子群时,将所有粒子的 'fitness' 键设置为 0,例如:
```python
# 初始化粒子群
particles = []
for i in range(n):
particle = {}
particle['w1'] = np.random.uniform(x_min, x_max, size=(input_size, hidden_size))
particle['w2'] = np.random.uniform(x_min, x_max, size=(hidden_size, output_size))
particle['b1'] = np.random.uniform(x_min, x_max, size=(1, hidden_size))
particle['b2'] = np.random.uniform(x_min, x_max, size=(1, output_size))
particle['pbest'] = particle.copy()
particle['fitness'] = 0 # 添加这一行
particles.append(particle)
```
这样就可以避免 'fitness' 键不存在的问题了。
阅读全文