改进的粒子群优化bp神经网络预测番茄产量python代码案例
时间: 2023-08-03 20:12:06 浏览: 118
以下是一个改进的粒子群优化BP神经网络预测番茄产量的Python代码案例:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
import math
# 读取数据
data = pd.read_excel('tomato_yield.xlsx')
data = data[['Year', 'Temperature (°C)', 'Rainfall (mm)', 'Yield (tons/hectare)']]
# 数据预处理
scaler = MinMaxScaler()
data = scaler.fit_transform(data)
# 划分训练集和测试集
train_size = int(len(data) * 0.8)
train_data = data[:train_size]
test_data = data[train_size:]
# 粒子群优化BP神经网络模型
class BPNN(object):
def __init__(self, input_size, hidden_size, output_size):
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size
self.w1 = np.random.randn(self.input_size, self.hidden_size)
self.b1 = np.random.randn(self.hidden_size)
self.w2 = np.random.randn(self.hidden_size, self.output_size)
self.b2 = np.random.randn(self.output_size)
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def forward(self, x):
z = np.dot(x, self.w1) + self.b1
h = self.sigmoid(z)
y = np.dot(h, self.w2) + self.b2
return y
def loss(self, x, y_true):
y_pred = self.forward(x)
loss = np.mean((y_true - y_pred) ** 2)
return loss
def train(self, x, y_true, swarm_size, max_iter, lr, w, c1, c2):
min_loss = float('inf')
swarm_best = np.zeros((swarm_size, self.hidden_size + self.output_size))
swarm_best_loss = np.zeros((swarm_size,))
swarm_v = np.zeros((swarm_size, self.hidden_size + self.output_size))
swarm_p = np.random.randn(swarm_size, self.hidden_size + self.output_size)
for i in range(swarm_size):
self.w1 = scaler.fit_transform(self.w1)
self.w2 = scaler.fit_transform(self.w2)
swarm_p[i] = np.concatenate([self.w1.flatten(), self.w2.flatten()])
swarm_best[i] = swarm_p[i]
swarm_best_loss[i] = self.loss(x, y_true)
for iter in range(max_iter):
for i in range(swarm_size):
v = w * swarm_v[i] + c1 * np.random.rand() * (swarm_best[i] - swarm_p[i]) + c2 * np.random.rand() * (swarm_best[swarm_best_loss.argmin()] - swarm_p[i])
swarm_p[i] = swarm_p[i] + lr * v
self.w1 = scaler.fit_transform(swarm_p[i][:self.hidden_size].reshape(self.input_size, self.hidden_size))
self.w2 = scaler.fit_transform(swarm_p[i][self.hidden_size:].reshape(self.hidden_size, self.output_size))
loss = self.loss(x, y_true)
if loss < swarm_best_loss[i]:
swarm_best[i] = swarm_p[i]
swarm_best_loss[i] = loss
if loss < min_loss:
min_loss = loss
best_w1 = self.w1
best_b1 = self.b1
best_w2 = self.w2
best_b2 = self.b2
self.w1 = best_w1
self.b1 = best_b1
self.w2 = best_w2
self.b2 = best_b2
def predict(self, x):
y_pred = self.forward(x)
return y_pred
# 训练模型
input_size = 2
hidden_size = 5
output_size = 1
swarm_size = 20
max_iter = 50
lr = 0.5
w = 0.5
c1 = 0.5
c2 = 0.5
x_train = train_data[:, :2]
y_train = train_data[:, 2:]
x_test = test_data[:, :2]
y_test = test_data[:, 2:]
model = BPNN(input_size, hidden_size, output_size)
model.train(x_train, y_train, swarm_size, max_iter, lr, w, c1, c2)
# 预测结果
y_train_pred = model.predict(x_train)
y_test_pred = model.predict(x_test)
# 反归一化
y_train = scaler.inverse_transform(y_train)
y_train_pred = scaler.inverse_transform(y_train_pred)
y_test = scaler.inverse_transform(y_test)
y_test_pred = scaler.inverse_transform(y_test_pred)
# 计算RMSE
train_rmse = math.sqrt(mean_squared_error(y_train, y_train_pred))
test_rmse = math.sqrt(mean_squared_error(y_test, y_test_pred))
# 绘制结果图
plt.plot(y_train, label='true')
plt.plot(y_train_pred, label='predict')
plt.legend()
plt.title('Training set')
plt.show()
plt.plot(y_test, label='true')
plt.plot(y_test_pred, label='predict')
plt.legend()
plt.title('Testing set')
plt.show()
print('Training RMSE:', train_rmse)
print('Testing RMSE:', test_rmse)
```
在该代码中,我们使用了改进的粒子群优化算法来训练BP神经网络,并对番茄产量进行预测。其中,我们使用了`MinMaxScaler`来进行数据的归一化处理,使用了`mean_squared_error`来计算RMSE,使用了`matplotlib`来对结果进行可视化展示。在模型训练完成后,我们通过预测结果图和RMSE值来评估模型的性能。
阅读全文