BP神经网络模型Python代码
时间: 2024-08-16 18:05:18 浏览: 52
BP神经网络(Backpropagation Neural Network)是一种多层前馈神经网络,通过反向传播算法进行训练。以下是一个简单的BP神经网络模型的Python代码实现:
```python
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
class NeuralNetwork:
def __init__(self, x, y):
self.input = x
self.weights1 = np.random.rand(self.input.shape, 4)
self.weights2 = np.random.rand(4, 1)
self.y = y
self.output = np.zeros(y.shape)
def feedforward(self):
self.layer1 = sigmoid(np.dot(self.input, self.weights1))
self.output = sigmoid(np.dot(self.layer1, self.weights2))
def backprop(self):
d_weights2 = np.dot(self.layer1.T, (2 * (self.y - self.output) * sigmoid_derivative(self.output)))
d_weights1 = np.dot(self.input.T, (np.dot(2 * (self.y - self.output) * sigmoid_derivative(self.output), self.weights2.T) * sigmoid_derivative(self.layer1)))
self.weights1 += d_weights1
self.weights2 += d_weights2
if __name__ == "__main__":
X = np.array([[0, 0, 1],
[0, 1, 1],
[1, 0, 1],
[1, 1, 1]])
y = np.array([, , , ])
nn = NeuralNetwork(X, y)
for i in range(1500):
nn.feedforward()
nn.backprop()
print("输出结果:")
print(nn.output)
```
这个代码实现了一个简单的BP神经网络,包括前向传播和反向传播过程。首先定义了激活函数`sigmoid`及其导数`sigmoid_derivative`。然后创建了一个`NeuralNetwork`类,包含输入层、权重矩阵、输出层等属性。`feedforward`方法用于计算神经网络的输出,`backprop`方法用于更新权重。最后,通过循环迭代训练神经网络,并输出训练后的输出结果。
阅读全文