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 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) return score # 定义变量的下限和上限 lb = [5, 5] ub = [30, 30] # 利用PySwarm库实现改进的粒子群算法来优化BP神经网络预测模型 result = pso(fitness_func, lb, ub) # 输出最优解和函数值 print('最优解:', result[0]) print('最小函数值:', result[1]) # 绘制预测值和真实值对比图 model = nn_model(X) model.fit(X_train, y_train, epochs=60, verbose=0) 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() # 绘制损失函数曲线图 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()
时间: 2024-04-03 15:37:19 浏览: 59
numpy-1.22.4+vanilla-cp311-cp311-win-amd64-whl
这是一个使用改进的粒子群算法优化BP神经网络预测模型的代码,通过读取Excel文件并将其分为训练集和测试集,利用StandardScaler进行数据标准化处理。然后定义BP神经网络模型和适应度函数,并定义变量的下限和上限。接下来使用PySwarm库实现改进的粒子群算法来优化BP神经网络预测模型,输出最优解和函数值。最后绘制预测值和真实值对比图和损失函数曲线图。
阅读全文