上面的代码补充真实值与预测值对比图、误差值和R方值
时间: 2024-03-27 22:38:54 浏览: 111
好的,下面是代码补充。需要安装matplotlib和sklearn库:
```
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.neural_network import MLPRegressor
from sklearn.metrics import mean_squared_error, r2_score
from pyswarm import pso
import matplotlib.pyplot as plt
file = "zhong.xlsx"
data = pd.read_excel(file)
# 数据预处理
scaler = MinMaxScaler(feature_range=(0, 1))
data_scaled = scaler.fit_transform(data)
X = data_scaled[:, :-1]
y = data_scaled[:, -1]
# 定义BP神经网络模型
def neural_network(w):
clf = MLPRegressor(hidden_layer_sizes=(8, 4), activation='relu', solver='lbfgs')
clf.fit(X, y)
return clf.predict(X)
# 定义粒子群算法目标函数
def objective_function(w):
return ((neural_network(w) - y) ** 2).mean()
# 使用粒子群算法优化BP神经网络模型
lb = np.zeros(8)
ub = np.ones(8)
xopt, fopt = pso(objective_function, lb, ub, maxiter=100)
# 输出预测结果
predicted = neural_network(xopt)
predicted = scaler.inverse_transform(np.concatenate((X, predicted.reshape(-1, 1)), axis=1))[:, -1]
# 计算误差值和R方值
mse = mean_squared_error(data.iloc[:, -1], predicted)
r2 = r2_score(data.iloc[:, -1], predicted)
print("均方误差:", mse)
print("R方值:", r2)
# 绘制真实值与预测值对比图
plt.plot(data.iloc[:, -1], label="真实值")
plt.plot(predicted, label="预测值")
plt.legend()
plt.show()
```
在上述代码中,我们新增了计算均方误差和R方值的代码,并使用matplotlib库绘制了真实值与预测值对比图。可以通过调整隐藏层神经元数量和迭代次数等超参数,来尝试优化预测效果。
阅读全文