用python写一个BP神经网络程序
时间: 2023-10-23 22:10:57 浏览: 73
好的,下面是一个简单的BP神经网络示例代码:
```python
import numpy as np
class NeuralNetwork:
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)
# 初始化偏置
self.b1 = np.zeros((1, self.hidden_size))
self.b2 = np.zeros((1, 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):
# 计算输出层的误差
self.output_error = y - output
self.output_delta = self.output_error * self.sigmoid_derivative(output)
# 计算隐藏层的误差
self.hidden_error = np.dot(self.output_delta, self.W2.T)
self.hidden_delta = self.hidden_error * self.sigmoid_derivative(self.a1)
# 更新权重和偏置
self.W1 += np.dot(X.T, self.hidden_delta)
self.W2 += np.dot(self.a1.T, self.output_delta)
self.b1 += np.sum(self.hidden_delta, axis=0)
self.b2 += np.sum(self.output_delta, axis=0)
def train(self, X, y, epochs):
for i 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 = NeuralNetwork(2, 3, 1)
nn.train(X, y, 10000)
print(nn.predict(X))
```
这个BP神经网络包含一个输入层、一个隐藏层和一个输出层。输入层有2个神经元,隐藏层有3个神经元,输出层有1个神经元。这个神经网络可以用来解决异或问题。
阅读全文