Python 神经网络代码示例:使用 ReLU 激活函数
当然可以!以下是一个简单的具有 ReLU 激活函数的神经网络的代码示例:
import numpy as np
# 定义 ReLU 激活函数
def relu(x):
return np.maximum(0, x)
# 定义神经网络类
class NeuralNetwork:
def __init__(self, input_dim, hidden_dim, output_dim):
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.output_dim = output_dim
# 初始化权重和偏置
self.weights1 = np.random.randn(self.input_dim, self.hidden_dim)
self.bias1 = np.zeros((1, self.hidden_dim))
self.weights2 = np.random.randn(self.hidden_dim, self.output_dim)
self.bias2 = np.zeros((1, self.output_dim))
def forward(self, X):
# 前向传播
self.hidden_layer = relu(np.dot(X, self.weights1) + self.bias1)
self.output_layer = np.dot(self.hidden_layer, self.weights2) + self.bias2
return self.output_layer
# 实例化神经网络对象
input_dim = 2
hidden_dim = 4
output_dim = 1
nn = NeuralNetwork(input_dim, hidden_dim, output_dim)
# 测试神经网络
X = np.array([[0, 1], [1, 0], [0, 0], [1, 1]])
print(nn.forward(X)) # 输出神经网络的预测结果
在上面的代码中,我们定义了一个 ReLU 激活函数,并在神经网络类中使用它。我们还实例化了一个神经网络对象,并使用它来进行预测。
原文地址: https://www.cveoy.top/t/topic/mjUI 著作权归作者所有。请勿转载和采集!