从零开始构建一个简单的神经网络
前向传播 (Forward Propagation)
神经网络本质上是由多个线性和非线性函数堆叠而成的复合函数。对每一层,输入矩阵 $X$ 会经过权重 $W$ 和偏置 $b$ 的线性变换:
$$Z = W \cdot X + b$$
随后通过激活函数引入非线性特性。本文使用Sigmoid函数:
$$\sigma(z) = \frac{1}{1 + e^{-z}}$$
损失函数与反向传播 (Backpropagation)
我们使用均方误差(MSE)来衡量网络预测值 $\hat{y}$ 与真实值 $y$ 的差距:
$$L = \frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2$$
反向传播利用链式法则(Chain Rule)计算损失函数对每个权重和偏置的梯度,并使用梯度下降算法更新参数。
NumPy 核心代码实现
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
# 初始化权重
inputs = np.array([[0,0], [0,1], [1,0], [1,1]])
expected_output = np.array([[0], [1], [1], [0]])
weights = np.random.uniform(size=(2, 1))
# 训练循环
for epoch in range(10000):
# 前向传播
hidden_layer = np.dot(inputs, weights)
output = sigmoid(hidden_layer)
# 反向传播计算误差
error = expected_output - output
d_weights = error * sigmoid_derivative(output)
# 权重更新
weights += np.dot(inputs.T, d_weights)