Skip to content

深度学习基础 ​

深度学习可以看成用多层可学习函数拟合数据关系的方法。猫狗分类把像素映射到类别;语言模型则根据已有 token 预测后续 token。模型不需要由人逐条写出所有判别规则,但仍需要人设计任务、准备数据、选择结构和评估方法。

更多且质量合适的数据,在足够容量与计算支持下可能改善效果,并不意味着数据无限增加就必然持续进步。重复、错误或分布偏离的数据也可能妨碍学习,传统机器学习同样能够从增加数据中受益。

本课依次介绍矩阵计算、导数、前向传播、激活、损失、反向传播、优化器、正则化、归一化与学习率,最后串成一个多层感知机。理解每一步解决什么问题,比背诵公式更重要。

数值小例需要 Python 3 与 NumPy,最终完整示例还需要 PyTorch。可先建立独立 Python 环境,再按 NumPy 和 PyTorch 官方安装入口选择与操作系统兼容的版本;最终脚本使用 CPU 和合成数据,不需要下载模型或数据集。本文仅完成代码语法检查,未实际运行训练,不提供虚构的训练成绩。

神经网络的数学基础 ​

线性代数负责表示数据与变换,微积分提供参数调整方向,概率帮助描述分类与不确定性。这三部分连接起来,形成常见训练流程的基础。

线性代数:用矩阵批量计算 ​

一个神经元接收多个输入,多个神经元又可以同时接收同一组输入。把各组权重排成矩阵,就能用一次矩阵乘法表达这些加权和,便于检查维度,也适合硬件并行计算。

实例 ​

下面的身高、体重、年龄只是构造向量的示例,不用于真实的人体预测。各特征单位不同,真实训练时往往还要考虑缩放与适当的数据处理。

python
import numpy as np


def affine_projection(feature_vector, parameter_matrix, bias_vector):
    values = np.asarray(feature_vector, dtype=float)
    matrix = np.asarray(parameter_matrix, dtype=float)
    intercept = np.asarray(bias_vector, dtype=float)
    if matrix.ndim != 2 or values.shape != (matrix.shape[1],):
        raise ValueError("输入长度必须匹配矩阵的列数")
    if intercept.shape != (matrix.shape[0],):
        raise ValueError("每个输出应当有一个偏置")
    return matrix @ values + intercept


measurements = np.array([172.0, 68.0, 26.0])
projection_weights = np.array([[0.12, 0.18, 0.25], [0.35, 0.45, 0.55]])
projection_bias = np.array([0.2, -0.1])
projected = affine_projection(measurements, projection_weights, projection_bias)
manual = np.array([
    sum(weight * value for weight, value in zip(row, measurements)) + bias
    for row, bias in zip(projection_weights, projection_bias)
])
print("特征与参数形状:", measurements.shape, projection_weights.shape)
print("偏置和结果形状:", projection_bias.shape, projected.shape)
print("矩阵结果:", projected)
print("逐项核对:", manual)
print("两种方式相符:", np.allclose(projected, manual))

这里三维输入经过形状为 (2, 3) 的矩阵,得到二维输出。几何上,矩阵可以表示旋转、缩放等线性变换;加上偏置以后更准确地说是仿射变换。仅仅叠加仿射层仍可合并为一个仿射层,所以深度网络还需要非线性。

微积分:局部变化与链式法则 ​

导数描述自变量发生很小变化时,函数值如何改变。多参数函数对每个参数求偏导,并把它们排成向量,就得到梯度。训练通常沿梯度的反方向作小幅更新,希望降低损失。

实例 ​

用平方函数比较数值近似与解析导数。导数给出的是局部变化率,不能直接用它精确预测任意大的步长。

python
def square_value(point):
    return point * point


def central_difference(function, point, increment=1e-5):
    if increment <= 0:
        raise ValueError("差分步长必须大于零")
    upper = function(point + increment)
    lower = function(point - increment)
    return (upper - lower) / (2.0 * increment)


position = 2.5
small_change = 0.01
estimated_slope = central_difference(square_value, position)
exact_slope = 2.0 * position
actual_delta = square_value(position + small_change) - square_value(position)
linear_delta = exact_slope * small_change
print(f"位置 {position} 的函数值:{square_value(position):.6f}")
print(f"数值近似斜率:{estimated_slope:.6f}")
print(f"解析斜率:{exact_slope:.6f}")
print(f"小步后的实际增量:{actual_delta:.6f}")
print(f"一阶近似的增量:{linear_delta:.6f}")
print(f"近似差额:{actual_delta - linear_delta:.8f}")

中心差分用左右两个邻点估计斜率。步长过大时近似较粗,过小时浮点误差可能明显,因此数值差分很适合小规模核验,却不是训练大型网络的主要求导办法。

实例 ​

复合函数可以拆成内外两步:先平方,再立方,整体等于六次方。链式法则把外层对中间变量的导数,与中间变量对输入的导数相乘。

python
def inner_transform(value):
    return value ** 2


def outer_transform(value):
    return value ** 3


def composed_transform(value):
    return outer_transform(inner_transform(value))


coordinate = 1.5
intermediate = inner_transform(coordinate)
outer_slope = 3.0 * intermediate ** 2
inner_slope = 2.0 * coordinate
chain_slope = outer_slope * inner_slope
delta = 1e-5
finite_difference = (
    composed_transform(coordinate + delta) - composed_transform(coordinate - delta)
) / (2.0 * delta)
closed_form = 6.0 * coordinate ** 5
print("中间结果:", intermediate)
print("内外局部导数:", inner_slope, outer_slope)
print("链式法则:", chain_slope)
print("差分核对:", finite_difference)
print("六次方的解析导数:", closed_form)

多层网络就是更大的复合函数。反向传播按计算关系复用局部导数,从损失端逐步传回各参数,而不必为每个参数独立做一次数值扰动。

概率论:根据输入预测类别 ​

条件概率 P(Y|X) 表示在已知输入 X 时,结果 Y 的概率。例如观察到乌云后,预测下雨的可能性。分类网络通常先输出分数 logits,再通过合适的变换得到归一化的类别分布。

实例 ​

三个分数对应猫、狗和鸟。Softmax 先减去最大分数以改善数值稳定性,再指数化和归一化;它给出模型分布,不保证已经校准为真实发生频率。

python
import numpy as np


def normalized_exponential(scores, axis=-1):
    values = np.asarray(scores, dtype=np.float64)
    centered = values - values.max(axis=axis, keepdims=True)
    numerators = np.exp(centered)
    return numerators / numerators.sum(axis=axis, keepdims=True)


animal_names = ("猫", "狗", "鸟")
animal_scores = np.array([2.2, 1.1, 0.4])
animal_distribution = normalized_exponential(animal_scores)
print("未归一化分数:", animal_scores)
print("模型类别分布:", animal_distribution)
print("总和:", animal_distribution.sum())
for animal, chance in zip(animal_names, animal_distribution):
    print(f"{animal} 的模型概率:{chance:.2%}")
