TFRecord提供了一种统一的格式来存储数据。普通的数据处理方法使用了一个从类别名到所有数据列表的词典来维护图像和类别的关系。这种方式的课扩展性很差,当数据来源更加复杂、每一个样例中的信息更加丰富之后,这种方式就很难有效的记录数据中的信息了。于是TensorFlow提供了TFRecord的格式来统一存储数据。
TFRecord格式介绍
TFRecord文件中的数据都是通过tf.train.Example Protocol Buffer的格式存储的。以下代码给出了tf.train.Example的定义
message Example {
Features features = 1;
}
message Feature {
map<string, Feature> feature = 1;
}
message Feature {
oneof kind {
BytesList bytes_list = 1;
BytesList float_list = 2;
BytesList int64_list = 3;
}
};
上述代码可以看出tf.train.Example的数据结构比较简洁。tf.train.Example中包含了一个从属性名称到取值的字典。其中属性名称为一个字符串,属性的取值可以为字符串(BytesList)、实数列表(FloatList)或者整数列表(Int64List)。比如讲一张解码前的图像存为一个字符串,图像所对应的类别编号存为整数列表。
样例程序
将MNIST输入数据转化为TFRecord格式
import tensorflow as tf
from tensorflow.example.tutorials.mnist import input_data
import numpy
#生成整数型的属性
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.unit8, 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)}))
#将一个Example写入TFRecord文件
writer.write(example.SerializeToString())
writer.close()
以上程序可以将MNIST数据集中所有的训练数据存储到一个TFRecord文件中。当数据量较大时,也可以将数据写入多个TFRecord文件。TensorFlow对从文件列表中读取数据提供很好的支持,以下给出了如何读取TFRecord文件中的数据
import tensorflow as tf
#创建一个reader来读取TFRecord文件中的样例
reader = tf.TFRecordReader()
#创建一个队列来维护输入文件列表,
#tf.train.string_input_producer函数
filename_queue = tf.train.string_inpt_producer(["/path/to/output.tfrecords"])
#从文件中读取一个样例,也可以使用read_up_to函数一次性读取多个样例
_, serialized_example = reader.read(filename_quque)
#解析读入的一个样例,如果需要解析多个样例,可以使用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可以将字符串解析成图像对应的像素数组。
image = tf.decorde_raw(features['image_raw'], tf.unit8)
label = 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):
print(sess.run([image, label, pixels]))