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

TensorFlow 自定义组件

从 Keras 层、损失和指标开始,实际验证自定义训练步、序列化、图编译和两种专项模型运算。

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

学完这一章,你能够

选择扩展位置

层定义可复用的前向计算,损失衡量训练目标,指标维护观察状态,自定义训练循环控制每步更新。本章先验证线性投影,再把自定义损失、求导、优化器和指标放进同一次训练。

特殊卷积、注意力变体与推荐特征交叉通常放在层里。研究网络可组合自定义层与正则化,硬件专用内核和混合精度则需要额外验证支持范围、数值误差和吞吐。

创建、跟踪并恢复层的状态

在 __init__ 保存配置,在 build 按输入的末轴建立权重,在 call 计算前向输出。add_weight 可让 Keras 3 跟踪可训练参数。直接赋给属性的 tf.Variable 不会自动加入 trainable_weights。把同一个层对象接到两个分支即可共享参数。

需要重建时,get_config 先合并父类配置,再保存自己的宽度,并给类注册序列化名。保存 .keras 后重载,本站核对了层名称、输出宽度、权重改变后的两组预测和注册配置。

让损失先保持样本维度

函数形式的均方差只在特征轴求均值,留下每个样本的损失。Loss 子类可在 call 加入逐样本的预测惩罚,再由基类执行 reduction。活动惩罚应明确归一方式,整批求和再与单个均方差标量相加会使目标随批大小变化。

用 GradientTape 观察惩罚项的梯度。输入先检查形状与取值范围,明确分母为零时的数学约定;可选择稳定运算、有限值检查等方法。加 epsilon 只适用于定义允许的计算。

用真实的训练步和指标核对更新

变量创建后,tf.function 可按签名跟踪训练步。先前向求逐样本损失并取平均,再用 GradientTape 求梯度,由 apply_gradients 更新权重。固定样本实测两步损失为 10 和 2.5,内核变为 1.5。指标经过四个样本的均值为 6.25,重置后为 0。

初始权重 0,第一步损失 10,第二步损失 2.5,两步后权重 1.5。
按本站训练步实际返回值绘制,损失为各步更新前的值。

区分图追踪、精度策略和 XLA

签名定义可接受的秩和类型。首次调用跟踪 TensorFlow 操作,稳定签名可减少重追踪。先核对实际图和跟踪次数,再单独测量运行速度。

先设置 mixed_float16,再建立采用该策略的层。这个实验观察到 float16 计算和 float32 权重,最后恢复全局策略。需要在目标硬件上测量吞吐,训练场景还要核对损失缩放及数值稳定性。

旧写法 tf.config.optimizer.set_jit(True) 是自动聚类设置。本站用 tf.function(jit_compile=True) 明确编译一个 CPU 函数,检查输出 32 和优化后的 HLO。GPU、TPU 及未被编译器支持的算子需要各自验证。

用可比较的输入调试层与应用

单元测试同时断言输出形状和数值。遇到 NaN 时优先定位无效运算;学习率影响更新幅度,裁剪限制已经计算出的梯度范数。图模式也可能因为输入签名频繁变化而增加追踪成本。

像素重排把通道位置变成空间位置。NHWC 输入 [1,1,1,4] 用放大倍率 2,输出为 [1,2,2,1],像素排列为第一行 1、2,第二行 3、4。输入通道数需能被放大倍率平方整除。

分位数损失对预测偏低与偏高赋予不同斜率。给各列明确分位数并逐样本计算,再决定如何归约。站内例使用 0.25、0.5、0.75,检查已知正误差和负误差形成的两组损失。

权重的三种处理方式

方式状态适用条件
add_weight()加入层的受跟踪权重集合。指定形状、初始化器与 trainable,随后由训练与保存流程处理。
直接给层挂接变量直接挂接 tf.Variable 在 Keras 3 不自动注册为权重。需要跟踪时可用 add_weight 或 keras.Variable,特殊初始化也可用初始化器。
共享同一个层多次调用同一层对象保留同一份权重。让不同输入分支执行共享投影,训练时按共享变量处理。

调试信号与核对方法

