首页 > 解决方案 > 如何直接从 tf.data.Dataset.from_generator 方法生成编码文本?

问题描述

使用tf.data API 获得更好的性能Tensorflow 教程展示了一个简单而高效的Dataset实现。使用文本数据集时,此实现将类似于:

class TextDataset(tf.data.Dataset):

    def _generator(dataset_dir, num_samples):
        # Opening the dataset file
        dataset_file = open(dataset_dir, "r")

        for sample_idx in range(num_samples):
            # Reading data (line, record) from the file
            sample = dataset_file.readline()

            yield {"idx": sample_idx, "text": sample}

    def __new__(cls, dataset_dir, num_samples=3):
        return tf.data.Dataset.from_generator(
            cls._generator,
            output_types={"idx": tf.dtypes.int64, "text": tf.dtypes.string},
            output_shapes={"idx": (), "text": ()},
            args=(dataset_dir, num_samples,)
        )

生成以下数据集:

{'idx': <tf.Tensor: shape=(), dtype=int64, numpy=0>,  
 'text': <tf.Tensor: shape=(), dtype=string, numpy=b'sample one'>},

{'idx': <tf.Tensor: shape=(), dtype=int64, numpy=1>, 
 'text': <tf.Tensor: shape=(), dtype=string, numpy=b'sample two'>},

{'idx': <tf.Tensor: shape=(), dtype=int64, numpy=2>, 
 'text': <tf.Tensor: shape=(), dtype=string, numpy=b'sample three'>}

...

现在,与其在方法中将 yieldtext作为字符串,不如_generator只返回字符串标记的标识符(编码)。这可以通过tokenizer.

那么,如何text在方法中生成它之前将其编码为整数列表_generator

注意: Google Colab中提供了一个工作示例。

标签: tensorflowtensorflow2.0tensorflow-datasets

解决方案


推荐阅读