如何将图像和标签序列化为 TFRecord 并在训练时反序列化?请描述 Protocol Buffer 的作用。

解读

在国内工业级 TensorFlow 面试中,这道题几乎必问。它同时考察三点:

  1. 是否理解 TFRecord 是 Google 官方推荐的“大数据集统一容器”;
  2. 是否能把图像、标签等异构数据高效地塞进一个可顺序读取的二进制文件,避免训练阶段 Python 解码成为瓶颈;
  3. 是否明白 Protocol Buffer(后文简称 PB)只是“描述文件格式”的 DSL,真正的序列化/反序列化由 TensorFlow 的 C++ 内核完成,Python 层只负责“填字段”。

面试官希望听到“写-读-性能”三板斧:写阶段用 tf.io.serialize_tensor + tf.train.Example;读阶段用 tf.data.TFRecordDataset + tf.io.parse_single_example;性能阶段用 .batch().prefetch() 并打开 num_parallel_reads。只要能把这条链路讲闭环,就能拿到基础分;再补充 PB 的跨语言、前后向兼容、强类型校验等特性,可拉开差距。

知识点

  1. TFRecord 本质:顺序追加的 RecordIO 文件,每条记录带 8-byte 长度校验,适合大规模分布式读取。
  2. tf.train.Example 协议:PB 消息,顶层只有 Features 字段,内部是 map<string, Feature>;Feature 支持三种容器:BytesList、FloatList、Int64List。
  3. 图像三种存法:① 直接存 JPEG/PNG 原始字节(推荐,省磁盘);② 存解码后的 uint8 扁平向量;③ 存 float32 归一化向量。国内大厂普遍用①,因为 tf.image.decode_image 在 C++ 端做,GPU 预处理流水线零拷贝。
  4. 标签同步:图像与标签必须落在同一条 Example,避免 shuffle 后错位;多任务场景用 feature 多字段即可。
  5. PB 作用:① 跨语言生成读写代码(Python/C++/Java/Go);② 字段编号机制保证新旧版本兼容;③ 强类型 + 字段缺失默认值,避免手写字节偏移错误。
  6. 性能调优:tf.data 的 map(..., num_parallel_calls=tf.data.AUTOTUNE) 与 prefetch(tf.data.AUTOTUNE) 组合,可把解码、增强、拷贝全部下沉到 C++ 线程池,Python GIL 不再是瓶颈。

答案

(以下代码可直接在 TF 2.x 环境运行,默认图像已缩放至统一尺寸,仅演示核心链路)

  1. 序列化(写 TFRecord)
import tensorflow as tf
import pathlib, json

def _bytes_feature(value):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

def _int64_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

def image_example(image_path, label_id):
    img_raw = tf.io.read_file(image_path)          # 保持原始编码
    return tf.train.Example(features=tf.train.Features(feature={
        'image': _bytes_feature(img_raw.numpy()),
        'label': _int64_feature(label_id),
    })).SerializeToString()

def write_tfrecord(image_dir, label_map_json, out_file):
    label_map = json.load(open(label_map_json))    # {"cat": 0, "dog": 1}
    writer = tf.io.TFRecordWriter(out_file)
    for img_path in pathlib.Path(image_dir).rglob('*.jpg'):
        label_name = img_path.parent.name
        example = image_example(str(img_path), label_map[label_name])
        writer.write(example)
    writer.close()
  1. 反序列化(训练时读取)
def parse_fn(serialized):
    feature_desc = {
        'image': tf.io.FixedLenFeature([], tf.string),
        'label': tf.io.FixedLenFeature([], tf.int64),
    }
    example = tf.io.parse_single_example(serialized, feature_desc)
    image = tf.image.decode_jpeg(example['image'], channels=3)
    image = tf.image.resize(image, [224, 224])
    image = tf.cast(image, tf.float32) / 255.0
    return image, example['label']

def create_dataset(tfrecord_list, batch_size, epochs):
    ds = tf.data.TFRecordDataset(tfrecord_list,
                                 num_parallel_reads=tf.data.AUTOTUNE)
    ds = ds.map(parse_fn, num_parallel_calls=tf.data.AUTOTUNE)
    ds = ds.shuffle(2048).batch(batch_size).prefetch(tf.data.AUTOTUNE)
    return ds.repeat(epochs)
  1. Protocol Buffer 的作用总结 PB 是“数据模式 + 跨语言序列化”方案。tf.train.Example 就是一条预定义好的 PB 消息,字段编号 1 对应 Features。好处:
  • 前后向兼容:新增字段只需用新编号,老模型读新数据不会崩溃;
  • 强类型:写错类型会在 Python 层直接抛异常,避免训练阶段才发现错位;
  • 高性能:序列化后体积比 JSON 小 3~5 倍,解析速度高一个量级,且 C++ 内核可零拷贝直接读取。

拓展思考

  1. 多标签与变长数据:如果一张图对应不定长标签(如检测里的 N 个框),把框坐标、类别分别存成 FloatList/Int64List,长度维度用 tf.io.VarLenFeature 解析,再用 tf.sparse.to_dense 转成稠密张量即可。
  2. 分片与大数据:单机写 TFRecord 容易成为瓶颈,国内常用 Beam/DataFlow 或 Spark-TFRecord 并行写;文件名按 part-00000-of-01024 规范命名,tf.data.Dataset.list_files 自动支持 glob 读取。
  3. 加密与合规:PB 只是二进制,无法加密敏感字段;若训练数据含人脸,需要先在写阶段做 AES 加密,再在 parse_fn 里解密,注意把解密算子注册为 tf.py_function 会回退到 Python,性能下降 30% 以上,最好自定义 C++ 解密 op。
  4. TF 2.11+ 新 IO 方案:社区正在推 tf.data.experimental.service 与 SnapshotDataset,可把 TFRecord 直接缓存到分布式 SSD,训练重启秒级恢复,适合千卡场景;面试中提及可展示对最新生态的关注。