bp神经网络时序预测代码python
时间: 2024-05-20 09:08:46 浏览: 116
BP神经网络是一种常用的机器学习模型,可用于时序预测等问题。以下是一个使用Python编写的简单的BP神经网络时序预测代码示例:
```python
import numpy as np
class BPNN:
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.W2 = np.random.randn(self.hidden_size, self.output_size)
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def forward(self, x):
self.z2 = np.dot(x, self.W1)
self.a2 = self.sigmoid(self.z2)
self.z3 = np.dot(self.a2, self.W2)
y_pred = self.sigmoid(self.z3)
return y_pred
def sigmoid_prime(self, x):
return x * (1 - x)
def backward(self, x, y, y_pred, lr):
delta3 = (y_pred - y) * self.sigmoid_prime(y_pred)
dW2 = np.dot(self.a2.T, delta3)
delta2 = np.dot(delta3, self.W2.T) * self.sigmoid_prime(self.a2)
dW1 = np.dot(x.T, delta2)
self.W1 -= lr * dW1
self.W2 -= lr * dW2
def train(self, X, Y, epochs=1000, lr=0.1):
for i in range(epochs):
y_pred = self.forward(X)
self.backward(X, Y, y_pred, lr)
def predict(self, X):
y_pred = self.forward(X)
return y_pred
if __name__ == '__main__':
# 生成样本数据
X = np.array([[0.2], [0.4], [0.6], [0.8], [1.0]])
Y = np.array([[0.4], [0.5], [0.6], [0.7], [0.8]])
# 创建BP神经网络
nn = BPNN(1, 3, 1)
# 训练模型
nn.train(X, Y)
# 预测结果
x_test = np.array([[1.2]])
y_pred = nn.predict(x_test)
print("预测结果:", y_pred)
```
以上代码实现了一个简单的BP神经网络,其中`train()`函数用于训练模型,`predict()`函数用于预测结果。在训练时需要提供输入数据`X`和对应的输出数据`Y`,可以通过调整学习率和迭代次数等超参数来优化模型效果。
阅读全文