BP神经网络预测算法python
时间: 2023-12-14 22:34:53 浏览: 103
BP神经网络是一种常用的人工神经网络,用于回归和分类问题。下面是一个简单的BP神经网络回归预测模型的Python实现示例:
```python
import numpy as np
class BPNeuralNetwork:
def __init__(self, input_dim, hidden_dim, output_dim):
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.output_dim = output_dim
self.weights1 = np.random.randn(self.input_dim, self.hidden_dim)
self.bias1 = np.zeros((1, self.hidden_dim))
self.weights2 = np.random.randn(self.hidden_dim, self.output_dim)
self.bias2 = np.zeros((1, self.output_dim))
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(self, x):
return x * (1 - x)
def forward(self, X):
self.z1 = np.dot(X, self.weights1) + self.bias1
self.a1 = self.sigmoid(self.z1)
self.z2 = np.dot(self.a1, self.weights2) + self.bias2
self.a2 = self.sigmoid(self.z2)
return self.a2
def backward(self, X, y, output):
self.error = y - output
self.delta2 = self.error * self.sigmoid_derivative(output)
self.error_hidden = self.delta2.dot(self.weights2.T)
self.delta1 = self.error_hidden * self.sigmoid_derivative(self.a1)
self.weights1 += X.T.dot(self.delta1)
self.bias1 += np.sum(self.delta1, axis=0, keepdims=True)
self.weights2 += self.a1.T.dot(self.delta2)
self.bias2 += np.sum(self.delta2, axis=0)
def train(self, X, y, epochs):
for epoch in range(epochs):
output = self.forward(X)
self.backward(X, y, output)
def predict(self, X):
return self.forward(X)
# 示例
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])
nn = BPNeuralNetwork(2, 3, 1)
nn.train(X, y, 10000)
print(nn.predict(X))
```
该示例中,我们定义了一个BPNeuralNetwork类,其中包含了神经网络的前向传播、反向传播和训练方法。我们使用sigmoid函数作为激活函数,并使用随机初始化的权重和偏置。在示例中,我们使用一个包含两个输入、三个隐藏神经元和一个输出的神经网络来解决异或问题。我们使用训练集进行训练,并使用训练好的模型进行预测。
阅读全文