BP神经网络时间序列预测代码
时间: 2023-08-30 20:09:35 浏览: 116
这是一个简单的基于BP神经网络的时间序列预测代码示例,使用Python编写,需要使用numpy和matplotlib库:
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成用于训练的数据
def generate_data():
x = np.linspace(-np.pi, np.pi, 200)
y = np.sin(x)
return x, y
# 构建BP神经网络模型
class BPNeuralNetwork:
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)
# sigmoid激活函数
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
# BP神经网络前向传播
def forward(self, x):
self.z1 = np.dot(x, self.W1) + self.b1
self.a1 = self.sigmoid(self.z1)
self.z2 = np.dot(self.a1, self.W2) + self.b2
self.y_hat = self.z2
return self.y_hat
# BP神经网络反向传播
def backward(self, x, y, y_hat, lr):
delta2 = y - y_hat
delta1 = np.dot(delta2, self.W2.T) * self.a1 * (1 - self.a1)
dW2 = np.dot(self.a1.T, delta2)
db2 = np.sum(delta2, axis=0)
dW1 = np.dot(x.T, delta1)
db1 = np.sum(delta1, axis=0)
# 根据学习率更新权重和偏置
self.W2 += lr * dW2
self.b2 += lr * db2
self.W1 += lr * dW1
self.b1 += lr * db1
# BP神经网络训练
def train(self, x_train, y_train, epochs, lr):
for epoch in range(epochs):
y_hat = self.forward(x_train)
self.backward(x_train, y_train, y_hat, lr)
if epoch % 1000 == 0:
loss = np.mean((y_train - y_hat) ** 2)
print(f'Epoch {epoch}: Loss = {loss}')
# 数据生成和预处理
x, y = generate_data()
x_train = x.reshape(-1, 1)
y_train = y.reshape(-1, 1)
# 创建BP神经网络模型
model = BPNeuralNetwork(input_size=1, hidden_size=10, output_size=1)
# 训练模型
model.train(x_train, y_train, epochs=10000, lr=0.01)
# 预测结果并绘图
y_pred = model.forward(x_train)
plt.plot(x, y_train)
plt.plot(x, y_pred)
plt.show()
```
在上面的代码中,我们首先生成一个正弦波形的时间序列数据,然后构建一个具有一个隐藏层和一个输出层的BP神经网络模型,使用均方误差作为损失函数,使用反向传播算法进行训练,并使用训练后的模型进行预测并绘制结果图像。
阅读全文