蓝色天空网mbsky.com · 知识 · 实践 · 创造机器学习 · 本地阅读预览
教程 / AI / 智能开发 / 机器学习

前向传播与反向传播

核对 1-1-1 微型网络前向推理、均方误差与交叉熵损失、链式求导解析反传与中心差分梯度校验、单步及多轮梯度下降收敛与学习率消融实测。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

前向推理与反向学习的完整闭环

前向传播与反向传播共同构成神经网络训练的闭环:前向传播是推理路径,输入数据逐层流向输出层生成预测结果;反向传播是学习路径,依据预测值与真实标签的误差,从输出层反向逐层计算损失函数对每个权重与偏置的偏导数(梯度),量化各参数对误差的贡献并交由优化器更新参数。

1-1-1 微型网络前向传播与损失函数

以预测房价的 1-1-1 三层微型网络为例:输入面积 x,隐藏层单神经元执行 z1 = w1·x + b1 与 Sigmoid 激活 a1 = σ(z1) = 1/(1+e^{-z1}),输出层线性输出 y_pred = w2·a1 + b2。取 w1=2.0, b1=-1.0, w2=1.5, b2=0.5 与输入 x=3.0,本站双精度实测前向输出为 z1=5.0000、a1=0.9933、y_pred=1.9900(精确值 1.989961;原示例手工四舍五入中间项略偏至 1.9899)。

为量化预测偏差,回归任务常用均方误差 MSE = (1/N)Σ(y_true - y_pred)^2(单样本即 L=(y_true - y_pred)^2),分类任务常用交叉熵损失。设真实房价 y_true=2.5,上述初始预测对应的单样本 MSE 损失为 0.2601,优化目标即调整 w1, b1, w2, b2 使损失持续下降。

链式求导反向传播与有限差分梯度校验

反向传播本质是微积分链式法则沿计算图的高效复用:梯度指明损失函数上升最陡的方向,沿其反方向即可“下山”减小损失。对 L=(y_true - y_pred)^2 从后向前依次求偏导:先得 ∂L/∂y_pred = -2(y_true - y_pred) = -1.0201,再乘局部导数得输出层梯度 ∂L/∂w2 = -1.0133、∂L/∂b2 = -1.0201;随后反传至隐藏层输出 ∂L/∂a1 = (∂L/∂y_pred)·w2 = -1.5301,乘以 Sigmoid 导数 σ'(z1)=σ(z1)(1-σ(z1))=0.0066,最终求得隐藏层梯度 ∂L/∂w1 = -0.0305、∂L/∂b1 = -0.0102。注意 z1=5.0 处于 Sigmoid 饱和区,导致隐藏层梯度被压缩到输出层的 3% 左右。本站对全部 4 个参数执行中心有限差分校验 (L(p+ε)-L(p-ε))/(2ε)(ε=1e-6),解析梯度与数值梯度最大误差仅 1.37e-10。

梯度下降更新、网络扩展与学习率消融实测

取得梯度后按“参数 ← 参数 - 学习率 × 梯度”执行梯度下降。本站取 learning_rate=0.1 执行单步更新后,参数移动为 w1→2.0030、b1→-0.9990、w2→1.6013、b2→0.6020,重新前向预测 y_pred 从 1.9900 升至 2.1927(逼近真实值 2.5),损失由 0.2601 骤降至 0.0944(单步净降 -0.1657,全精度数值与来源手算截断结果 0.0940 仅差 0.0004)。

针对四项巩固练习,本站全部完成了离线实测:(1)扩展至 2 个隐藏神经元并分别用 Sigmoid 与 ReLU(导数为 z>0 取 1 否则 0)配合二元交叉熵损失执行向量化反传,两类激活的解析梯度与有限差分最大误差均为 6e-11;(2)在 80 条含噪线性样本 y = 2x + 1 + noise(0.15) 上构建 1-4-1 ReLU 网络运行 300 轮完整训练循环(lr=0.05),MSE 从 9.37158 降至 0.03098,拟合决定系数 R² 达 0.9944;(3)在同初始化下对比 220 轮不同学习率:过小 lr=0.002 收敛缓慢(终损 5.67633),适中 lr=0.05 平滑收敛至 0.04006,而过大 lr=0.8 仅迭代 5 步即震荡发散溢出。前向推理、反向求导与梯度下降三者协作,构成了所有现代深度学习训练的基石。

运行 1-1-1 链式反传差分校验、ReLU/交叉熵扩展、回归训练循环与学习率消融实验

python · 阅读源码
"""Independent pure-NumPy forward & backward propagation lab: 1-1-1 micro-net, finite-diff gradcheck, ReLU/BCE, training loop & LR ablation."""
import json
import math
import platform

import numpy as np


