tfrecord 存储数据的优势
-
读取和解析速度比较快,易用性较好。tfrecord的读取和解析都比较方便,结构化设计对于数据的存储非常友好。字典的设计形式非常契合特征存储需求,在解析之后只需要将相应的特征输入模型就可以进行模型训练和推理了。
-
可以对数据进行压缩,存储空间利用率高。tfreocd采用了类似与protobuf的方式,是一种二进制的存储格式,在存储性能和读取性能上都进行了一定的优化。
-
方便后续tensorflow数据流调用。tensorflow提供了tf.data高性能数据流处理样本读取流程。特征读取和预处理主要占用CPU,模型训练主要占用GPU,高性能的训练数据流可以将数据读取和模型训练流程高度并行化,加强GPU利用率。
tfrecord 数据的存储
我们常用的特征数据大部分是矩阵信息。在使用tfrecord存储数据的时候需要对特征数据进行转换,将矩阵信息转换为tfrecord允许的特征存储格式。
def bytes_feature(value):
"""
Return a bytes_list as a string / byte
"""
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def float_feature(value):
"""
Returns a float_list from a float / double.
"""
return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))
def int64_feature(value):
"""
Returns an int64_list from a bool / enum / int / uint.
"""
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
tf.train.Feature
函数主要用于转换一个需要保存的特征,其中有三个关键字可以选择tf.train.BytesList
,tf.train.FloatList
,tf.train.Int64List
,这三个关键字分别对应了二进制,浮点数,整数三种不同的特征存储方式。所有的特征都能够转为二进制特征进行存储,二进制是最常用的特征存储方式。
get_samples
函数是将np.array
矩阵和图像转换为tfrecord存储方式的一个示例。图像特征先用tf.image.encode_png
进行了编码压缩,大幅减少了图像矩阵占用的存储空间。position
是一个多维的np.array
,被转换为适合tfrecord存储的二进制数据。
def get_samples(image_path):
"""
get feature and label
"""
position = np.random.randint(0, 400, (20, 2))
# get image
np_image = cv2.imread("data/tensorflow.png")
tf_input = tf.placeholder(tf.uint8, [np_image.shape[0], np_image.shape[1], np_image.shape[2]])
# encode image
tf_image_raw = tf.image.encode_png(tf_input)
with tf.Session() as sess:
image_raw = sess.run(tf_image_raw, feed_dict={tf_input: np_image})
tf_sample = dict()
# feature to bytes
tf_sample['position'] = bytes_feature(position.tobytes())
tf_sample['image'] = bytes_feature(image_raw)
return tf_sample
get_samples
函数返回的是一个编码的字典,将这个字典的内容写入tfrecord就可以完成数据的存储了。写入的方法如下:
def dump_tfrecord_file(samples, tfrecord_path):
"""
dump samples
"""
if not samples:
print "no samples"
return None
tf_writer = tf.python_io.TFRecordWriter(tfrecord_path)
sample_proto = tf.train.Example(features=tf.train.Features(feature=samples))
tf_writer.write(sample_proto.SerializeToString())
其中samples
是编码好的字典,tfrecord_path
是希望写入的tfrecord路径。
tfrecord 数据的解析
我们这里使用tf.data来解析tfreocrd文件。tf.data是一个高性能的输入数据流处理工具,提供了简单高效的接口读取和解析tfrecord。
def parser(record):
"""
parser samples from tfrecord
"""
sample = {
"position": tf.FixedLenFeature((), tf.string),
"image": tf.FixedLenFeature((), tf.string)
}
parsed_sample = tf.parse_single_example(record, sample)
position = tf.decode_raw(parsed_sample['position'], tf.int64)
position = tf.reshape(position, [20, 2])
image = tf.image.decode_png(parsed_sample['image'], channels=3)
return [position, image]
def parse_tfrecord(record_dir):
"""
read tfrecord use tf data piple line
"""
tfrecord_list = glob.glob(record_dir + '/*.tfrecord')
print tfrecord_list
tf_data = tf.data.TFRecordDataset(tfrecord_list)
tf_data = tf_data.map(parser)
tf_data = tf_data.batch(1)
iterator = tf_data.make_one_shot_iterator()
tf_result = iterator.get_next()
with tf.Session() as sess:
result = sess.run(tf_result)
print result[0].shape
print result[1].shape
parser
函数定义了tfrecord数据的解析方式。tf.decode_raw
将二进制文件还原为对应的矩阵。需要注意的是一般解析得到矩阵之后都需要tf.reshape
操作将矩阵的shape进行还原。 parse_tfrecord
函数定义了一个基于tf.data的数据流,从文件夹中读取文件,进行并行化处理,然后由one_shot_iterator
迭代器输出.