介绍
读取 TFRecord文件 分两步实现:
- 读取文件
- 解析数据
参见官方文档:
https://www.tensorflow.org/tutorials/load_data/tfrecord#reading_a_tfrecord_file
读取文件
使用tf.data.TFRecordDataset读取文件
tf.data.TFRecordDataset用于读取 TFRecord 文件,使用方式与tf.data.Dataset几乎相同
例子1:读取一个文件
dataset=tf.data.TFRecordDataset("/Users/mym/Desktop/python/1.tfrecord")
for data in dataset:
print(data)
print("-"*50)
执行结果:
也就是生成TFRecord文件时,序列化的数据,所以此时的数据还不能直接使用,需要解析
例子2:读取多个个文件
filenames=["/Users/mym/Desktop/python/1.tfrecord","/Users/mym/Desktop/python/2.tfrecord"]
dataset=tf.data.TFRecordDataset(filenames)
解析数据
定义数据结构:
feature = {
"name":tf.io.FixedLenFeature([], tf.string, default_value=""),
"age":tf.io.FixedLenFeature([], tf.int64, default_value=0),
"height":tf.io.FixedLenFeature([], tf.float32, default_value=0.0),
"parents":tf.io.FixedLenFeature([2], tf.string, default_value=["",""]),
"likes":tf.io.VarLenFeature(tf.string)
}
解释:
- 数据结构也是类似JSON,
key:value结构
- name、age、height 对应 value 数量是固定的,所以用
tf.io.FixedLenFeature(),- 第一个参数可以写
[]或者[1],表示有1个值; - 第二个参数是类型;
- 第三个参数是默认值
- 第一个参数可以写
- parents 对应 value 数量是固定的,所以用
tf.io.FixedLenFeature(),- 第一个参数是
[2],表示有2个值; - 第二个参数是类型;
- 第三个参数是默认值,是
["",""],表示这2个值的默认值
- 第一个参数是
- likes 对应 value 数量不固定,所以用
tf.io.VarLenFeature(),只有一个参数:数据类型
然后使用tf.io.parse_single_example解析数据
例子
接上面2个例子
def _parse(data):
feature = {
"name":tf.io.FixedLenFeature([], tf.string, default_value=""),
"age":tf.io.FixedLenFeature([], tf.int64, default_value=0),
"height":tf.io.FixedLenFeature([], tf.float32, default_value=0.0),
"parents":tf.io.FixedLenFeature([2], tf.string, default_value=["",""]),
"likes":tf.io.VarLenFeature(tf.string)
}
res=tf.io.parse_single_example(data,feature)
return res
dataset2=dataset.map(_parse,num_parallel_calls=tf.data.experimental.AUTOTUNE)
for data in dataset2:
print(data)
print("-"*50)
执行结果:
将序列化的数据成功解析成 dict 类型
tf.data.TFRecordDataset
用于读取 TFRecord 文件,使用方式与tf.data.Dataset几乎相同
tf.io.FixedLenFeature
解析定长 Feature,返回Tensor
官方api:
https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/io/FixedLenFeature
函数
@staticmethod
__new__(
cls,
shape,
dtype,
default_value=None
)
参数:
- shape:输入数据的shape。
- dtype:输入的数据类型。
- default_value:默认值。必须与dtype、shape匹配。
否则报错Tensorflow:Can't parse serialized Example.
属性
- shape
- dtype
- default_value
tf.io.VarLenFeature
解析 不定长的Feature,返回 SparseTensor,用于处理可变长度的输入
官方api:
https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/io/VarLenFeature
属性
dtype:数据类型
tf.io.parse_single_example
解析单个 Example
官方api:
https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/io/parse_single_example
语法
tf.io.parse_single_example(
serialized,
features,
example_names=None,
name=None
)
参数:
- serialized:传入序列化的字符串
- features:定义数据结构
返回值:
- 返回 dict 类型,
key:value结构,value是 Tensor 或 SparseTensor
感谢:
https://www.jianshu.com/p/b480e5fcb638