def sigmoid(z):
    return 1.0 / (1.0 + np.exp(-z))


def sigmoid_deriv(z):
    s = sigmoid(z)
    return s * (1.0 - s)


def run_cases():
    cases = []

    # 1. Exact 1-1-1 micro-network forward, analytical chain-rule backprop, finite-diff check & 1 GD step
    w1, b1 = 2.0, -1.0
    w2, b2 = 1.5, 0.5
    x_in, y_true, lr = 3.0, 2.5, 0.1

    def micro_loss(p):
        z1 = p[0] * x_in + p[1]
        a1 = float(sigmoid(z1))
        yp = p[2] * a1 + p[3]
        return (y_true - yp) ** 2

    z1 = w1 * x_in + b1
    a1 = float(sigmoid(z1))
    y_pred = w2 * a1 + b2
    loss0 = (y_true - y_pred) ** 2

    dL_dyp = -2.0 * (y_true - y_pred)
    dL_dw2 = dL_dyp * a1
    dL_db2 = dL_dyp * 1.0
    dL_da1 = dL_dyp * w2
    sp_z1 = float(sigmoid_deriv(z1))
    dL_dw1 = dL_da1 * sp_z1 * x_in
    dL_db1 = dL_da1 * sp_z1 * 1.0

    # Central finite difference gradient check
    params = [w1, b1, w2, b2]
    ana_grads = [dL_dw1, dL_db1, dL_dw2, dL_db2]
    eps = 1e-6
    num_grads = []
    for i in range(4):
        p_plus = list(params)
        p_minus = list(params)
        p_plus[i] += eps
        p_minus[i] -= eps
        num_grads.append((micro_loss(p_plus) - micro_loss(p_minus)) / (2.0 * eps))
    max_fd_err = max(abs(a - n) for a, n in zip(ana_grads, num_grads))

    # One gradient descent update
    w1_new = w1 - lr * dL_dw1
    b1_new = b1 - lr * dL_db1
    w2_new = w2 - lr * dL_dw2
    b2_new = b2 - lr * dL_db2
    y_pred_new = w2_new * float(sigmoid(w1_new * x_in + b1_new)) + b2_new
    loss_new = (y_true - y_pred_new) ** 2

    c1_ok = bool(
        round(z1, 4) == 5.0
        and round(a1, 4) == 0.9933
        and round(y_pred, 4) == 1.99
        and round(loss0, 4) == 0.2601
        and max_fd_err < 1e-9
        and round(y_pred_new, 4) == 2.1927
        and round(loss_new, 4) == 0.0944
        and loss_new < loss0
    )
    cases.append(dict(
        name="micro_network_forward_backward_and_gd_step",
        inputs=dict(w1=w1, b1=b1, w2=w2, b2=b2, x=x_in, y_true=y_true, lr=lr),
        prerequisites="1-1-1 Sigmoid 回归网络前向推理、链式求导反向传播、中心差分校验与单步梯度下降",
        action="验证前向输出与 4 个链式梯度与中心差分误差 <1e-9,且单步 lr=0.1 更新使损失由 0.2601 降至 0.0944。",
        expected=dict(forward_exact=True, gradcheck_lt_1e9=True, loss_dropped=True),
        actual=dict(
            forward_exact=bool(round(z1, 4) == 5.0 and round(a1, 4) == 0.9933),
            gradcheck_lt_1e9=bool(max_fd_err < 1e-9),
            loss_dropped=bool(loss_new < loss0 and round(loss_new, 4) == 0.0944),
        ),
        measurements=dict(
            z1=round(z1, 4), a1=round(a1, 4), y_pred=round(y_pred, 4), loss_before=round(loss0, 4),
            dL_dy_pred=round(dL_dyp, 4), dL_dw2=round(dL_dw2, 4), dL_db2=round(dL_db2, 4),
            dL_da1=round(dL_da1, 4), sigma_prime_z1=round(sp_z1, 4), dL_dw1=round(dL_dw1, 4), dL_db1=round(dL_db1, 4),
            max_finite_diff_err=round(max_fd_err, 12),
            y_pred_after=round(y_pred_new, 4), loss_after=round(loss_new, 4),
            loss_delta=round(loss_new - loss0, 4),
        ),
        passed=c1_ok,
    ))

    # 2. Expanded 2-hidden-neuron network (Sigmoid vs ReLU) & Binary Cross-Entropy analytical gradcheck
    X_m = np.array([[1.2, -0.7, 0.4, 2.0]])  # (1, 4)
    y_bin = np.array([[1.0, 0.0, 1.0, 1.0]])  # (1, 4)
    rng = np.random.default_rng(42)
    W1 = rng.normal(0.0, 0.5, size=(2, 1))
    b1 = np.array([[0.3], [-0.2]])
    W2 = rng.normal(0.0, 0.5, size=(1, 2))
    b2 = np.array([[0.1]])

    def bce_forward_backward(act_name: str, W1_, b1_, W2_, b2_):
        Z1 = W1_ @ X_m + b1_
        if act_name == "relu":
            A1 = np.maximum(0.0, Z1)
            dact = (Z1 > 0.0).astype(np.float64)
        else:
            A1 = sigmoid(Z1)
            dact = A1 * (1.0 - A1)
        Z2 = W2_ @ A1 + b2_
        A2 = sigmoid(Z2)
        eps_c = 1e-12
        loss = float(-np.mean(y_bin * np.log(A2 + eps_c) + (1.0 - y_bin) * np.log(1.0 - A2 + eps_c)))
        m = X_m.shape[1]
        dZ2 = (A2 - y_bin) / m
        gW2 = dZ2 @ A1.T
        gb2 = np.sum(dZ2, axis=1, keepdims=True)
        dZ1 = (W2_.T @ dZ2) * dact
        gW1 = dZ1 @ X_m.T
        gb1 = np.sum(dZ1, axis=1, keepdims=True)
        return loss, (gW1, gb1, gW2, gb2)

    errs = {}
    for act_name in ("sigmoid", "relu"):
        _, (gW1, gb1, gW2, gb2) = bce_forward_backward(act_name, W1, b1, W2, b2)
        max_e = 0.0
        for p_arr, g_arr in ((W1, gW1), (b1, gb1), (W2, gW2), (b2, gb2)):
            for idx in np.ndindex(p_arr.shape):
                orig = float(p_arr[idx])
                p_arr[idx] = orig + eps
                lp, _ = bce_forward_backward(act_name, W1, b1, W2, b2)
                p_arr[idx] = orig - eps
                lm, _ = bce_forward_backward(act_name, W1, b1, W2, b2)
                p_arr[idx] = orig
                max_e = max(max_e, abs(float(g_arr[idx]) - (lp - lm) / (2.0 * eps)))
        errs[act_name] = round(max_e, 11)

    c2_ok = errs["sigmoid"] < 1e-7 and errs["relu"] < 1e-7
    cases.append(dict(
        name="multi_hidden_relu_vs_sigmoid_and_bce_gradcheck",
        inputs=dict(hidden_neurons=2, loss="binary_cross_entropy", activations=["sigmoid", "relu"]),
        prerequisites="扩展至 2 个隐藏神经元并切换 ReLU 与二元交叉熵损失的向量化反传梯度检验",
        action="验证 Sigmoid 与 ReLU 隐藏层配合交叉熵损失的全部权重与偏置解析梯度与中心差分误差均 <1e-7。",
        expected=dict(sigmoid_gradcheck_ok=True, relu_gradcheck_ok=True),
        actual=dict(sigmoid_gradcheck_ok=(errs["sigmoid"] < 1e-7), relu_gradcheck_ok=(errs["relu"] < 1e-7)),
        measurements=dict(max_grad_err_by_activation=errs),
        passed=c2_ok,
    ))

    # 3. Full training loop fitting y = 2x + 1 + noise (Exercise 3)
    rng3 = np.random.default_rng(2026)
    X_reg = np.linspace(-2.0, 2.0, 80).reshape(1, -1)
    y_reg = 2.0 * X_reg + 1.0 + rng3.normal(0.0, 0.15, size=X_reg.shape)

    def train_mlp_reg(lr_val: float, epochs: int = 300, seed: int = 12):
        r = np.random.default_rng(seed)
        W1_ = r.normal(0.0, 0.5, size=(4, 1))
        b1_ = np.zeros((4, 1))
        W2_ = r.normal(0.0, 0.5, size=(1, 4))
        b2_ = np.zeros((1, 1))
        losses = []
        m = X_reg.shape[1]
        for _ in range(epochs):
            Z1 = W1_ @ X_reg + b1_
            A1 = np.maximum(0.0, Z1)
            yp = W2_ @ A1 + b2_
            diff = yp - y_reg
            loss = float(np.mean(diff ** 2))
            if not math.isfinite(loss) or loss > 1e8:
                losses.append(float("inf"))
                break
            losses.append(loss)
            dyp = (2.0 / m) * diff
            gW2 = dyp @ A1.T
            gb2 = np.sum(dyp, axis=1, keepdims=True)
            dZ1 = (W2_.T @ dyp) * (Z1 > 0.0)
            gW1 = dZ1 @ X_reg.T
            gb1 = np.sum(dZ1, axis=1, keepdims=True)
            W1_ -= lr_val * gW1
            b1_ -= lr_val * gb1
            W2_ -= lr_val * gW2
            b2_ -= lr_val * gb2
        yp_final = W2_ @ np.maximum(0.0, W1_ @ X_reg + b1_) + b2_
        ss_res = float(np.sum((y_reg - yp_final) ** 2))
        ss_tot = float(np.sum((y_reg - np.mean(y_reg)) ** 2))
        r2 = 1.0 - ss_res / ss_tot if math.isfinite(ss_res) else float("-inf")
        return losses, r2

    losses_good, r2_good = train_mlp_reg(lr_val=0.05, epochs=300)
    c3_ok = losses_good[-1] < losses_good[0] * 0.02 and r2_good > 0.97
    cases.append(dict(
        name="regression_training_loop_convergence",
        inputs=dict(formula="y = 2x + 1 + noise(0.15)", samples=80, arch="1-4-1 ReLU", epochs=300, lr=0.05),
        prerequisites="完整前向 -> MSE -> 反向传播 -> 梯度下降多轮训练循环拟合线性含噪数据",
        action="验证 300 轮训练后 MSE 下降超过 98% 且拟合决定系数 R^2 > 0.97。",
        expected=dict(mse_dropped_98pct=True, r2_gt_097=True),
        actual=dict(mse_dropped_98pct=(losses_good[-1] < losses_good[0] * 0.02), r2_gt_097=(r2_good > 0.97)),
        measurements=dict(
            ep1_mse=round(losses_good[0], 5),
            ep300_mse=round(losses_good[-1], 5),
            final_r2=round(r2_good, 4),
        ),
        passed=c3_ok,
    ))

    # 4. Learning rate sensitivity ablation (Exercise 4: too small vs moderate vs too large)
    l_small, _ = train_mlp_reg(lr_val=0.002, epochs=220)
    l_opt, _ = train_mlp_reg(lr_val=0.05, epochs=220)
    l_huge, _ = train_mlp_reg(lr_val=0.8, epochs=220)
    small_end = round(l_small[-1], 5)
    opt_end = round(l_opt[-1], 5)
    huge_diverged = bool((not math.isfinite(l_huge[-1])) or (l_huge[-1] > l_huge[0]))
    c4_ok = bool(opt_end < small_end and opt_end < 0.05 and huge_diverged)
    cases.append(dict(
        name="learning_rate_sensitivity_ablation",
        inputs=dict(lrs=[0.002, 0.05, 0.8], epochs=220),
        prerequisites="同初始化下对比过小、适中与过大三种学习率的收敛曲线差异",
        action="验证 lr=0.002 收敛偏慢、lr=0.05 稳定收敛至 <0.05,而 lr=0.8 出现震荡发散。",
        expected=dict(moderate_beats_small=True, moderate_lt_005=True, huge_lr_diverges=True),
        actual=dict(moderate_beats_small=bool(opt_end < small_end), moderate_lt_005=bool(opt_end < 0.05), huge_lr_diverges=huge_diverged),
        measurements=dict(
            lr_0002_final_mse=small_end,
            lr_005_final_mse=opt_end,
            lr_08_diverged=huge_diverged,
            lr_08_steps_before_stop=len(l_huge),
        ),
        passed=c4_ok,
    ))

    payload = dict(
        version=platform.python_version(),
        numpy=np.__version__,
        system=platform.system(),
        cases=cases,
    )
    print(json.dumps(payload, ensure_ascii=False))


