使用python完成BP神经网络的设计与实现
时间: 2023-06-15 20:07:25 浏览: 105
好的,下面是BP神经网络的设计与实现过程:
1. 导入必要的库
```python
import numpy as np
```
2. 定义BP神经网络的类
```python
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.bias1 = np.zeros((1, self.hidden_size))
self.weights2 = np.random.randn(self.hidden_size, self.output_size)
self.bias2 = np.zeros((1, self.output_size))
def forward(self, X):
self.hidden_layer = np.dot(X, self.weights1) + self.bias1
self.activated_hidden_layer = self.sigmoid(self.hidden_layer)
self.output_layer = np.dot(self.activated_hidden_layer, self.weights2) + self.bias2
self.activated_output_layer = self.sigmoid(self.output_layer)
return self.activated_output_layer
def sigmoid(self, s):
return 1 / (1 + np.exp(-s))
def sigmoid_derivative(self, s):
return s * (1 - s)
def backward(self, X, y, o, learning_rate):
self.error = y - o
self.delta_output = self.error * self.sigmoid_derivative(o)
self.error_hidden = self.delta_output.dot(self.weights2.T)
self.delta_hidden = self.error_hidden * self.sigmoid_derivative(self.activated_hidden_layer)
self.weights1 += X.T.dot(self.delta_hidden) * learning_rate
self.bias1 += np.sum(self.delta_hidden, axis=0, keepdims=True) * learning_rate
self.weights2 += self.activated_hidden_layer.T.dot(self.delta_output) * learning_rate
self.bias2 += np.sum(self.delta_output, axis=0, keepdims=True) * learning_rate
def train(self, X, y, learning_rate, epochs):
for epoch in range(epochs):
output = self.forward(X)
self.backward(X, y, output, learning_rate)
def predict(self, X):
return self.forward(X)
```
3. 实例化BP神经网络并进行训练
```python
X = np.array([[0, 0, 1], [0, 1, 1], [1, 0, 1], [1, 1, 1]])
y = np.array([[0], [1], [1], [0]])
nn = BPNeuralNetwork(3, 4, 1)
nn.train(X, y, 0.1, 10000)
```
4. 预测新数据
```python
new_data = np.array([[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 0]])
print(nn.predict(new_data))
```
这样就完成了BP神经网络的设计与实现。
阅读全文