TensorFlow 深度学习框架(10) -- TFRecord 文件存储

TensorFlow 提供了 TFRecord 来统一输入数据的格式。tf.train.Example 中包含了一个从属性名称到取值的字典。其中属性名称为一个字符串,属性的值可以为 字符串(BytesList),实数列表(FloatList)或者整数列表(Int64List)。比如将一张解码前的图像存为一个字符串,图像所对应的类别编号存为整数列表。

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np

# 生成整数型的属性
def _int64_feature(value):
    return tf.train.Feature(int64_list = tf.train.Int64List(value = [value]))

# 生成字符串型的属性
def _bytes_feature(value):
    return tf.train.Feature(bytes_list = tf.train.BytesList(value = [value]))

mnist = input_data.read_data_sets(
    "/path/to/mnist/data",dtype = tf.uint8, one_hot = True)
images = mnist.train.images

# 训练数据所对应的正确答案,可以作为一个属性保存在 TFRecord 中
labels = mnist.train.labels
# 训练数据的分辨率,这可以作为 Example 中的一个属性
pixels = images.shape[1]
num_examples = mnist.train.num_examples

# 输出 TFRecord 文件的地址
filename = "/path/to/output.tfrecords"
# 创建一个 writer 来写 TFRecord 文件
writer = tf.python_io.TFRecordWriter(filename)
for index in range(num_examples):
    # 将图像矩阵转换成一个字符串
    image_raw = images[index].tostring()
    # 将一个样例转化为 Example Protocol Buffer 并将所有的信息写入这个数据结构
    example = tf.train.Example(features = tf.train.Features(feature = {
        'pixels':_int64_feature(pixels),
        'label':_int64_feature(np.argmax(labels[index])),
        'image_raw':_bytes_feature(image_raw)}))
    writer.write(example.SerializeToString())
writer.close()

以上程序将训练数据存储到一个 TFRecord 文件中。当数据量比较大时,也可以写入多个 TFRecord 文件。TensorFlow 对从文件列表中读取数据提供了很好的支持。

import tensorflow as tf
# 创建一个 reader 来读取 TFRecord 中的样例
reader = tf.TFRecordReader()
# 创建一个队列来维护输入文件列表
filename_queue = tf.train.string_input_producer(
    ["/path/to/output.tfrecords"])

# 从文件中读出一个样例。也可以使用 read_up_to 函数一次性读取多个样例
# 读取多个样例 read_up_to(filename_queue, num_records = n)
_, serialized_example = reader.read(filename_queue)
# 解析读入的一个样例。如果需要解析多个样例,可以用 parse_example 函数
features = tf.parse_single_example(
        serialized_example,
        features = {
            # TensorFlow 提供两种不同的属性解析方法。一种方法是 tf.FixedLenFeature,
            # 这种方法解析的结果为一个 tensor。另一种方法是 tf.VarLenFeature,这种方法
            # 得到的解析结果为 SparseTensor,用于处理稀疏数据
            # 这里解析数据的格式需要和上面程序写入数据的格式一致
            'image_raw':tf.FixedLenFeature([],tf.string),
            'pixels':tf.FixedLenFeature([],tf.int64),
            'label':tf.FixedLenFeature([],tf.int64),
        })

# tf.decode_raw 可以将字符串解析成图像对应的像素数组
images = tf.decode_raw(features['image_raw'],tf.uint8)
labels = tf.cast(features['label'],tf.int32)
pixels = tf.cast(features['pixels'],tf.int32)

sess = tf.Session()
# 启动多线程处理输入数据
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess = sess,coord = coord)

# 每次运行可以读取 TFRecord 文件中的一个样例,当所有样例读完后,会重头读取
for i in range(10):
    image, label, pixel = sess.run([images, labels, pixels])

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值