tensorflow - 如何直接从 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中提供了一个工作示例。
解决方案
推荐阅读
- ag-grid-angular - 使用 Ivy 的 Angular 8 中的 AG Grid 模块导入错误
- scala - Spark Streaming 延迟写入 Kafka - x 分钟后
- azure - 应用服务的响应时间指标到底是什么
- f# - 在不需要函数的上下文中使用 F# 扩展
- ruby - 如何合并数组内的哈希?
- javascript - Vue.js 在更改键后没有响应鼠标事件
- apache-camel - 如何使用 Apache Camel Routes 执行 Arquillian 测试
- swift - 表视图委托内的集合视图
- javascript - Javascript - 使用箭头函数重写 for 循环?
- database - DolphinDB 在重新分配未定义的变量时抛出异常