Traceback (most recent call last): File "D:\untitled\粒子群优化算法.py", line 34, in <module> xopt, fopt = pso(loss_function, bounds=bounds, args=(X, y)) TypeError: pso() got an unexpected keyword argument 'bounds' Process finished with exit code 1
时间: 2023-12-22 15:06:07 浏览: 110
Mac下anaconda中Spyder打开报错Traceback(most recent call last)…问题
5星 · 资源好评率100%
这个错误提示说明你的`pyswarm`库版本较低,不支持`bounds`参数。可以尝试升级`pyswarm`库的版本,或者使用`lb`和`ub`参数代替`bounds`参数来设置搜索范围。修改后的代码如下:
```python
import numpy as np
import pandas as pd
from sklearn.neural_network import MLPRegressor
from pyswarm import pso
# 读取数据
data = pd.read_csv('tomato.csv')
# 数据预处理
X = data.iloc[:, :-1]
y = data.iloc[:, -1]
# 定义神经网络模型
def nn_model(x, w1, w2, b1, b2):
a1 = np.dot(x, w1) + b1
z1 = np.tanh(a1)
a2 = np.dot(z1, w2) + b2
return a2
# 定义损失函数
def loss_function(params, *args):
x, y = args
w1, w2, b1, b2 = params
y_pred = nn_model(x, w1, w2, b1, b2)
mse = np.mean((y - y_pred) ** 2)
return mse
# 定义粒子群算法的搜索范围
lb = [-1, -1, -1, -1]
ub = [1, 1, 1, 1]
# 运行粒子群算法
xopt, fopt = pso(loss_function, lb=lb, ub=ub, args=(X, y))
# 用最优参数组合构建神经网络模型
w1 = np.array([xopt[0], xopt[1]]).reshape(2, 1)
w2 = np.array([xopt[2], xopt[3]]).reshape(1, 2)
b1 = 0
b2 = 0
model = MLPRegressor(hidden_layer_sizes=(1,), activation='tanh', solver='lbfgs', random_state=1)
model.coefs_ = [w1, w2]
model.intercepts_ = [b1, b2]
# 预测结果
y_pred = model.predict(X)
print('预测结果:', y_pred)
```
这个版本的代码中,我们使用`lb`和`ub`参数分别代表搜索范围的上下限。
阅读全文