基于pythen编写BP神经网络代码
时间: 2024-05-07 17:19:42 浏览: 9
好的,以下是一个简单的BP神经网络的代码示例:
```python
import numpy as np
class BPNeuralNetwork:
def __init__(self, input_size, hidden_size, output_size, lr=0.1):
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size
self.lr = lr
# 初始化权重
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.random.randn(self.hidden_size)
self.bias2 = np.random.randn(self.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.bias1)
# 计算输出层的值
self.output_layer = self.sigmoid(np.dot(self.hidden_layer, self.weights2) + self.bias2)
return self.output_layer
def backward(self, x, y, output):
# 计算输出层的误差
self.output_error = y - output
self.output_delta = self.output_error * self.sigmoid_derivative(output)
# 计算隐藏层的误差
self.hidden_error = np.dot(self.output_delta, self.weights2.T)
self.hidden_delta = self.hidden_error * self.sigmoid_derivative(self.hidden_layer)
# 更新权重和偏置
self.weights2 += self.lr * np.dot(self.hidden_layer.T, self.output_delta)
self.bias2 += self.lr * np.sum(self.output_delta, axis=0)
self.weights1 += self.lr * np.dot(x.T, self.hidden_delta)
self.bias1 += self.lr * np.sum(self.hidden_delta, axis=0)
def train(self, x, y, epochs):
for i in range(epochs):
output = self.forward(x)
self.backward(x, y, output)
def predict(self, x):
return self.forward(x)
```
其中,`BPNeuralNetwork` 类的构造函数接收输入层、隐藏层和输出层的大小,以及学习速率 `lr`。`sigmoid` 和 `sigmoid_derivative` 分别是 sigmoid 函数和其导数。`forward` 方法用来进行前向传播,计算隐藏层和输出层的值。`backward` 方法用来进行反向传播,计算误差并更新权重和偏置。`train` 方法用来进行训练,接收输入 `x` 和目标输出 `y`,以及训练的轮数 `epochs`。`predict` 方法用来进行预测,接收输入 `x`,返回预测的输出。