print("最大概率类别:", animal_names[int(animal_distribution.argmax())])

不能把未经计算的近似百分比写进结论。使用实际数组打印结果,能避免分数已经变化、注释里的旧概率却没有更新的问题。

数学部分入门核心在网络中的作用
线性代数向量、矩阵与张量维度表示参数并批量完成前向运算
微积分导数、偏导与链式法则计算梯度,为参数更新提供方向
概率条件分布与归一化表达分类结果并构造训练目标

前向传播 ​

把输入按网络定义依次变换,得到预测,就是前向传播。训练时还会根据预测计算损失;推理时则根据任务返回分数、类别或生成内容。

用计算图组织步骤 ​

图中的节点表示加法、矩阵乘法或激活等运算,连线表示数值依赖。保存必要的中间量,可以让之后的梯度计算知道每一步使用了什么。

实例 ​

这个网络从二维输入进入三个隐藏单元,再输出两个类别分数。为便于单独阅读,代码包含自己的 Softmax,而不依赖上一个代码块里的定义。

python
import numpy as np


def forward_classifier(vector, hidden_matrix, hidden_bias, output_matrix, output_bias):
    preactivation = hidden_matrix @ vector + hidden_bias
    hidden_values = np.maximum(preactivation, 0.0)
    class_scores = output_matrix @ hidden_values + output_bias
    shifted = class_scores - class_scores.max()
    probabilities = np.exp(shifted) / np.exp(shifted).sum()
    return {
        "hidden_linear": preactivation,
        "hidden_activation": hidden_values,
        "class_logits": class_scores,
        "probabilities": probabilities,
    }


sample_vector = np.array([1.2, 1.8])
hidden_matrix = np.array([[0.15, 0.25], [0.35, 0.45], [0.55, 0.65]])
hidden_bias = np.array([0.05, 0.10, 0.15])
output_matrix = np.array([[0.2, 0.1, 0.3], [0.4, 0.6, 0.5]])
output_bias = np.array([0.1, -0.1])
forward_values = forward_classifier(
    sample_vector, hidden_matrix, hidden_bias, output_matrix, output_bias
)
for label, value in forward_values.items():
    print(f"{label}:形状 {value.shape},数值 {value}")
print("输出分布归一化:", np.isclose(forward_values["probabilities"].sum(), 1.0))

计算图让中间结果与依赖关系清楚可见。反向传播不是把这些数倒着重新算一遍,而是按相反的依赖顺序传递损失对各中间量的导数。

从矩阵角度理解网络 ​

全连接层可以写为 a[l] = activation(W[l] @ a[l-1] + b[l])。若上一层有 n 个数,下一层有 m 个单元,以列向量约定表示时,权重形状为 (m, n),偏置形状为 (m,)。

一批样本通常按行排列,代码便可能写成 X @ W.T + b。两种写法描述相同关系,只是存放方向不同。卷积、注意力、残差与归一化还包含其他操作,所以不能把这一条公式当作所有网络结构的完整定义。

为什么需要非线性激活 ​

只有矩阵乘法和偏置的层,无论叠几层都能合并。非线性使网络能够表达单个仿射变换无法表示的关系,但深度、宽度和数据仍决定实际能学到什么。

实例 ​

下面分别计算两次仿射变换,并与合并后的参数比较。它验证的是无激活时的等价关系,不是说任何深度网络都可随意压成一层。

python
import numpy as np


def merge_affine_layers(first_weight, first_bias, second_weight, second_bias):
    merged_weight = second_weight @ first_weight
    merged_bias = second_weight @ first_bias + second_bias
    return merged_weight, merged_bias


input_point = np.array([1.5, -0.5])
first_weight = np.array([[0.2, 0.4], [0.6, 0.3]])
first_bias = np.array([0.1, -0.2])
second_weight = np.array([[0.7, 0.1], [0.5, 0.8]])
second_bias = np.array([-0.1, 0.2])
intermediate_point = first_weight @ input_point + first_bias
two_stage_result = second_weight @ intermediate_point + second_bias
merged_weight, merged_bias = merge_affine_layers(
    first_weight, first_bias, second_weight, second_bias
)
single_stage_result = merged_weight @ input_point + merged_bias
print("逐层执行:", two_stage_result)
print("参数合并:", single_stage_result)
print("数值等价:", np.allclose(two_stage_result, single_stage_result))
print("最大绝对差:", np.abs(two_stage_result - single_stage_result).max())

激活函数详解 ​

激活决定单元怎样响应线性输入。选择时要考虑非线性表达、梯度行为、数值稳定与计算成本。处处可微不是硬性要求,例如 ReLU 在零点不可微,框架仍可使用约定的次梯度。也没有一种激活能保证所有网络都不出现梯度问题。

Sigmoid:输出压缩与饱和 ​

Sigmoid 为 1 / (1 + exp(-x)),输出在零与一之间。导数为 s * (1-s),当输入绝对值很大时接近零,多层连乘时可能使梯度衰减。

实例 ​

稳定实现需要留意指数溢出。这里对正负输入分别计算,同时打印输出与导数;它不需要绘图库。

python
import numpy as np


def stable_sigmoid(values):
    array = np.asarray(values, dtype=np.float64)
    result = np.empty_like(array)
    nonnegative = array >= 0
    result[nonnegative] = 1.0 / (1.0 + np.exp(-array[nonnegative]))
    exp_negative = np.exp(array[~nonnegative])
    result[~nonnegative] = exp_negative / (1.0 + exp_negative)
    return result


def sigmoid_slope(values):
    activation = stable_sigmoid(values)
    return activation * (1.0 - activation)


probe_values = np.array([-12.0, -5.0, -1.0, 0.0, 1.0, 5.0, 12.0])
activations = stable_sigmoid(probe_values)
slopes = sigmoid_slope(probe_values)
for point, output, slope in zip(probe_values, activations, slopes):
    print(f"输入 {point:6.1f},输出 {output:.8f},导数 {slope:.8f}")
print("零点导数:", float(sigmoid_slope(np.array([0.0]))[0]))
print("边缘输入的导数更小:", slopes[[0, -1]])

饱和不是在某个固定绝对值以后突然发生,而是渐进变化。Sigmoid 的非零中心输出也会影响优化;隐藏层常选其他函数,但二分类概率建模仍常用它。采用融合损失时,通常直接传 logits,让库在内部稳定计算。

ReLU 及常见变体 ​

ReLU 把负数截为零,正区间保持不变,计算简单。Leaky ReLU 为负区间保留小斜率;GELU 采用平滑门控;Swish/SiLU 则使用 x * sigmoid(x)。SwiGLU 是带门控的层结构,不能只用 Swish 的一个标量公式完整表示。

