Python 实现 BP 神经网络并测试 ReLU 激活函数
以下是使用 Python 编写的一个基本的 BP 神经网络,并使用 ReLU 函数进行测试:
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.rand(hidden_size, input_size)
self.weights2 = np.random.rand(output_size, hidden_size)
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def relu(self, x):
return np.maximum(0,x)
def forward(self, input):
hidden = self.relu(np.dot(self.weights1, input))
output = self.sigmoid(np.dot(self.weights2, hidden))
return output
def backward(self, input, target, output, learning_rate=0.1):
error = target - output
delta2 = error * output * (1 - output)
delta1 = np.dot(self.weights2.T, delta2) * (1 - self.relu(np.dot(self.weights1, input)))
self.weights2 += learning_rate * np.outer(delta2, self.relu(np.dot(self.weights1, input)))
self.weights1 += learning_rate * np.outer(delta1, input)
def train(self, input, target, epochs):
for i in range(epochs):
for j in range(len(input)):
output = self.forward(input[j])
self.backward(input[j], target[j], output)
# test the neural network with ReLU function
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([0, 1, 1, 0])
nn = NeuralNetwork(2, 3, 1)
nn.train(X, y, 10000)
for i in range(len(X)):
print('Input: ', X[i], ' Target: ', y[i], ' Output: ', nn.forward(X[i]))
在这个例子中,我们使用了一个包含一个隐藏层的神经网络,并使用 ReLU 函数作为激活函数。我们使用反向传播算法来训练网络并得出预测结果。
我们使用 XOR 问题来测试神经网络,其中我们拥有 4 个输入数据,每个数据都有两个特征。每个数据都对应一个目标值,我们希望神经网络能够根据输入数据预测出目标值。最后我们将预测值与目标值进行比较,以评估神经网络的性能。
在这个例子中,神经网络可以正确地预测出所有目标值,说明 ReLU 函数在神经网络中的表现良好。
原文地址: https://www.cveoy.top/t/topic/nu0x 著作权归作者所有。请勿转载和采集!