TFRecord 读写示例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/G66565906/article/details/84230630

格式

为统一数据的存储, Tensorflow提供了一种通用数据格式

message Example {
   Features features = 1;
};

message Features {
  map<string, Feature> feature = 1;
};

message Feature {
  oneof kind {
  BytesList  bytes_list =1;
  FloatList float_list = 2;
  Int64List int64_list = 3;
 }
};

以该格式存储数据的文件被称为TFRecode文件,通常一个TFRecode文件会包含成百上千条Example记录。

import tensorflow as tf

 
TFWriter = tf.python_io.TFRecordWriter("e:/test.tf")
 
example = tf.train.Example(features=tf.train.Features(feature={'test': tf.train.Feature(int64_list=tf.train.Int64List(value= [222,44,22] )),
                                                               'string': tf.train.Feature(bytes_list=tf.train.BytesList(value=  [  bytes("test", "gbk"), bytes("test2", "gbk") ] )) 
                                                               }))


TFWriter.write(example.SerializeToString())
example = tf.train.Example(features=tf.train.Features(feature={'test': tf.train.Feature(int64_list= tf.train.Int64List(value=  [222,44,33] )),
                                                               'string': tf.train.Feature(
                                                                   bytes_list=tf.train.BytesList(value= [   bytes("test", "gbk"),  bytes("test3", "gbk") ] ))
                                                               }))
TFWriter.write(example.SerializeToString())
TFWriter.close();

生成TFRecode文件相对比较普通,主要有两个三个步骤:

一:定义TFWriter

二:构造tr.train.Example对象并写入TFWriter

三:关闭文件

import tensorflow as tf
import numpy as np
 
files = tf.train.string_input_producer(["e:/test.tf"]);


TFReader = tf.TFRecordReader()

_, data = TFReader.read(files)

featurs = tf.parse_single_example(data, features={"test": tf.FixedLenFeature([3],  tf.int64),
                                                  "string":tf.FixedLenFeature([2], tf.string)
                                                  })

with tf.Session() as sess:
    tf.global_variables_initializer()
    tf.train.start_queue_runners()

    tempdata = (sess.run((featurs["test"])))

    print(tempdata)

    tempdata = (sess.run((featurs["string"] )))

    print(tempdata)
    print(tempdata[0].decode("gbk"))




读取TFRecode文件相对麻烦一些,这里使用了文件队列,需要注意的时需要开启一个Session,并调用tf.global_variables_initializer(),

tf.train.start_queue_runners(), 因为tf.train.string_input_producer()创建了队列线程,需要start_queue_runners()启动线程。

猜你喜欢

转载自blog.csdn.net/G66565906/article/details/84230630
今日推荐