keras学习 0x07-Tfrecord 读取

3,609次阅读
没有评论

共计 1735 个字符,预计需要花费 5 分钟才能阅读完成。

很久没更新了,都已经忘记的差不多了,说实话是自己偷懒了,最近一段时间周末其实也是有时间来更新的。

上一篇文章写的还是怎么生成tfrecord,这次准备从tfrecord中读数据。

读写的方式可以使用 tf.data 或者使用 python io 方法来读取,不过建议还是使用 tf.data 来实现数据的读写。

import tensorflow as tf

def parse_example(example_proto):
    feature_key_value_pair = {
        'clothes_category': tf.FixedLenFeature([1],dtype=tf.int64),
        'clothes_prices': tf.FixedLenFeature([1],dtype=tf.float32),
        'clothes_name': tf.FixedLenFeature([], dtype=tf.string),
        'clothes_topic': tf.VarLenFeature(dtype=tf.float32)
    }
    return tf.parse_single_example(example_proto, feature_key_value_pair)
filenames = ['./resources/clothes.tfrecord']
raw_dataset = tf.data.TFRecordDataset(filenames)
dataset=raw_dataset.map(parse_example)
iter_data=dataset.make_one_shot_iterator()
next_example=iter_data.get_next()
with tf.Session() as sess:
    try:
        while True:
            data_record = sess.run(next_example)
            print(data_record)
    except:
        pass

上面给出了一段使用tf.data读取tfrecord的示例代码,生成tfrecord的方法是使用上一节使用的方法来tfrecord生成

由于是从tfrecord 中读取数据,所以是使用TFRecordDataset方法从文件中读取数据,由于数据是序列化存储在文件中,所以在也是需要相应方法去解析出来,所以定义了parse_example用来解析序列化数据,map依次对tfrecord中存储的每一记录使用parse_example方法去解析,make_one_shot_iterator 是构建迭代器,用于迭代样本。

make_one_shot_iterator 这个方法只遍历数据一遍,并非循环迭代。关于tf.data中迭代器的使用包含四种迭代器,这个在下一篇文章会介绍,这里暂时先不说了。

iter_data.get_next() 操作会在执行时生成 Dataset 的下一个元素,并且此操作通常充当输入管道代码和模型之间的接口。

后续就是构建session会话,不断的打印数据,打印的结果如下所示:

{'clothes_topic': SparseTensorValue(indices=array([[0],
       [1],
       [2]]), values=array([110., 120.,  78.], dtype=float32), dense_shape=array([3])), 'clothes_category': array([10]), 'clothes_name': b'jack jones', 'clothes_prices': array([100.6], dtype=float32)}
{'clothes_topic': SparseTensorValue(indices=array([[0],
       [1],
       [2],
       [3]]), values=array([ 89., 130.,  87., 522.], dtype=float32), dense_shape=array([4])), 'clothes_category': array([11]), 'clothes_name': b'cat', 'clothes_prices': array([101.6], dtype=float32)}

 

 

 

 

正文完
请博主喝杯咖啡吧!
post-qrcode
 
admin
版权声明:本站原创文章,由 admin 2019-09-09发表,共计1735字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码