BP神经网络PYTHON代码
时间: 2024-06-13 21:01:51 浏览: 132
BP神经网络是一种常用的人工神经网络,可用于分类、回归、模式识别等问题。下面是一个简单的BP神经网络的Python实现代码:
```python
import numpy as np
class BPNN:
def __init__(self, input_size, hidden_size, output_size, learning_rate):
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size
self.learning_rate = learning_rate
self.w1 = np.random.rand(self.input_size, self.hidden_size)
self.b1 = np.random.rand(self.hidden_size)
self.w2 = np.random.rand(self.hidden_size, self.output_size)
self.b2 = np.random.rand(self.output_size)
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.w1) + self.b1
self.a1 = self.sigmoid(self.z1)
self.z2 = np.dot(self.a1, self.w2) + self.b2
self.a2 = self.sigmoid(self.z2)
return self.a2
def backward(self, x, y, output):
delta2 = (y - output) * self.sigmoid_derivative(output)
d_w2 = np.dot(self.a1.T, delta2)
delta1 = np.dot(delta2, self.w2.T) * self.sigmoid_derivative(self.a1)
d_w1 = np.dot(x.T, delta1)
self.w1 += self.learning_rate * d_w1
self.b1 += self.learning_rate * np.sum(delta1, axis=0)
self.w2 += self.learning_rate * d_w2
self.b2 += self.learning_rate * np.sum(delta2, axis=0)
def train(self, x, y):
output = self.forward(x)
self.backward(x, y, output)
# 示例
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
Y = np.array([, , , ])
bpnn = BPNN(2, 4, 1, 0.5)
for i in range(10000):
for j in range(4):
bpnn.train(X[j], Y[j])
print(bpnn.forward(np.array([0, 0])))
print(bpnn.forward(np.array([0, 1])))
print(bpnn.forward(np.array([1, 0])))
print(bpnn.forward(np.array([1, 1])))
```
以上代码实现了一个简单的BP神经网络,其中`__init__`方法初始化了神经网络的权重和偏置,`sigmoid`方法实现了sigmoid激活函数,`forward`方法实现了前向传播过程,`backward`方法实现了反向传播过程,`train`方法实现了训练过程。在示例中,我们使用BP神经网络实现了异或逻辑运算。
阅读全文