首页 > 解决方案 > Tensorflow:计算 TFRecord 文件中的示例数——不使用已弃用的 `tf.python_io.tf_record_iterator`

问题描述

请在标记重复之前阅读帖子

我正在寻找一种有效的方法来计算 TFRecord 图像文件中的示例数量。由于 TFRecord 文件不保存有关文件本身的任何元数据,因此用户必须遍历文件才能计算此信息。

StackOverflow 上有几个不同的问题可以回答这个问题。问题是他们似乎都使用了 DEPRECATEDtf.python_io.tf_record_iterator命令,所以这不是一个稳定的解决方案。以下是现有帖子的示例:

从 Tensorflow 中的 .tfrecords 文件中获取记录总数

每个 tfrecord 中的示例数

每个 tfrecord 中的示例数

所以我想知道是否有一种方法可以使用新的 Dataset API 来计算记录数。

标签: tensorflowtfrecord

解决方案


该类下列出了一个reduce方法Dataset。他们给出了一个使用该方法计数记录的示例:

# generate the dataset (batch size and repeat must be 1, maybe avoid dataset manipulation like map and shard)
ds = tf.data.Dataset.range(5) 
# count the examples by reduce
cnt = ds.reduce(np.int64(0), lambda x, _: x + 1)

## produces 5

不知道这种方法是否比@krishnab 的 for 循环更快。


推荐阅读