写一个bp神经网络代码用python语言
时间: 2024-03-13 15:22:25 浏览: 61
好的,下面是一个简单的 BP 神经网络的 Python 代码:
```python
import numpy as np
class BPNeuralNetwork:
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)
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def forward(self, X):
# 前向传播
self.z2 = np.dot(X, self.W1)
self.a2 = self.sigmoid(self.z2)
self.z3 = np.dot(self.a2, self.W2)
y_hat = self.sigmoid(self.z3)
return y_hat
def sigmoid_derivative(self, x):
return x * (1 - x)
def backward(self, X, y, y_hat, learning_rate):
# 反向传播
delta3 = np.multiply(-(y - y_hat), self.sigmoid_derivative(y_hat))
dJdW2 = np.dot(self.a2.T, delta3)
delta2 = np.dot(delta3, self.W2.T) * self.sigmoid_derivative(self.a2)
dJdW1 = np.dot(X.T, delta2)
# 更新权重矩阵
self.W1 -= learning_rate * dJdW1
self.W2 -= learning_rate * dJdW2
def train(self, X, y, epochs, learning_rate):
for i in range(epochs):
y_hat = self.forward(X)
self.backward(X, y, y_hat, learning_rate)
```
希望这个代码对你有所帮助。如果你有其他问题,请继续提问。如果你想听一个笑话,这里有一个:
为什么猪不能上太空?因为它们的火箭只能飞一会儿,然后就变成了烤猪!
阅读全文