python实现BP算法的代码
以下是一个简单的Python实现BP算法的代码:
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, 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()
print("Output after training:")
print(self.output)
# 测试
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)
该代码实现了一个简单的3层神经网络,包括输入层、隐藏层和输出层,其中隐藏层包含4个神经元。训练数据是一个XOR逻辑门的输入输出,即当输入为(0,0)或(1,1)时,输出为0;当输入为(0,1)或(1,0)时,输出为1。
在训练过程中,我们首先进行前向传播,然后计算输出误差,并通过反向传播调整权重。最后输出训练后的模型的预测结果
原文地址: https://www.cveoy.top/t/topic/doXW 著作权归作者所有。请勿转载和采集!