现象检查方向可验证对照
损失为 NaN输入或中间运算不满足数值条件。先测无效除法,再验证符合定义的安全除法或稳定公式。
梯度范数过大较大的梯度与过大的更新需要分别诊断。比较裁剪前后范数,并按实际训练检查学习率与优化器。
步骤耗时过长重复追踪、数据搬运或设备选择都可能影响批次时间。核对 tf.function 的跟踪次数,再对照等价输入下的时间和数值。

从权重跟踪到两步自定义训练

python · 阅读源码
"""Exercise Keras custom layers, objectives and a compiled training step."""
import json
from pathlib import Path
import platform
from tempfile import TemporaryDirectory

import tensorflow as tf


@tf.keras.utils.register_keras_serializable(package="BlueSky")
class SumProjection(tf.keras.layers.Layer):
    def __init__(self, width, **kwargs):
        super().__init__(**kwargs)
        self.width = width

    def build(self, input_shape):
        self.kernel = self.add_weight(
            name="kernel", shape=(input_shape[-1], self.width), initializer="ones"
        )
        self.offset = self.add_weight(name="offset", shape=(self.width,), initializer="zeros")

    def call(self, value):
        return tf.linalg.matmul(value, self.kernel) + self.offset

    def get_config(self):
        return {**super().get_config(), "width": self.width}


def row_mse(target, prediction):
    return tf.reduce_mean(tf.square(target - prediction), axis=-1)


@tf.keras.utils.register_keras_serializable(package="BlueSky")
class PenalizedMSE(tf.keras.losses.Loss):
    def __init__(self, strength=0.5, **kwargs):
        super().__init__(**kwargs)
        self.strength = strength

    def call(self, target, prediction):
        penalty = self.strength * tf.reduce_mean(tf.abs(prediction), axis=-1)
        return row_mse(target, prediction) + penalty

    def get_config(self):
        return {**super().get_config(), "strength": self.strength}


def percentile_loss(target, predictions, quantiles):
    error = target - predictions
    return tf.reduce_sum(tf.maximum(quantiles * error, (quantiles - 1) * error), axis=-1)


class BatchLossMean(tf.keras.metrics.Metric):
    def __init__(self, name="batch_loss_mean"):
        super().__init__(name=name)
        self.total = self.add_weight(name="total", initializer="zeros")
        self.count = self.add_weight(name="count", initializer="zeros")

    def update_state(self, losses):
        self.total.assign_add(tf.reduce_sum(losses))
        self.count.assign_add(tf.cast(tf.size(losses), self.count.dtype))

    def result(self):
        return tf.math.divide_no_nan(self.total, self.count)

    def reset_state(self):
        self.total.assign(0)
        self.count.assign(0)


class UntrackedVariableLayer(tf.keras.layers.Layer):
    def build(self, input_shape):
        self.scaling = tf.Variable(2.0, trainable=True)

    def call(self, inputs):
        return inputs * self.scaling


class ProjectionTests(tf.test.TestCase):
    def test_output_shape_and_values(self):
        layer = SumProjection(2, name="example")
        output = layer(tf.constant([[4.0, 7.0], [3.0, -2.0]]))
        self.assertEqual(output.shape, (2, 2))
        self.assertAllClose(output, [[11.0, 11.0], [1.0, 1.0]])


def observe(cases, name, inputs, prerequisites, action, expected, actual):
    assert expected == actual, (name, expected, actual)
    cases.append(dict(name=name, inputs=inputs, prerequisites=prerequisites,
                      action=action, expected=expected, actual=actual, passed=True))