if __name__ == "__main__":
    run_cases()
预期结果 · 待实际运行核验
  • 核对 1-1-1 解析梯度与中心差分误差 1.37e-10、单步损失 0.2601->0.0944、2 隐元 Sigmoid/ReLU 交叉熵差分误差 6e-11、y=2x+1 训练 R²=0.9944 及 lr=0.8 发散对比。
运行 1-1-1 链式反传差分校验、ReLU/交叉熵扩展、回归训练循环与学习率消融实验

所需环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。

当前源码 SHA256:4d59b3241877ee4b4238272694da50e672baebc2c7cb4692bcfa797e2a82869e

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载前向传播与反向传播实验

所需环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。

ZIP SHA256:7f17a6ea515267520a899ab3af783fc51abfa01d1e1c4fd9d90ba292cb38355f

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么在 1-1-1 Sigmoid 微型网络算例中,输出层权重梯度 ∂L/∂w2=-1.0133,而隐藏层权重梯度 ∂L/∂w1 却骤降至 -0.0305?

展开参考解答

因为输入经线性变换后 z1=5.0 已落入 Sigmoid 的平坦饱和区,σ'(5.0)=σ(5)(1-σ(5)) 仅约 0.0066;按链式法则反传乘以该极小局部导数后,梯度被衰减了两个数量级,这正是深层 Sigmoid 网络易发生梯度消失的缩影。

规范与官方依据