Tensorflow-从单个大型txt文件读取数据的正确方法

Tensorflow-从单个大型txt文件读取数据的正确方法,tensorflow,Tensorflow,我想问一下,使用tensorflow批量读取大型文本数据的正确模式是什么 这里是一行文本数据。在单个txt文件中有数十亿行这样的数据 目标上下文标签 现在,我正试图按照官方文档中的建议使用tfrecords 这是我的路 filename_queue = tf.train.string_input_producer([self._train_data], num_epochs=self._num_epochs) reader = tf.TFRecordReader()

我想问一下,使用tensorflow批量读取大型文本数据的正确模式是什么

这里是一行文本数据。在单个txt文件中有数十亿行这样的数据

目标上下文标签

现在,我正试图按照官方文档中的建议使用tfrecords

这是我的路

    filename_queue = tf.train.string_input_producer([self._train_data], num_epochs=self._num_epochs)

    reader = tf.TFRecordReader()

    _, serialized_example = reader.read(filename_queue)

    features = tf.parse_single_example(
        serialized_example,
        # Defaults are not specified since both keys are required.
        features={
            'target': tf.FixedLenFeature([], tf.int64),
            'context': tf.FixedLenFeature([], tf.int64),
            'label': tf.FixedLenFeature([], tf.int64),
        })

    target = features['target']
    context = features['context']
    label = features['label']
    min_after_dequeue = 10000
    capacity = min_after_dequeue + 3 * self._batch_size
    target_batch, context_batch, label_batch = tf.train.shuffle_batch(
        [target, context, label], batch_size=self._batch_size, capacity=capacity,
        min_after_dequeue=min_after_dequeue, num_threads=self._concurrent_steps)
在那之后,我使用时间轴来进行分析。结果表明,该部分占用了大部分时间。 这是分析图。

顺便说一句,我使用批量大小500。
有什么建议吗?

应用于一批元素通常比应用于每个单独的元素更有效,因为前一个op有一个高效的多线程实现,可以在输入包含多个示例时使用。以下代码重写应该可以提高性能:

filename_queue = tf.train.string_input_producer([self._train_data], num_epochs=self._num_epochs)

reader = tf.TFRecordReader()

# Read a batch of up to 128 examples at once.
_, serialized_examples = reader.read_up_to(filename_queue, 128)

features = tf.parse_example(
    serialized_examples,
    # Defaults are not specified since both keys are required.
    features={
        'target': tf.FixedLenFeature([], tf.int64),
        'context': tf.FixedLenFeature([], tf.int64),
        'label': tf.FixedLenFeature([], tf.int64),
    })

target = features['target']
context = features['context']
label = features['label']
min_after_dequeue = 10000
capacity = min_after_dequeue + 3 * self._batch_size

# Pass `enqueue_many=True` because the input is now a batch of parsed examples.
target_batch, context_batch, label_batch = tf.train.shuffle_batch(
    [target, context, label], batch_size=self._batch_size, capacity=capacity,
    min_after_dequeue=min_after_dequeue, num_threads=self._concurrent_steps,
    enqueue_many=True)

你的CPU满了吗?如果没有,则可能需要使用更多线程(在
tf.train.shuffle\u batch()
num\u threads
参数中)来解析文件中的记录。其他可能性:您可以使用
reader.read\u to(n)
tf.parse\u example()
而不是
tf.parse\u single\u example()
,并将
enqueue\u many=True
传递给
tf.train.shuffle\u batch()
,以便执行批处理,这应该更有效。@mrry就是我使用的
reader.read\u up\u to(n)
tf.parse_example()
一次读取多行数据并解决问题。