首页
/ TheAlgorithms/Python项目中的双层隐藏层神经网络实现解析

TheAlgorithms/Python项目中的双层隐藏层神经网络实现解析

2025-07-05 00:35:30作者:冯梦姬Eddie

神经网络基础概念

神经网络是一种模仿生物神经网络结构和功能的计算模型,由大量的人工神经元相互连接构成。它能够通过学习和训练来识别模式、分类数据和做出预测。神经网络的核心在于通过调整各层之间的连接权重来最小化预测误差。

双层隐藏层神经网络结构

本文介绍的实现采用了双层隐藏层的全连接前馈神经网络结构:

  1. 输入层:接收原始数据输入
  2. 第一隐藏层:4个神经元节点
  3. 第二隐藏层:3个神经元节点
  4. 输出层:1个神经元节点(适用于二分类问题)

这种结构比单隐藏层网络具有更强的表达能力,能够学习更复杂的非线性关系。

核心组件实现

1. 初始化函数

def __init__(self, input_array: np.ndarray, output_array: np.ndarray) -> None:
    # 初始化各层权重矩阵
    self.input_layer_and_first_hidden_layer_weights = rng.random((input_array.shape[1], 4))
    self.first_hidden_layer_and_second_hidden_layer_weights = rng.random((4, 3))
    self.second_hidden_layer_and_output_layer_weights = rng.random((3, 1))

初始化时随机生成各层之间的权重矩阵,矩阵维度由前后层的节点数决定。这种随机初始化有助于打破对称性,使网络能够有效学习。

2. 前向传播

def feedforward(self) -> np.ndarray:
    # 输入层到第一隐藏层
    self.layer_between_input_and_first_hidden_layer = sigmoid(np.dot(self.input_array, self.input_layer_and_first_hidden_layer_weights))
    
    # 第一隐藏层到第二隐藏层
    self.layer_between_first_hidden_layer_and_second_hidden_layer = sigmoid(np.dot(self.layer_between_input_and_first_hidden_layer, self.first_hidden_layer_and_second_hidden_layer_weights))
    
    # 第二隐藏层到输出层
    self.layer_between_second_hidden_layer_and_output = sigmoid(np.dot(self.layer_between_first_hidden_layer_and_second_hidden_layer, self.second_hidden_layer_and_output_layer_weights))
    
    return self.layer_between_second_hidden_layer_and_output

前向传播过程通过矩阵乘法和Sigmoid激活函数逐层计算,最终得到输出值。Sigmoid函数将输出压缩到(0,1)区间,适合二分类问题。

3. 反向传播

def back_propagation(self) -> None:
    # 计算各层权重更新量
    updated_second_hidden_layer_and_output_layer_weights = np.dot(...)
    updated_first_hidden_layer_and_second_hidden_layer_weights = np.dot(...)
    updated_input_layer_and_first_hidden_layer_weights = np.dot(...)
    
    # 更新权重
    self.input_layer_and_first_hidden_layer_weights += updated_input_layer_and_first_hidden_layer_weights
    self.first_hidden_layer_and_second_hidden_layer_weights += updated_first_hidden_layer_and_second_hidden_layer_weights
    self.second_hidden_layer_and_output_layer_weights += updated_second_hidden_layer_and_output_layer_weights

反向传播算法通过链式法则计算损失函数对各层权重的梯度,然后使用梯度下降法更新权重。这是神经网络能够学习的关键步骤。

4. 训练过程

def train(self, output: np.ndarray, iterations: int, give_loss: bool) -> None:
    for iteration in range(1, iterations + 1):
        self.output = self.feedforward()
        self.back_propagation()
        if give_loss:
            loss = np.mean(np.square(output - self.feedforward()))
            print(f"Iteration {iteration} Loss: {loss}")

训练过程是前向传播和反向传播的交替进行,通过多次迭代逐步降低预测误差。

关键技术点

  1. Sigmoid激活函数:将线性变换转换为非线性,使网络能够学习复杂模式

    def sigmoid(value: np.ndarray) -> np.ndarray:
        return 1 / (1 + np.exp(-value))
    
  2. Sigmoid导数:反向传播时用于计算梯度

    def sigmoid_derivative(value: np.ndarray) -> np.ndarray:
        return (value) * (1 - (value))
    
  3. 预测函数:将输出值转换为0/1分类结果

    def predict(self, input_arr: np.ndarray) -> int:
        return int((self.layer_between_second_hidden_layer_and_output > 0.6)[0])
    

实际应用示例

代码中提供了一个简单的二分类示例,使用8组3维输入数据和对应的标签进行训练:

test_input = np.array(([0,0,0],[0,0,1],[0,1,0],[0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1]))
output = np.array(([0],[1],[1],[0],[1],[0],[0],[1]))

这个示例展示了如何初始化网络、训练模型并进行预测。

性能优化建议

  1. 增加学习率参数控制权重更新幅度
  2. 实现批量梯度下降或小批量梯度下降
  3. 添加正则化项防止过拟合
  4. 使用更先进的优化算法如Adam
  5. 增加早停机制防止过拟合

总结

这个双层隐藏层神经网络实现展示了神经网络的基本原理和实现方法。通过理解这段代码,可以掌握神经网络的前向传播、反向传播等核心概念,为进一步学习更复杂的深度学习模型打下基础。代码结构清晰,适合作为神经网络学习的入门教材。