bpnn的python代码
时间: 2024-06-17 12:02:19 浏览: 139
BP神经网络是一种常见的人工神经网络,其主要用于监督学习任务。在Python中,有多种实现BP神经网络的库,其中比较常用的是numpy和pybrain。
以下是一个使用numpy实现的BP神经网络的简单代码示例:
```python
import numpy as np
class NeuralNetwork:
def __init__(self, input_size, hidden_size, output_size):
self.weights1 = np.random.randn(input_size, hidden_size)
self.weights2 = np.random.randn(hidden_size, output_size)
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(self, x):
return x * (1 - x)
def forward(self, X):
self.hidden_layer = self.sigmoid(np.dot(X, self.weights1))
self.output_layer = self.sigmoid(np.dot(self.hidden_layer, self.weights2))
def backward(self, X, y, learning_rate):
output_error = y - self.output_layer
output_delta = output_error * self.sigmoid_derivative(self.output_layer)
hidden_error = np.dot(output_delta, self.weights2.T)
hidden_delta = hidden_error * self.sigmoid_derivative(self.hidden_layer)
self.weights2 += learning_rate * np.dot(self.hidden_layer.T, output_delta)
self.weights1 += learning_rate * np.dot(X.T, hidden_delta)
def train(self, X, y, learning_rate=0.1, epochs=10000):
for i in range(epochs):
self.forward(X)
self.backward(X, y, learning_rate)
def predict(self, X):
self.forward(X)
return self.output_layer
```
在这个示例中,NeuralNetwork类初始化时接收输入层、隐藏层和输出层的大小,并随机初始化权重。sigmoid和sigmoid_derivative函数分别用于计算激活函数和激活函数的导数。forward函数实现前向传播,backward函数实现反向传播,train函数用于训练模型,predict函数用于进行预测。
阅读全文