BP神经网络(Python代码实现)不使用pytorch
时间: 2024-02-01 10:04:25 浏览: 68
你可以使用NumPy库来实现一个简单的反向传播神经网络(BP神经网络)的Python代码。下面是一个基本的代码示例:
```python
import numpy as np
# 定义激活函数sigmoid
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义激活函数sigmoid的导数,用于反向传播
def sigmoid_derivative(x):
return x * (1 - x)
# 定义BP神经网络类
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.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.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):
# 反向传播
self.error = y - output
self.delta2 = self.error * sigmoid_derivative(output)
self.error_hidden = np.dot(self.delta2, self.weights2.T)
self.delta1 = self.error_hidden * sigmoid_derivative(self.a1)
# 更新权重和偏置
self.weights2 += np.dot(self.a1.T, self.delta2)
self.bias2 += np.sum(self.delta2, axis=0, keepdims=True)
self.weights1 += np.dot(X.T, self.delta1)
self.bias1 += np.sum(self.delta1, axis=0)
def train(self, X, y, epochs):
for epoch in range(epochs):
# 前向传播
output = self.forward(X)
# 反向传播
self.backward(X, y, output)
def predict(self, X):
# 预测
return self.forward(X)
# 创建训练数据集
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])
# 创建BP神经网络对象
nn = NeuralNetwork(input_size=2, hidden_size=3, output_size=1)
# 训练BP神经网络
nn.train(X, y, epochs=10000)
# 预测新样本
new_X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
predictions = nn.predict(new_X)
print(predictions)
```
这段代码实现了一个简单的逻辑门XOR的BP神经网络。它使用了NumPy库来进行矩阵运算和数学函数计算。你可以根据自己的需要修改网络结构、训练数据和训练参数。希望能对你有所帮助!
阅读全文