给我一个bp神经网络的python代码的列子
时间: 2024-03-27 08:36:40 浏览: 76
这是一个简单的BP神经网络的Python代码的示例:
```python
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
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 = sigmoid(self.z1)
self.z2 = np.dot(self.a1, self.weights2) + self.bias2
self.a2 = sigmoid(self.z2)
return self.a2
def backward(self, X, y, output):
error = output - y
delta2 = error * sigmoid(output, derivative=True)
d_weights2 = np.dot(self.a1.T, delta2)
delta1 = np.dot(delta2, self.weights2.T) * sigmoid(self.z1, derivative=True)
d_weights1 = np.dot(X.T, delta1)
self.weights1 -= d_weights1
self.weights2 -= d_weights2
self.bias1 -= np.sum(delta1, axis=0)
self.bias2 -= np.sum(delta2, axis=0)
def train(self, X, y):
output = self.forward(X)
self.backward(X, y, output)
def predict(self, X):
return self.forward(X)
```
这个代码实现了一个单隐藏层的BP神经网络,可以用于对二分类问题进行预测。其中,`sigmoid`函数用于激活函数的计算,`forward`函数用于正向传播,`backward`函数用于反向传播,`train`函数用于训练模型,`predict`函数用于对新数据进行预测。
阅读全文