用Python代码实现BP神经网络
时间: 2023-11-07 12:08:53 浏览: 72
基于python实现BP神经网络
可以的,以下是一个简单的Python代码实现BP神经网络:
```
import numpy as np
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)
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(self, x):
return x * (1 - x)
def forward(self, input_data):
self.hidden_layer = self.sigmoid(np.dot(input_data, self.weights1))
self.output_layer = self.sigmoid(np.dot(self.hidden_layer, self.weights2))
return self.output_layer
def backward(self, input_data, target_output, learning_rate):
# 计算输出层的误差
output_error = target_output - 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.weights1 += learning_rate * np.dot(input_data.T, hidden_delta)
self.weights2 += learning_rate * np.dot(self.hidden_layer.T, output_delta)
def train(self, input_data, target_output, learning_rate, epochs):
for i in range(epochs):
output = self.forward(input_data)
self.backward(input_data, target_output, learning_rate)
def predict(self, input_data):
return self.forward(input_data)
```
这个神经网络实现了一个输入层、一个隐藏层和一个输出层。通过调用`train`方法,可以用给定的输入和输出数据训练神经网络。然后,通过调用`predict`方法,可以用训练好的神经网络预测新的输出数据。
阅读全文