import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from keras.models import Sequential from keras.layers import Dense from pyswarm import pso import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler from sklearn.metrics import mean_absolute_error from sklearn.metrics import mean_squared_error from sklearn.metrics import r2_score file = "zhong.xlsx" data = pd.read_excel(file) #reading file X=np.array(data.loc[:,'种植密度':'有效积温']) y=np.array(data.loc[:,'产量']) y.shape=(185,1) # 将数据集分为训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.25, random_state=10) SC=StandardScaler() X_train=SC.fit_transform(X_train) X_test=SC.fit_transform(X_test) y_train=SC.fit_transform(y_train) y_test=SC.fit_transform(y_test) print("X_train.shape:", X_train.shape) print("X_test.shape:", X_test.shape) print("y_train.shape:", y_train.shape) print("y_test.shape:", y_test.shape) # 定义BP神经网络模型 def nn_model(X): model = Sequential() model.add(Dense(8, input_dim=X_train.shape[1], activation='relu')) model.add(Dense(12, activation='relu')) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') return model # 定义适应度函数 def fitness_func(X): model = nn_model(X) model.fit(X_train, y_train, epochs=60, verbose=2) score = model.evaluate(X_test, y_test, verbose=2) print(score) # 定义变量的下限和上限 lb = [5, 5] ub = [30, 30] # 利用PySwarm库实现改进的粒子群算法来优化BP神经网络预测模型 result = pso(fitness_func, lb, ub) # 输出最优解和函数值 print('最优解:', result[0]) print('最小函数值:', result[1]) mpl.rcParams["font.family"] = "SimHei" mpl.rcParams["axes.unicode_minus"] = False # 绘制预测值和真实值对比图 model = nn_model(X) model.fit(X_train, y_train, epochs=60, verbose=2) y_pred = model.predict(X_test) y_true = SC.inverse_transform(y_test) y_pred=SC.inverse_transform(y_pred) plt.figure() plt.plot(y_true,"bo-",label = '真实值') plt.plot(y_pred,"ro-", label = '预测值') plt.title('神经网络预测展示') plt.xlabel('序号') plt.ylabel('产量') plt.legend(loc='upper right') plt.show() print("R2 = ",r2_score(y_test, y_pred)) # R2 # 绘制损失函数曲线图 model = nn_model(X) history = model.fit(X_train, y_train, epochs=60, validation_data=(X_test, y_test), verbose=2) plt.plot(history.history['loss'], label='train') plt.plot(history.history['val_loss'], label='test') plt.legend() plt.show() mae = mean_absolute_error(y_test, y_pred) print('MAE: %.3f' % mae) mse = mean_squared_error(y_test, y_pred) print('mse: %.3f' % mse)
时间: 2024-03-21 12:40:29 浏览: 179
first_NN_keras_keras_神经网络_多层感知机_糖尿病数据集_糖尿病_
你的代码中存在一些问题。首先,在导入模块时,你应该将每个模块分开导入,而不是在同一行导入。例如,应该将`import numpy as np import pandas as pd`分开成两行导入。其次,在进行数据标准化时,你应该使用同一个`StandardScaler`对象对训练集和测试集进行转换,而不是分别创建两个不同的对象进行转换。应该如下修改:
```
SC=StandardScaler()
X_train=SC.fit_transform(X_train)
X_test=SC.transform(X_test)
y_train=SC.fit_transform(y_train)
y_test=SC.transform(y_test)
```
另外,你在训练模型时,对于`y_train`和`y_test`也进行了标准化,这是不正确的。你应该只对输入变量进行标准化,而不是对输出变量进行标准化。应该修改为:
```
SC=StandardScaler()
X_train=SC.fit_transform(X_train)
X_test=SC.transform(X_test)
```
最后,你在定义适应度函数时,应该将`X`作为参数传递给`nn_model`函数,而不是直接使用全局变量`X_train`和`y_train`。应该修改为:
```
def fitness_func(X):
model = nn_model(X)
model.fit(X_train, y_train, epochs=60, verbose=2)
score = model.evaluate(X_test, y_test, verbose=2)
print(score)
```
除了以上问题,你的代码看起来应该能够正常运行。
阅读全文