当编写一个基于Python的BP(反向传播)神经网络的代码时,通常我们会使用像NumPy这样的库来处理矩阵运算,或者使用更高级的库,如TensorFlow或PyTorch。以下是一个简单的使用NumPy实现的BP神经网络的例子。
请注意,这个例子是为了教学目的而简化的,并没有包含所有可能的优化和特性(如学习率衰减、动量、批量归一化、正则化等)。
python复制代码
import numpy as np | |
# Sigmoid激活函数 | |
def sigmoid(x): | |
return 1 / (1 + np.exp(-x)) | |
# Sigmoid的导数 | |
def sigmoid_derivative(x): | |
return x * (1.0 - x) | |
class NeuralNetwork: | |
def __init__(self, x, y): | |
self.input = x | |
self.weights1 = np.random.rand(self.input.shape[1],4) | |
self.weights2 = np.random.rand(4,1) | |
self.y = y | |
self.output = np.zeros(self.y.shape) | |
def feedforward(self): | |
self.layer1 = sigmoid(np.dot(self.input, self.weights1)) | |
self.output = sigmoid(np.dot(self.layer1, self.weights2)) | |
def backprop(self): | |
# 反向传播算法 | |
# 应用链式法则计算权重的梯度 | |
d_weights2 = np.dot(self.layer1.T, (2*(self.y - self.output) * sigmoid_derivative(self.output))) | |
d_weights1 = np.dot(self.input.T, (np.dot(2*(self.y - self.output) * sigmoid_derivative(self.output), self.weights2.T) * sigmoid_derivative(self.layer1))) | |
# 更新权重 | |
self.weights1 += d_weights1 | |
self.weights2 += d_weights2 | |
def train(self, epochs): | |
for i in range(epochs): | |
self.feedforward() | |
self.backprop() | |
# 示例数据 | |
X = np.array([[0,0,1], | |
[0,1,1], | |
[1,0,1], | |
[1,1,1]]) | |
y = np.array([[0],[1],[1],[0]]) | |
nn = NeuralNetwork(X,y) | |
nn.train(1500) | |
print(nn.output) |
这个神经网络有两个隐藏层神经元,一个输出层神经元,用于处理简单的XOR问题。请注意,在实际应用中,可能需要调整网络结构(如添加更多层、更改神经元数量等)以及训练参数(如学习率、迭代次数等)以达到最佳性能。同时,对于更复杂的问题,使用TensorFlow或PyTorch等库通常会更加高效和方便。
1223

被折叠的 条评论
为什么被折叠?



