从 TensorFlow 图表中的 TFRecords 文件中读取顺序数据?

Reading sequential data from TFRecords files within the TensorFlow graph?

我正在处理视频数据,但我相信这个问题应该适用于任何顺序数据。我想从 TFRecords 文件传递​​我的 RNN 10 连续示例(视频帧)。当我第一次开始阅读文件时,我需要抓取 10 个示例,并使用它来创建一个序列示例,然后将其推送到队列中供 RNN 在准备就绪时使用。然而,现在我有了 10 帧,下次我从 TFRecords 文件读取时,我只需要取 1 个示例并将其他 9 个移过来。但是当我到达第一个 TFRecords 文件的末尾时,我需要在第二个 TFRecords 文件上重新启动进程。据我了解,cond op 将处理每个条件下所需的 ops,即使该条件不是要使用的条件。当使用条件检查是读取 10 个示例还是仅读取 1 个示例时,这将是一个问题。是否有办法解决此问题以仍然获得上述所需的结果?

您可以使用 TensorFlow 1.12 中最近添加的 Dataset.window() 转换来执行此操作:

filenames = tf.data.Dataset.list_files(...)

# Define a function that will be applied to each filename, and return the sequences in that
# file.
def get_examples_from_file(filename):
  # Read and parse the examples from the file using the appropriate logic.
  examples = tf.data.TFRecordDataset(filename).map(...)

  # Selects a sliding window of 10 examples, shifting along 1 example at a time.
  sequences = examples.window(size=10, shift=1, drop_remainder=True)

  # Each element of `sequences` is a nested dataset containing 10 consecutive examples.
  # Use `Dataset.batch()` and get the resulting tensor to convert it to a tensor value
  # (or values, if there are multiple features in an example).
  return sequences.map(
      lambda d: tf.data.experimental.get_single_element(d.batch(10)))

# Alternatively, you can use `filenames.interleave()` to mix together sequences from
# different files.
sequences = filenames.flat_map(get_examples_from_file)