简单BP神经网络代码
时间: 2024-05-07 14:14:32 浏览: 64
简单的BP神经网络代码
BP神经网络是一种常用的人工神经网络,它可以用于分类、回归等任务。下面是一个简单的BP神经网络代码示例:
```python
import numpy as np
# 定义sigmoid函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义BP神经网络类
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.weights1 = np.random.randn(self.input_size, self.hidden_size)
self.weights2 = np.random.randn(self.hidden_size, self.output_size)
# 前向传播
def forward(self, X):
self.z2 = np.dot(X, self.weights1)
self.a2 = sigmoid(self.z2)
self.z3 = np.dot(self.a2, self.weights2)
y_hat = sigmoid(self.z3)
return y_hat
# 反向传播
def backward(self, X, y, y_hat):
delta3 = (y_hat - y) * sigmoid(self.z3) * (1 - sigmoid(self.z3))
d_weights2 = np.dot(self.a2.T, delta3)
delta2 = np.dot(delta3, self.weights2.T) * sigmoid(self.z2) * (1 - sigmoid(self.z2))
d_weights1 = np.dot(X.T, delta2)
return d_weights1, d_weights2
# 训练模型
def train(self, X, y, learning_rate, epochs):
for i in range(epochs):
y_hat = self.forward(X)
d_weights1, d_weights2 = self.backward(X, y, y_hat)
self.weights1 -= learning_rate * d_weights1
self.weights2 -= learning_rate * d_weights2
# 测试代码
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([, , , ])
nn = BPNeuralNetwork(2, 3, 1)
nn.train(X, y, 0.5, 10000)
print(nn.forward(X))
```
以上代码实现了一个输入层为2,隐藏层为3,输出层为1的BP神经网络,并使用XOR数据集进行训练和测试。在实际应用中,我们可以根据需要调整输入层、隐藏层和输出层的大小,以及学习率和训练轮数等超参数来优化模型的性能。
阅读全文