def examples(cases):
    data = tf.constant([[4.0, 7.0], [3.0, -2.0]])
    test = ProjectionTests("test_output_shape_and_values")
    test.test_output_shape_and_values()
    layer = SumProjection(2, name="tied_projection")
    first = layer(data)
    observe(cases, "custom_layer_build", data.numpy().tolist(), "First call builds kernel and bias",
            "Check shape, values and tracked weights, including the tf.test.TestCase assertions",
            [[2, 2], [[11.0, 11.0], [1.0, 1.0]], 2],
            [list(first.shape), first.numpy().tolist(), len(layer.trainable_weights)])
    model = tf.keras.Sequential([tf.keras.Input((2,)), layer])
    layer.kernel.assign([[2.0, 3.0], [2.0, 3.0]])
    layer.offset.assign([1.0, -1.0])
    with TemporaryDirectory(prefix="tf-custom-layer-") as directory:
        path = Path(directory) / "sum.keras"
        model.save(path)
        reload = tf.keras.models.load_model(path)
        actual = [reload.layers[0].name, reload.layers[0].width, reload(data).numpy().tolist()]
        observe(cases, "keras_config_roundtrip", [2, "tied_projection"], "Registered custom class and .keras file",
                "Reload config, trained-like weights and prediction in a new model",
                ["tied_projection", 2, [[23.0, 32.0], [3.0, 2.0]]], actual)
    raw = UntrackedVariableLayer()
    direct = float(raw(tf.constant(3.0)))
    left = tf.keras.Input((2,))
    right = tf.keras.Input((2,))
    tied = tf.keras.Model([left, right], [layer(left), layer(right)])
    outputs = tied([data[:1], data[1:]])
    observe(cases, "weight_tracking_and_sharing", [3, 2], "Keras 3, direct tf.Variable and reused tracked layer",
            "Compare direct variable discovery with a layer shared by both branches",
            [6.0, 0, 2, [[23.0, 32.0]], [[3.0, 2.0]]],
            [direct, len(raw.trainable_weights), len(tied.trainable_weights),
             outputs[0].numpy().tolist(), outputs[1].numpy().tolist()])

    estimate = tf.Variable([[0.0, 3.0], [2.0, 6.0]])
    zeros = tf.zeros_like(estimate)
    mse = row_mse(zeros, estimate)
    observe(cases, "per_sample_mse", estimate.numpy().tolist(), "Match shape [batch, channels]",
            "Reduce channels while preserving the two samples", [4.5, 20.0], mse.numpy().tolist())
    loss = PenalizedMSE(reduction="none")
    with tf.GradientTape() as tape:
        values = loss(zeros, estimate)
        objective = tf.reduce_mean(values)
    gradient = tape.gradient(objective, estimate)
    restored = tf.keras.losses.deserialize(tf.keras.losses.serialize(loss))
    observe(cases, "penalized_loss_class", estimate.numpy().tolist(), "Batch of two with per-sample penalty",
            "Verify loss, registered config, expected gradients and reduction",
            [[5.25, 22.0], 0.5, [[0.0, 1.625], [1.125, 3.125]]],
            [values.numpy().tolist(), restored.strength, gradient.numpy().tolist()])

    linear = tf.keras.Sequential([tf.keras.Input((1,)),
        tf.keras.layers.Dense(1, use_bias=False, kernel_initializer="zeros")])
    optimizer = tf.keras.optimizers.SGD(0.1)
    optimizer.build(linear.trainable_weights)
    metric = BatchLossMean()

    @tf.function(input_signature=[tf.TensorSpec([None, 1], tf.float32),
                                  tf.TensorSpec([None, 1], tf.float32)])
    def update(features, targets):
        with tf.GradientTape() as tape:
            losses = row_mse(targets, linear(features, training=True))
            mean = tf.reduce_mean(losses)
        gradients = tape.gradient(mean, linear.trainable_weights)
        optimizer.apply_gradients(zip(gradients, linear.trainable_weights))
        metric.update_state(losses)
        return mean

    features = tf.constant([[1.0], [2.0]])
    targets = 2 * features
    before = [float(update(features, targets)), float(update(features, targets))]
    observe(cases, "compiled_custom_step", [1, 2], "Built variables; CPU; fixed rank and dynamic batch axis",
            "Run two real optimizer steps and read the weight, graph trace count and iteration counter",
            [[10.0, 2.5], 1.5, 2, 1],
            [before, float(linear.layers[0].kernel[0, 0]), int(optimizer.iterations),
             update.experimental_get_tracing_count()])
    seen = float(metric.result())
    metric.reset_state()
    observe(cases, "metric_state_and_reset", [4, 16, 1, 4], "Two updates populated a four-sample state",
            "Read the accumulated metric and reset it",
            [6.25, 0.0], [seen, float(metric.result())])

    invalid = tf.math.divide_no_nan(0.0, 0.0)
    nan = tf.math.divide(0.0, 0.0)
    clipped, norm = tf.clip_by_global_norm([tf.constant([6.0, 8.0])], 5.0)
    observe(cases, "stability_and_clip", [0, 0, 6, 8], "Use an explicitly chosen zero-denominator convention",
            "Observe NaN, guarded division and gradient vector with reduced norm",
            [True, 0.0, 10.0, [3.0, 4.0]],
            [bool(tf.math.is_nan(nan)), float(invalid), float(norm), clipped[0].numpy().tolist()])

    saved = tf.keras.mixed_precision.global_policy()
    try:
        tf.keras.mixed_precision.set_global_policy("mixed_float16")
        mixed = SumProjection(2)
        values = mixed(data)
        actual = [mixed.compute_dtype, mixed.variable_dtype, values.dtype.name]
    finally:
        tf.keras.mixed_precision.set_global_policy(saved)
    observe(cases, "mixed_precision_policy", "mixed_float16", "CPU exercise observes types only",
            "Construct after changing policy, infer and restore the previous policy",
            ["float16", "float32", "float16", True], actual + [tf.keras.mixed_precision.global_policy() == saved])

    @tf.function(jit_compile=True)
    def compiled(vector):
        return tf.reduce_sum(tf.square(vector) + 1)

    vector = tf.constant([2, 3, 4])
    value = int(compiled(vector))
    hlo = compiled.experimental_get_compiler_ir(vector)(stage="optimized_hlo")
    observe(cases, "cpu_xla", [2, 3, 4], "TensorFlow CPU with XLA compilation",
            "Compile with jit_compile and inspect optimized HLO",
            [32, True], [value, "HloModule" in hlo and "ENTRY" in hlo])

    packed = tf.constant([[[[1.0, 2.0, 3.0, 4.0]]]])
    transformed = tf.nn.depth_to_space(packed, 2)
    observe(cases, "pixel_shuffle", [1, 1, 1, 4], "NHWC, scale 2, channels divisible by scale squared",
            "Rearrange four channels into two rows of pixels",
            [[1, 2, 2, 1], [[1.0, 2.0], [3.0, 4.0]]],
            [list(transformed.shape), tf.squeeze(transformed).numpy().tolist()])
    quantiles = tf.constant([0.25, 0.5, 0.75])
    target = tf.constant([[4.0], [1.0]])
    expected = [0.5, 2.25]
    predictions = tf.constant([[3.0, 4.0, 5.0], [3.0, 1.0, 0.0]])
    result = percentile_loss(target, predictions, quantiles)
    observe(cases, "pinball_percentiles", [0.25, 0.5, 0.75],
            "Each column predicts one quantile, one target is broadcast per sample",
            "Observe asymmetric loss for under- and overprediction",
            expected, result.numpy().tolist())


if __name__ == "__main__":
    observations = []
    examples(observations)
    print(json.dumps(dict(version=platform.python_version(), tensorflow=tf.__version__,
                          keras=tf.keras.__version__, system=platform.system(),
                          devices=[device.name for device in tf.config.list_physical_devices()],
                          cases=observations), ensure_ascii=True))
预期结果 · 待实际运行核验
  • 本站程序核对 12 项行为。训练的两步损失为 10 和 2.5;像素重排产出约定的 2×2 布局。
从权重跟踪到两步自定义训练

所需环境:Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。

当前源码 SHA256:d75a4f6a4ec56d5fedfb56ce9321103fa9aa4b890ead783d803e15802b9fe6a0

下载本站示例源码

本地运行

解压后按 README 运行本站程序。

下载TensorFlow 自定义组件实例

所需环境:Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。

ZIP SHA256:72f48d78a3011f75e2b2d8bc71bd3a9d544b8b7c10681c74952f0bd4e89139d6

常见错误与边界

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

练习与解答

为什么均方差先保留批次轴?

展开参考解答

这样才能按样本加权和累积,再明确由哪个阶段求整体均值。

规范与官方依据