实例 ​

下面比较几个激活并给出 ReLU 导数。零点导数采用零的常见约定;这是一项实现选择,不是零点存在普通导数。

python
import numpy as np


def rectifier(values):
    return np.maximum(np.asarray(values, dtype=float), 0.0)


def rectifier_slope(values):
    return (np.asarray(values) > 0).astype(float)


def leaky_rectifier(values, negative_slope=0.02):
    array = np.asarray(values, dtype=float)
    return np.where(array >= 0, array, negative_slope * array)


def approximate_gelu(values):
    array = np.asarray(values, dtype=float)
    argument = np.sqrt(2.0 / np.pi) * (array + 0.044715 * array ** 3)
    return 0.5 * array * (1.0 + np.tanh(argument))


def silu_activation(values):
    array = np.asarray(values, dtype=float)
    return array / (1.0 + np.exp(-array))


positions = np.array([-4.0, -2.0, -0.5, 0.0, 0.5, 2.0, 4.0])
for point, basic, leaky, smooth, gated in zip(
    positions, rectifier(positions), leaky_rectifier(positions),
    approximate_gelu(positions), silu_activation(positions)
):
    print(f"{point:5.1f} | ReLU {basic:7.4f} | Leaky {leaky:7.4f} | GELU {smooth:7.4f} | SiLU {gated:7.4f}")
print("ReLU 局部导数:", rectifier_slope(positions))

若一个 ReLU 单元对全部当前训练输入都落在负区间,局部梯度会为零,可能长期没有有效更新,这就是常说的“死亡 ReLU”现象。不过输入分布或上游参数变化仍可能改变状态,不能一概说它永远无法恢复。

函数或结构主要形式有利之处需要注意常见用途
Sigmoid将数压到 (0,1)便于表达二分类概率大绝对值区间梯度很小二分类输出或门控
ReLUmax(x,0)运算简单,正区间斜率固定负区间梯度为零多种前馈与视觉网络
Leaky ReLU负区间保留小斜率减少完全无梯度的区域需选负斜率,并非总能改善效果ReLU 的一种替代
GELUx * Φ(x)平滑地调节输入计算与近似方式要明确部分 Transformer 前馈层
Swish/SiLUx * sigmoid(βx)平滑门控不是每个任务都优于 ReLU深层网络
SwiGLUSiLU 门控分支与另一分支逐元素相乘可提高某些前馈结构的表达维度与参数规模需配套设计部分大语言模型

怎样选择激活 ​

普通小型 MLP 可以从 ReLU 开始,再根据训练与验证结果决定是否替换。若负区间无梯度成为问题,可以对比 Leaky ReLU、GELU 等,但也应检查学习率和初始化。

二分类输出可映射为 Sigmoid,多类互斥任务可映射为 Softmax,回归可直接输出实数。训练时要遵守损失函数的输入约定,尤其不要给本来接收 logits 的融合损失重复加概率变换。已有 Transformer 应保持其架构所要求的激活,不宜随意替换后沿用旧权重。

损失函数 ​

损失把预测与训练目标之间的差异转成可优化的数值。它决定模型被奖励什么,也决定异常值和不同错误怎样影响更新。降低训练损失并不自动说明真实任务更好,还需独立验证。

分类中的交叉熵 ​

当标签是正确类别时,交叉熵鼓励模型提高这个类别的概率。对于单个样本,它等于正确类别概率的负对数;给正确类别的概率越低,惩罚越大。

实例 ​

以下比较正确且自信、不确定、自信但错误三种分数。代码使用 one-hot 标签演示批平均交叉熵,并核对类别索引写法。

python
import numpy as np


def softmax_rows(scores):
    shifted = scores - np.max(scores, axis=-1, keepdims=True)
    exponentials = np.exp(shifted)
    return exponentials / exponentials.sum(axis=-1, keepdims=True)


def cross_entropy_from_probabilities(probabilities, one_hot_labels):
    if probabilities.shape != one_hot_labels.shape:
        raise ValueError("概率与标签的维度应一致")
    safe = np.clip(probabilities, 1e-12, 1.0)
    per_example = -(one_hot_labels * np.log(safe)).sum(axis=-1)
    return float(per_example.mean())


correct_class = 0
label_matrix = np.eye(3)[[correct_class]]
score_cases = {
    "正确且较自信": np.array([[4.5, 0.4, -0.2]]),
    "类别差距很小": np.array([[1.0, 0.95, 0.9]]),
    "对错误类很自信": np.array([[-0.2, 4.5, 0.4]]),
}
for description, score_matrix in score_cases.items():
    distribution = softmax_rows(score_matrix)
    average_loss = cross_entropy_from_probabilities(distribution, label_matrix)
    index_form = -np.log(distribution[0, correct_class])
    print(description)
    print("分布:", distribution[0])
    print("批平均损失:", average_loss)
    print("索引形式核对:", index_form)

实际库常把 LogSoftmax 与负对数似然融合计算,以减少数值问题。PyTorch 的 CrossEntropyLoss 接口说明规定输入是未归一化 logits,常见标签是类别索引;不是先自行 Softmax 再把概率传入同一个损失。

回归中的 MSE ​

均方误差对每个预测差值平方后求平均。平方会放大较大的偏差,因此异常值可能有很大影响;MAE 使用绝对值,对极端偏差的增长较缓,但选择仍要结合业务损失含义。

实例 ​

房价数字的单位在这里设为万元,仅用于比较损失函数,不用于估价。观察某一个预测偏离较大时,两种指标怎样变化。

python
import numpy as np


def regression_metrics(predictions, observations):
    predicted = np.asarray(predictions, dtype=float)
    observed = np.asarray(observations, dtype=float)
    if predicted.shape != observed.shape or not predicted.size:
        raise ValueError("两组非空数据需要具有相同形状")
    errors = predicted - observed
    return {
        "mse": float(np.square(errors).mean()),
        "mae": float(np.abs(errors).mean()),
        "maximum_error": float(np.abs(errors).max()),
    }


actual_prices = np.array([120.0, 210.0, 165.0])
forecast_cases = {
    "误差较均匀": np.array([122.0, 205.0, 163.0]),
    "有一个明显偏差": np.array([122.0, 285.0, 163.0]),
}
for case_name, forecast in forecast_cases.items():
    measures = regression_metrics(forecast, actual_prices)
    print(case_name, "预测:", forecast)
    print("误差指标:", measures)
print("MSE 的单位为万元的平方,MAE 的单位仍是万元。")

MSE 与 MAE 的数值单位不同,不宜只看数值大小互相比较。对于有特殊代价结构的任务,还可能使用 Huber 等其他损失,应明确选择依据。

语言模型的下一个 token 损失 ​

自回归语言模型可把词表中的 token 当作类别,在每个可训练位置计算交叉熵,再对有效位置平均。token 可能是一段文字、词的一部分或符号,并不总是一个完整词。

