python写一个BP神经网络
时间: 2024-04-18 11:21:56 浏览: 99
BP神经网络是一种常用的人工神经网络模型,用于解决分类和回归问题。下面是使用Python编写一个简单的BP神经网络的步骤:
1. 导入所需的库:
```python
import numpy as np
```
2. 定义神经网络的类:
```python
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.weights1 = np.random.randn(self.input_size, self.hidden_size)
self.weights2 = np.random.randn(self.hidden_size, self.output_size)
self.bias1 = np.zeros((1, self.hidden_size))
self.bias2 = np.zeros((1, self.output_size))
def forward(self, X):
self.z1 = np.dot(X, self.weights1) + self.bias1
self.a1 = self.sigmoid(self.z1)
self.z2 = np.dot(self.a1, self.weights2) + self.bias2
self.a2 = self.sigmoid(self.z2)
return self.a2
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(self, x):
return x * (1 - x)
def backward(self, X, y, learning_rate):
delta2 = (self.a2 - y) * self.sigmoid_derivative(self.a2)
d_weights2 = np.dot(self.a1.T, delta2)
d_bias2 = np.sum(delta2, axis=0, keepdims=True)
delta1 = np.dot(delta2, self.weights2.T) * self.sigmoid_derivative(self.a1)
d_weights1 = np.dot(X.T, delta1)
d_bias1 = np.sum(delta1, axis=0)
self.weights1 -= learning_rate * d_weights1
self.bias1 -= learning_rate * d_bias1
self.weights2 -= learning_rate * d_weights2
self.bias2 -= learning_rate * d_bias2
def train(self, X, y, epochs, learning_rate):
for epoch in range(epochs):
output = self.forward(X)
self.backward(X, y, learning_rate)
```
3. 准备训练数据和标签:
```python
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([, , , ])
```
4. 创建神经网络对象并进行训练:
```python
input_size = 2
hidden_size = 4
output_size = 1
epochs = 10000
learning_rate = 0.1
nn = NeuralNetwork(input_size, hidden_size, output_size)
nn.train(X, y, epochs, learning_rate)
```
5. 使用训练好的神经网络进行预测:
```python
test_data = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
predictions = nn.forward(test_data)
print(predictions)
```
这样就完成了一个简单的BP神经网络的编写。
阅读全文