TFRecord是TensorFlow中用于数据序列化的标准格式,广泛应用于机器学习数据处理场景。以下是关键知识点:

📘 什么是TFRecord?

TFRecord是一种二进制文件格式,用于存储结构化数据。其优势包括:

  • 高效序列化/反序列化
  • 支持大规模数据集
  • 与TensorFlow无缝集成
TFRecord_格式

🛠 使用场景

  1. 图像识别数据集(如MNIST/CIFAR)
  2. 文本处理任务
  3. 时间序列分析
  4. 模型训练数据准备
  5. 数据集分发与共享

📁 创建TFRecord文件

import tensorflow as tf

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]))

example = tf.train.Example(features=tf.train.Features(feature={
    'image/height': _int64_feature(256),
    'image/width': _int64_feature(256),
    'image/encoded': _bytes_feature(b'jpeg_data'),
    'image/format': _bytes_feature(b'jpeg'),
}))

with tf.io.TFRecordWriter('output.tfrecord') as writer:
    writer.write(example.SerializeToString())
数据序列化

📈 读取TFRecord文件

def parse_single_example(example):
    feature_description = {
        'image/height': tf.io.FixedLenFeature([], tf.int64),
        'image/width': tf.io.FixedLenFeature([], tf.int64),
        'image/encoded': tf.io.FixedLenFeature([], tf.string),
        'image/format': tf.io.FixedLenFeature([], tf.string),
    }
    return tf.io.parse_single_example(example, feature_description)

dataset = tf.data.TFRecordDataset('output.tfrecord')
dataset = dataset.map(parse_single_example)
数据流处理

📚 扩展阅读

想深入了解数据预处理?可参考:
数据预处理教程

GitHub示例代码
TFRecord官方文档