实例 ​

下面生成两段序列、每段三个位置的模拟 logits。目标必须与“下一个 token”对齐,真实语言训练还要处理填充、掩码与忽略位置。

python
import numpy as np


def sequence_cross_entropy(logits, next_token_ids):
    scores = np.asarray(logits, dtype=np.float64)
    labels = np.asarray(next_token_ids, dtype=np.int64)
    if scores.ndim != 3 or labels.shape != scores.shape[:2]:
        raise ValueError("分数应为批、序列、词表三维,标签应匹配前两维")
    if np.any(labels < 0) or np.any(labels >= scores.shape[-1]):
        raise ValueError("标签超出词表范围")
    normalized_scores = scores - scores.max(axis=-1, keepdims=True)
    log_partition = np.log(np.exp(normalized_scores).sum(axis=-1))
    chosen_scores = np.take_along_axis(normalized_scores, labels[..., None], axis=-1)[..., 0]
    per_position = log_partition - chosen_scores
    return float(per_position.mean()), per_position


random_source = np.random.default_rng(81)
vocabulary_size = 1000
mock_logits = random_source.normal(size=(2, 3, vocabulary_size))
mock_targets = np.array([[12, 45, 78], [23, 56, 89]])
mean_loss, position_losses = sequence_cross_entropy(mock_logits, mock_targets)
print("输入分数维度:", mock_logits.shape)
print("每个位置的损失:", position_losses)
print("有效位置平均:", mean_loss)
print("均匀分布时的比较基线:", np.log(vocabulary_size))

随机分数不对应任何真实模型,打印值不能当作模型成绩。基线 log(词表大小) 只表示均匀分布的交叉熵,实际比较还要统一分词、数据和有效位置口径。

任务常见损失对外解释的输出常见标签
二分类二元交叉熵或融合 logits 版本Sigmoid 概率零或一
互斥多分类交叉熵Softmax 分布类别索引或合规分布
多标签各标签二元交叉熵每类独立 Sigmoid多个零一标签
回归MSE、MAE 等连续实数目标数值
语言预测有效 token 的交叉熵下一个 token 分布已对齐 token 索引

反向传播 ​

反向传播计算损失对各参数的梯度,优化器才负责用梯度更新参数。把两者分开,有助于理解为什么调用 backward() 后还需要 step()。

用链式法则逐项推导 ​

取一个标量模型 prediction = weight * input + bias,损失为预测误差的平方。先求损失对预测的导数,再乘预测对各参数的导数。

实例 ​

下面用一个小学习率作一次更新,并重新计算损失。代码根据数值判断是否下降,不预先打印“必然成功”;步长太大时,梯度更新也可能使损失上升。

python
def scalar_forward(input_value, weight_value, bias_value):
    return weight_value * input_value + bias_value


feature = 2.0
target_value = 7.0
weight_value = 1.2
bias_value = 0.1
step_size = 0.05
prediction_before = scalar_forward(feature, weight_value, bias_value)
loss_before = (prediction_before - target_value) ** 2
gradient_prediction = 2.0 * (prediction_before - target_value)
gradient_weight = gradient_prediction * feature
gradient_bias = gradient_prediction
updated_weight = weight_value - step_size * gradient_weight
updated_bias = bias_value - step_size * gradient_bias
prediction_after = scalar_forward(feature, updated_weight, updated_bias)
loss_after = (prediction_after - target_value) ** 2
print("旧参数:", weight_value, bias_value)
print("损失对预测、权重、偏置的梯度:", gradient_prediction, gradient_weight, gradient_bias)
print("新参数:", updated_weight, updated_bias)
print("预测变化:", prediction_before, prediction_after)
print("损失变化:", loss_before, loss_after)
print("这一步损失降低:", loss_after < loss_before)

完整过程包括保存中间值、求出局部梯度、按依赖关系相乘和更新参数。对于批平均损失,梯度还要包含对应的平均因子,否则学习率和梯度量级会发生变化。

多层计算图中的梯度 ​

对于线性层,输出梯度与输入的外积形成权重梯度,输出梯度本身形成偏置梯度,再乘权重转置得到传向前层的梯度。激活层则把后方梯度与本地导数逐元素相乘。

实例 ​

下面是输入二维、隐藏三维、输出一维的回归网络。除手动反向传播外,还用中心差分抽查第一层参数,帮助核对梯度形状与方向。

python
import numpy as np


def two_layer_forward(vector, first_weight, first_bias, last_weight, last_bias):
    hidden_linear = first_weight @ vector + first_bias
    hidden = np.maximum(hidden_linear, 0.0)
    estimate = last_weight @ hidden + last_bias
    return hidden_linear, hidden, estimate


features = np.array([1.0, 2.0])
target = np.array([5.0])
first_weight = np.array([[0.12, 0.22], [0.32, 0.42], [0.52, 0.62]])
first_bias = np.array([0.1, 0.15, 0.2])
last_weight = np.array([[0.6, 0.7, 0.8]])
last_bias = np.array([0.3])
linear_hidden, hidden, estimate = two_layer_forward(
    features, first_weight, first_bias, last_weight, last_bias
)
starting_loss = float(np.square(estimate - target).mean())
output_gradient = 2.0 * (estimate - target) / target.size
last_weight_gradient = np.outer(output_gradient, hidden)
last_bias_gradient = output_gradient.copy()
hidden_gradient = last_weight.T @ output_gradient
linear_gradient = hidden_gradient * (linear_hidden > 0)
first_weight_gradient = np.outer(linear_gradient, features)
first_bias_gradient = linear_gradient.copy()

# 差分仅抽查一个参数,且输入避开 ReLU 的零点。
epsilon = 1e-5
perturbed = first_weight.copy()
perturbed[0, 0] += epsilon
upper_output = two_layer_forward(features, perturbed, first_bias, last_weight, last_bias)[2]
perturbed[0, 0] -= 2.0 * epsilon
lower_output = two_layer_forward(features, perturbed, first_bias, last_weight, last_bias)[2]
numerical_gradient = (
    np.square(upper_output - target).mean() - np.square(lower_output - target).mean()
) / (2.0 * epsilon)
print("第一层权重梯度形状:", first_weight_gradient.shape)
print("第二层权重梯度形状:", last_weight_gradient.shape)
print("抽查解析与数值梯度:", first_weight_gradient[0, 0], numerical_gradient)

learning_rate = 0.01
next_parameters = (
    first_weight - learning_rate * first_weight_gradient,
    first_bias - learning_rate * first_bias_gradient,
    last_weight - learning_rate * last_weight_gradient,
    last_bias - learning_rate * last_bias_gradient,
)
next_estimate = two_layer_forward(features, *next_parameters)[2]
print("更新前后损失:", starting_loss, np.square(next_estimate - target).mean())

