Python手写代码实现BP神经网络
时间: 2024-04-17 14:21:35 浏览: 81
当然可以!下面是一个简单的Python代码实现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.b1 = np.zeros((1, self.hidden_size))
self.W2 = np.random.randn(self.hidden_size, self.output_size)
self.b2 = np.zeros((1, self.output_size))
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, learning_rate):
# 反向传播
m = X.shape
# 计算输出层的误差
delta2 = self.a2 - y
# 计算隐藏层的误差
delta1 = np.dot(delta2, self.W2.T) * self.sigmoid_derivative(self.a1)
# 更新权重和偏置
dW2 = np.dot(self.a1.T, delta2) / m
db2 = np.sum(delta2, axis=0) / m
dW1 = np.dot(X.T, delta1) / m
db1 = np.sum(delta1, axis=0) / m
self.W2 -= learning_rate * dW2
self.b2 -= learning_rate * db2
self.W1 -= learning_rate * dW1
self.b1 -= learning_rate * db1
def train(self, X, y, epochs, learning_rate):
for i in range(epochs):
output = self.forward(X)
self.backward(X, y, learning_rate)
def predict(self, X):
return np.round(self.forward(X))
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(self, x):
return x * (1 - x)
```
使用示例:
```python
# 创建一个2-3-1的神经网络
nn = NeuralNetwork(2, 3, 1)
# 输入数据
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([, , , ])
# 训练神经网络
nn.train(X, y, epochs=10000, learning_rate=0.1)
# 预测结果
print(nn.predict(X))
```
这是一个简单的BP神经网络的实现,其中包括前向传播、反向传播、训练和预测等功能。你可以根据自己的需求进行修改和扩展。希望对你有帮助!
阅读全文