反向传播的核心是链式法则和梯度累积。一个变量流向多个分支时,各分支贡献应相加。现代框架通过自动微分记录这些关系,但仍需要正确构造前向计算与损失;它不会自动修正错误标签或无意中断开的计算图。

梯度下降优化器 ​

优化器把梯度变成实际更新。学习率控制步长,动量和自适应统计改变更新方式。它们都不能保证复杂非凸任务找到全局最优,比较时应统一任务与预算。

SGD:沿负梯度更新 ​

基本形式是 parameter -= learning_rate * gradient。使用随机小批次估计梯度时称为随机梯度下降;下面平方函数的精确梯度例子只是演示更新机制,没有随机抽样。

实例 ​

python
def quadratic_objective(parameter):
    return parameter ** 2


def quadratic_gradient(parameter):
    return 2.0 * parameter


def gradient_descent_path(initial, rate, number_of_steps):
    point = float(initial)
    records = [(0, point, quadratic_objective(point))]
    for index in range(1, number_of_steps + 1):
        gradient = quadratic_gradient(point)
        point -= rate * gradient
        records.append((index, point, quadratic_objective(point)))
    return records


descent_records = gradient_descent_path(initial=8.0, rate=0.1, number_of_steps=20)
for iteration, point, objective in descent_records:
    print(f"迭代 {iteration:2d},参数 {point:10.6f},目标值 {objective:12.8f}")
print("该函数的理论极小点是零,有限步通常只是逐步接近。")

简单 SGD 使用统一基础学习率,可能需要仔细调节,面对噪声、狭长谷地或鞍点时也可能推进缓慢。这些是可能出现的现象,不表示更复杂优化器在每个任务都更好。

Momentum:保留历史方向 ​

动量用过去梯度的平滑累计帮助更新。可采用 velocity = beta*velocity + (1-beta)*gradient,再减去学习率乘速度;也有不含 (1-beta) 的约定,不能在比较参数时混用。

实例 ​

下面在同一个平方函数上比较有无动量的轨迹,只打印实际数值,不预设哪一种一定更快。

python
import numpy as np


def optimize_with_history(start, rate, iterations, momentum_coefficient=None):
    parameter = float(start)
    velocity = 0.0
    path = [parameter]
    for _ in range(iterations):
        gradient = 2.0 * parameter
        if momentum_coefficient is None:
            update_direction = gradient
        else:
            velocity = (
                momentum_coefficient * velocity
                + (1.0 - momentum_coefficient) * gradient
            )
            update_direction = velocity
        parameter -= rate * update_direction
        path.append(parameter)
    return np.array(path)


without_momentum = optimize_with_history(8.0, 0.1, 20)
with_momentum = optimize_with_history(8.0, 0.1, 20, momentum_coefficient=0.9)
for step_number, plain, smoothed in zip(range(21), without_momentum, with_momentum):
    print(f"{step_number:2d} | 普通更新 {plain:10.6f} | 动量更新 {smoothed:10.6f}")
print("最后的平方目标值:", without_momentum[-1] ** 2, with_momentum[-1] ** 2)

动量可能减少某些方向的振荡,也可能造成过冲。收益与目标曲面、学习率、动量约定和步数有关,不能从“有惯性”直接推出必定更快收敛。

Adam:使用一阶与二阶统计 ​

Adam 对梯度维护一阶滑动平均和平方梯度的二阶滑动平均,进行初期偏差修正后,用第二项的平方根调节每个参数的更新尺度。

其关系可写成 m=β1*m+(1-β1)*g、v=β2*v+(1-β2)*g²,再以 m/(1-β1^t) 和 v/(1-β2^t) 修正,最终使用 lr*m_hat/(sqrt(v_hat)+eps)。常见起点是 β1 为 0.9、β2 为 0.999、eps 为 1e-8,但具体任务仍需验证。

实例 ​

python
import math


def adam_trajectory(initial_value, rate=0.3, steps=20, beta_first=0.9, beta_second=0.999, epsilon=1e-8):
    parameter = float(initial_value)
    first_moment = 0.0
    second_moment = 0.0
    observations = [(0, parameter, parameter ** 2)]
    for time_index in range(1, steps + 1):
        gradient = 2.0 * parameter
        first_moment = beta_first * first_moment + (1.0 - beta_first) * gradient
        second_moment = beta_second * second_moment + (1.0 - beta_second) * gradient ** 2
        corrected_first = first_moment / (1.0 - beta_first ** time_index)
        corrected_second = second_moment / (1.0 - beta_second ** time_index)
        adjustment = rate * corrected_first / (math.sqrt(corrected_second) + epsilon)
        parameter -= adjustment
        observations.append((time_index, parameter, parameter ** 2))
    return observations


for index, value, objective in adam_trajectory(initial_value=8.0):
    print(f"步数 {index:2d},参数 {value:10.6f},平方损失 {objective:12.8f}")

自适应不表示不需要学习率,也不表示所有参数拥有独立可随意设定的学习率。基础步长、数据尺度、批大小和调度都会影响表现。

AdamW:把权重衰减独立处理 ​

AdamW 将参数衰减与自适应梯度更新分开,避免把普通 L2 梯度直接混入自适应统计造成的不同效果。具体实现可查看 PyTorch AdamW 文档。

优化器更新特点可能优势需要调节适用考虑
SGD基于当前梯度简单、状态开销小学习率与调度可作为明确的基线
SGD 加动量结合历史梯度方向可能缓解振荡动量系数及基础步长需要比较实际轨迹
Adam一阶、二阶统计自适应缩放常较容易得到有效起点学习率、统计系数多种深度任务
AdamW自适应更新加独立衰减更清楚控制权重衰减衰减与参数分组许多 Transformer 训练流程

小型任务可从 Adam 或 AdamW 的常见参数起步,但 1e-3、3e-4 都只是候选,不存在通用最稳妥值。应结合训练曲线与验证表现选择,而不是仅凭优化器名称作结论。

正则化技术 ​

正则化尝试减少对训练样本的过度依赖,改善未见数据上的表现。它可能使训练更难,却有利于泛化;是否有效要看独立验证,不能只观察训练损失。

L1 与 L2 参数惩罚 ​

可以在任务损失后加 lambda * penalty。L1 使用绝对值之和,常有利于稀疏;L2 使用平方和,鼓励较小权重。若采用 0.5*lambda*sum(w²),其梯度就是 lambda*w,应明确系数约定。

实例 ​

python
import numpy as np


def parameter_penalties(parameters, l1_strength, l2_strength):
    vector = np.asarray(parameters, dtype=float)
    l1_value = l1_strength * np.abs(vector).sum()
    l1_subgradient = l1_strength * np.sign(vector)
    l2_value = 0.5 * l2_strength * np.square(vector).sum()
    l2_gradient = l2_strength * vector
    return {
        "l1_value": float(l1_value),
        "l1_subgradient": l1_subgradient,
        "l2_value": float(l2_value),
        "l2_gradient": l2_gradient,
    }


weights_for_demo = np.array([1.2, -1.8, 2.6, 0.4, 0.0])
penalties = parameter_penalties(weights_for_demo, l1_strength=0.08, l2_strength=0.1)
for name, value in penalties.items():
    print(name, value)
print("L1 在零处不可微,本例取零作为次梯度。")
print("实际训练通常把惩罚并入目标,或明确使用解耦的权重衰减。")

L2 倾向缩小权重,不代表参数绝不会等于零。L1 的稀疏效果也与优化方法和任务有关。AdamW 的解耦衰减与把 L2 项直接加到 Adam 的损失里,需要分别理解。

Dropout ​

Dropout 在训练时随机屏蔽部分激活,减弱模型对固定组合的依赖。常见的 inverted dropout 在保留部分上除以保留概率,使其期望与输入一致;评估时直接使用全部激活。

实例 ​

这个实现训练和评估都返回“结果、掩码”二元组,避免调用者因模式变化而收到不同数据结构。随机数生成器显式传入,便于复查演示过程。

python
import numpy as np


def inverted_dropout(values, drop_probability, generator, training=True):
    array = np.asarray(values, dtype=float)
    if not 0.0 <= drop_probability < 1.0:
        raise ValueError("丢弃概率需要位于零到一之间且不能等于一")
    if not training or drop_probability == 0.0:
        return array.copy(), np.ones_like(array, dtype=bool)
    keep_probability = 1.0 - drop_probability
    retained = generator.random(array.shape) < keep_probability
    scaled = array * retained / keep_probability
    return scaled, retained


generator = np.random.default_rng(41)
activation_vector = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
for repetition in range(3):
    transformed, mask = inverted_dropout(activation_vector, 0.4, generator, training=True)
    print(f"训练示例 {repetition + 1}:保留位置 {mask},结果 {transformed}")
evaluation_values, evaluation_mask = inverted_dropout(
    activation_vector, 0.4, generator, training=False
)
print("评估时结果:", evaluation_values)
print("评估时所有位置保留:", evaluation_mask)

某一次随机输出不需要和输入均值相同,保持的是随机过程的期望。Dropout 也不是越大越好,过强时可能导致欠拟合,推理前必须切换到正确模式。

数据增强 ​

图像中可以使用翻转、旋转、裁剪、缩放和颜色变化;文本可以尝试同义替换、删改或回译。但变化应尽量保留标签含义,例如左右方向本身是标签时就不能随意镜像,文本删除否定词也可能把意思翻转。

增强用于训练数据,不应把验证集的结果反复拿来构造训练样本。验证和测试流程应稳定,避免输入泄漏或评估口径变化。

手段基本思路潜在收益主要限制
参数惩罚限制权重规模或形态结构简单,可控制强度过强时也会妨碍拟合
Dropout随机移除部分激活减少固定共适应需区分训练与评估模式
数据增强生成保持语义的输入变化增加有效多样性依赖领域知识
早停验证不再改善时停止限制继续过拟合需要合适验证集与耐心值
批归一化使用统计归一化并学习缩放可改善优化,也可能带来正则效果依赖批统计并增加状态

批归一化与层归一化 ​

归一化通常对激活求均值、方差,标准化后再使用可学习缩放与偏移。两种常见方法的主要差别是对哪些维度统计,以及评估阶段怎样处理。

内部协变量偏移这一解释 ​

网络参数改变时,后层看到的输入分布也会改变。“内部协变量偏移”是提出批归一化时使用的解释。后续研究也从优化平滑性等角度理解其效果,因此不能把减少这种偏移当作所有归一化收益的唯一、已证明原因。

归一化也不保证每层分布始终固定。可学习缩放、任务分布和网络结构仍会改变激活,应根据训练实际表现评估。

Batch Normalization 的统计方式 ​

对二维 (batch, features) 输入,BatchNorm 按每列统计批均值与方差,再标准化、乘 gamma、加 beta。训练时通常维护运行统计,评估时使用保存的估计;卷积输入还会包含相应空间维度。

实例 ​

下面仅实现二维教学版本。update_fraction 表示新批统计的权重,运行均值使用 (1-a)*old+a*batch,与优化器动量不是一个概念。运行方差使用无偏估计,当前批归一化使用有偏方差,与 PyTorch 的相关约定保持一致。

python
import numpy as np


class BatchFeatureNormalizer:
    def __init__(self, width, update_fraction=0.1, epsilon=1e-5):
        if width < 1 or not 0.0 < update_fraction <= 1.0:
            raise ValueError("特征数量与更新比例不合适")
        self.scale = np.ones(width)
        self.shift = np.zeros(width)
        self.running_mean = np.zeros(width)
        self.running_variance = np.ones(width)
        self.update_fraction = update_fraction
        self.epsilon = epsilon

    def forward(self, values, training=True):
        batch = np.asarray(values, dtype=float)
        if batch.ndim != 2 or batch.shape[1] != len(self.scale):
            raise ValueError("输入必须是匹配特征数的二维批次")
        if training:
            if batch.shape[0] < 2:
                raise ValueError("教学训练版本至少需要两个样本")
            center = batch.mean(axis=0)
            variance = batch.var(axis=0, ddof=0)
            unbiased_variance = batch.var(axis=0, ddof=1)
            fraction = self.update_fraction
            self.running_mean = (1.0 - fraction) * self.running_mean + fraction * center
            self.running_variance = (
                (1.0 - fraction) * self.running_variance + fraction * unbiased_variance
            )
        else:
            center = self.running_mean
            variance = self.running_variance
        standardized = (batch - center) / np.sqrt(variance + self.epsilon)
        return self.scale * standardized + self.shift


toy_batch = np.array([[1.0, 2.0, 4.0], [2.0, 4.0, 5.0], [3.0, 5.0, 7.0], [4.0, 7.0, 8.0]])
normalizer = BatchFeatureNormalizer(width=3)
training_output = normalizer.forward(toy_batch, training=True)
evaluation_output = normalizer.forward(toy_batch[:2], training=False)
print("训练输出:", training_output)
print("列均值:", training_output.mean(axis=0))
print("列方差:", training_output.var(axis=0))
print("保存的运行均值:", normalizer.running_mean)
print("保存的运行方差:", normalizer.running_variance)
print("评估输出:", evaluation_output)

一批训练后的运行统计还不代表总体,评估输出不必也呈现零均值和单位方差。BatchNorm 在许多视觉模型中有用,但小批次、分布变化和模式切换都要注意。它并非绝对不能用于序列,只是序列长度、掩码和跨样本统计使设计更复杂。具体规则可从 BatchNorm1d 文档查看。

Layer Normalization 的统计方式 ​

LayerNorm 对每个样本或序列位置内部的指定特征维度统计,不依赖其他样本的数值。常见输入为 (batch, sequence, features),若只归一化最后一维,每个位置分别计算均值与方差。

实例 ​

python
import numpy as np


def normalize_last_features(values, scale, shift, epsilon=1e-5):
    array = np.asarray(values, dtype=float)
    scale_array = np.asarray(scale, dtype=float)
    shift_array = np.asarray(shift, dtype=float)
    if scale_array.shape != (array.shape[-1],) or shift_array.shape != scale_array.shape:
        raise ValueError("缩放与偏移需匹配最后一个维度")
    mean_per_position = array.mean(axis=-1, keepdims=True)
    variance_per_position = array.var(axis=-1, keepdims=True)
    normalized = (array - mean_per_position) / np.sqrt(variance_per_position + epsilon)
    return normalized * scale_array + shift_array


sequence_batch = np.array([
    [[1.0, 3.0, 2.0, 5.0], [2.0, 4.0, 3.0, 6.0], [3.0, 5.0, 4.0, 7.0]],
    [[4.0, 6.0, 5.0, 8.0], [5.0, 7.0, 6.0, 9.0], [6.0, 8.0, 7.0, 10.0]],
])
normalized_sequence = normalize_last_features(sequence_batch, np.ones(4), np.zeros(4))
print("输入与输出维度:", sequence_batch.shape, normalized_sequence.shape)
print("每个位置的特征均值:", normalized_sequence.mean(axis=-1))
print("每个位置的特征方差:", normalized_sequence.var(axis=-1))
single_sample = normalize_last_features(sequence_batch[:1], np.ones(4), np.zeros(4))
print("移除其他批样本后结果一致:", np.allclose(single_sample, normalized_sequence[:1]))

这里 gamma 为一、beta 为零,输出均值才近似零;学习后不应要求输出继续保持这个数值。LayerNorm 在训练和评估中通常都使用当前输入统计,不维护 BatchNorm 式运行均值。

方法常见统计维度与批大小的关系常见用途例子与限制
BatchNorm对每个特征汇总批次,卷积时还含空间位置统计受批次影响多种 CNNResNet 等;小批次要谨慎
LayerNorm每个样本或位置的指定特征轴不汇总其他样本Transformer 与部分序列网络BERT、GPT 类结构常见

并非所有语言模型都用同一种 LayerNorm。部分 Llama 架构采用 RMSNorm,它与减均值的 LayerNorm 不同。实现时应查看模型定义,不能把“序列模型常用归一化”理解为所有模型细节相同。API 的维度约定可从 LayerNorm 文档检查。

学习率调度 ​

学习率过大可能使更新振荡或发散,过小可能导致进展缓慢。调度是在训练过程中按步骤或验证结果改变步长,并不是代替基本的优化诊断。

Warmup:逐步增加起始步长 ​

预热先用较小学习率,再升到目标值,可帮助某些模型在训练早期稳定。它在不少 Transformer 流程中常见,但预热时长并无通用答案,应结合优化器、批大小和训练目标选择。

用余弦曲线降低学习率 ​

余弦退火把学习率从起点平滑降向下限,可以与预热相接。要先定义 step 是更新前还是更新后的编号,并处理总步数与预热步数的边界,避免除以零和末端反弹。

实例 ​

以下以从零开始的更新编号定义:前若干步升到峰值,随后在最后一次计划更新降到最低值;超过计划范围时保持最低值。

python
import math


def linear_warmup(step, warmup_count, peak_rate):
    if step < 0 or warmup_count < 0:
        raise ValueError("步数不能为负")
    if warmup_count == 0 or step >= warmup_count:
        return peak_rate
    return peak_rate * (step + 1) / warmup_count


def cosine_decay(step, total_count, peak_rate, minimum_rate=0.0):
    if total_count < 2 or not 0 <= minimum_rate <= peak_rate:
        raise ValueError("总更新次数与学习率边界不合适")
    progress = min(max(step / (total_count - 1), 0.0), 1.0)
    return minimum_rate + 0.5 * (peak_rate - minimum_rate) * (1.0 + math.cos(math.pi * progress))


def warmup_then_cosine(step, warmup_count, total_count, peak_rate, minimum_rate=0.0):
    if not 0 <= warmup_count < total_count:
        raise ValueError("预热次数必须小于总更新次数")
    if step < warmup_count:
        return linear_warmup(step, warmup_count, peak_rate)
    decay_count = total_count - warmup_count
    if decay_count == 1:
        return minimum_rate
    return cosine_decay(step - warmup_count, decay_count, peak_rate, minimum_rate)


total_updates = 100
preheat_updates = 10
for update in (0, 4, 9, 10, 25, 50, 75, 99, 100):
    print(
        update,
        linear_warmup(update, preheat_updates, 1e-3),
        cosine_decay(update, total_updates, 1e-3, 1e-5),
        warmup_then_cosine(update, preheat_updates, total_updates, 1e-3, 1e-5),
    )

学习率怎样影响训练 ​

出现损失突然增大时,应检查步长、数据异常和数值问题;下降很慢时,也要看梯度是否过小、模型容量与数据是否合适,不能把所有现象都归结为学习率。

学习率范围测试可以在保存初始状态后,用逐渐增大的候选值短暂观察损失,再恢复状态选择正式配置。测试过程也会改变权重,不应直接把最后状态当作正式起点。

调度方式改变方式适用考虑
固定步长全程保持不变简单基线,便于理解
分段衰减到指定步数降低阶段清楚的训练计划
余弦退火平滑逐步降低希望后期细化更新
预热加余弦前期上升、后期下降不少 Transformer 流程
平台期降低根据验证指标变化调整需要稳定监控与耐心值

实战:用 PyTorch 组织完整 MLP ​

最后把数据、模型、损失、AdamW、调度、训练、验证与推理串起来。合成二分类任务的规则是前五个特征之和是否为正,其余特征只作干扰。它是教学问题,准确率不能证明现实任务表现。

实例 ​

脚本只使用 CPU,不下载外部模型,不访问服务。它生成一份数据后再划分,避免分别创建训练、验证数据时重复重置随机种子而产生重叠样本。代码会在运行目录写一个 mlp-demo-checkpoint.pt,实际运行前应选择合适目录;本文未执行此训练或创建检查点。

python
import copy
import math
from pathlib import Path

import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, Dataset, random_split


class SyntheticSignDataset(Dataset):
    """按固定数学规则构造二分类样本,不代表真实业务。"""

    def __init__(self, sample_count=1000, feature_count=10, seed=173):
        if sample_count < 2 or feature_count < 5:
            raise ValueError("样本至少两个,特征至少五个")
        generator = np.random.default_rng(seed)
        values = generator.normal(size=(sample_count, feature_count)).astype(np.float32)
        labels = (values[:, :5].sum(axis=1) > 0.0).astype(np.int64)
        self.features = torch.from_numpy(values)
        self.labels = torch.from_numpy(labels)

    def __len__(self):
        return self.features.shape[0]

    def __getitem__(self, position):
        return self.features[position], self.labels[position]


class TabularMLP(nn.Module):
    def __init__(self, input_width=10, hidden_widths=(48, 24), class_count=2, drop_probability=0.1):
        super().__init__()
        operations = []
        previous_width = input_width
        for width in hidden_widths:
            operations.extend([
                nn.Linear(previous_width, width),
                nn.ReLU(),
                nn.LayerNorm(width),
                nn.Dropout(p=drop_probability),
            ])
            previous_width = width
        operations.append(nn.Linear(previous_width, class_count))
        self.layers = nn.Sequential(*operations)

    def forward(self, batch):
        return self.layers(batch)


def schedule_factor(update_index, warmup_updates, planned_updates, floor_fraction=0.01):
    if update_index < warmup_updates:
        return (update_index + 1) / max(warmup_updates, 1)
    denominator = max(planned_updates - warmup_updates - 1, 1)
    progress = min(max((update_index - warmup_updates) / denominator, 0.0), 1.0)
    cosine_part = 0.5 * (1.0 + math.cos(math.pi * progress))
    return floor_fraction + (1.0 - floor_fraction) * cosine_part


def evaluate(network, batches, objective):
    network.eval()
    total_loss = 0.0
    total_correct = 0
    total_examples = 0
    with torch.no_grad():
        for features, labels in batches:
            scores = network(features)
            loss = objective(scores, labels)
            count = labels.shape[0]
            total_loss += loss.item() * count
            total_correct += int((scores.argmax(dim=1) == labels).sum().item())
            total_examples += count
    if total_examples == 0:
        raise ValueError("验证集合不能为空")
    return total_loss / total_examples, total_correct / total_examples


def train_demo(checkpoint_path=Path("mlp-demo-checkpoint.pt")):
    torch.manual_seed(173)
    dataset = SyntheticSignDataset(sample_count=1000, feature_count=10, seed=173)
    split_generator = torch.Generator().manual_seed(911)
    training_subset, validation_subset = random_split(dataset, [800, 200], generator=split_generator)
    assert not (set(training_subset.indices) & set(validation_subset.indices))
    loader_generator = torch.Generator().manual_seed(317)
    training_batches = DataLoader(
        training_subset, batch_size=32, shuffle=True,
        generator=loader_generator, num_workers=0,
    )
    validation_batches = DataLoader(validation_subset, batch_size=32, shuffle=False, num_workers=0)
    network = TabularMLP(input_width=10, hidden_widths=(48, 24), class_count=2)
    objective = nn.CrossEntropyLoss()
    optimizer = torch.optim.AdamW(network.parameters(), lr=1e-3, weight_decay=1e-4)
    epochs = 20
    planned_updates = epochs * len(training_batches)
    warmup_updates = 2 * len(training_batches)
    scheduler = torch.optim.lr_scheduler.LambdaLR(
        optimizer,
        lr_lambda=lambda index: schedule_factor(index, warmup_updates, planned_updates),
    )
    best_accuracy = -1.0
    best_state = None
    completed_updates = 0
    print("数据划分:", len(training_subset), len(validation_subset))
    print("网络结构:", network)
    print("计划更新与预热:", planned_updates, warmup_updates)

    for epoch_index in range(epochs):
        network.train()
        accumulated_loss = 0.0
        correct_predictions = 0
        example_count = 0
        for features, labels in training_batches:
            optimizer.zero_grad(set_to_none=True)
            logits = network(features)
            loss = objective(logits, labels)
            loss.backward()
            optimizer.step()
            scheduler.step()
            completed_updates += 1
            batch_count = labels.shape[0]
            accumulated_loss += float(loss.item()) * batch_count
            correct_predictions += int((logits.argmax(dim=1) == labels).sum().item())
            example_count += batch_count

        training_loss = accumulated_loss / example_count
        training_accuracy = correct_predictions / example_count
        validation_loss, validation_accuracy = evaluate(network, validation_batches, objective)
        if validation_accuracy > best_accuracy:
            best_accuracy = validation_accuracy
            best_state = copy.deepcopy(network.state_dict())
            torch.save(
                {
                    "model_state": best_state,
                    "epoch": epoch_index + 1,
                    "validation_accuracy": best_accuracy,
                    "input_width": 10,
                    "hidden_widths": [48, 24],
                    "class_count": 2,
                    "data_seed": 173,
                },
                checkpoint_path,
            )
        next_rate = optimizer.param_groups[0]["lr"]
        print(
            f"轮次 {epoch_index + 1:02d},下一步学习率 {next_rate:.7f},"
            f"训练损失 {training_loss:.4f},训练准确率 {training_accuracy:.3f},"
            f"验证损失 {validation_loss:.4f},验证准确率 {validation_accuracy:.3f}"
        )

    if best_state is None:
        raise RuntimeError("没有可用于演示的模型状态")
    network.load_state_dict(best_state)
    network.eval()
    test_vectors = torch.tensor([
        [1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0],
        [-1.0, -1.0, -1.0, -1.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0],
    ], dtype=torch.float32)
    expected_labels = torch.tensor([1, 0])
    with torch.no_grad():
        test_logits = network(test_vectors)
        test_probabilities = torch.softmax(test_logits, dim=-1)
        predicted_labels = test_probabilities.argmax(dim=-1)
    print("实际完成更新数:", completed_updates)
    print("最佳验证准确率:", best_accuracy)
    print("检查点路径:", checkpoint_path.resolve())
    print("演示输入的规则标签:", expected_labels.tolist())
    print("模型预测:", predicted_labels.tolist())
    print("模型概率:", test_probabilities)
    return network


if __name__ == "__main__":
    train_demo()

流程里的 Dataset 与 DataLoader 负责样本读取和批次,MLP 负责 logits,交叉熵把 logits 与类别标签比较;zero_grad 清理旧梯度,backward 求导,优化器更新,调度器安排下一步学习率。训练模式启用 Dropout,验证模式关闭它,并用 no_grad 避免建立无用的梯度图。

日志中的损失按样本数加权,避免最后一个小批次与完整批次具有相同权重。验证集只用于选择候选状态,严格评估泛化时还需要独立测试集。检查点保存了最佳模型与少量元信息,若要中断后继续训练,还应保存优化器、调度器和随机状态;不要读取不可信检查点。

推理示例使用验证表现最好的状态,而不是默认最后一轮一定最好。这里没有给出准确率示意数字,实际运行结果受依赖、初始化和数值环境影响。将流程迁移到真实任务时,还需重新设计数据划分、指标、权限和资源预算,不能把一个合成任务的训练脚本直接视为完整生产系统。