TextVectorization 类tf_keras.layers.TextVectorization(
max_tokens=None,
standardize="lower_and_strip_punctuation",
split="whitespace",
ngrams=None,
output_mode="int",
output_sequence_length=None,
pad_to_max_tokens=False,
vocabulary=None,
idf_weights=None,
sparse=False,
ragged=False,
encoding="utf-8",
**kwargs
)
一个将文本特征映射为整数序列的预处理层。
这个层提供了在 TF-Keras 模型中处理文本的基本选项。它将一批字符串(一个样本 = 一个字符串)转换为词元索引列表(一个样本 = 整数词元索引的 1D 张量)或密集表示(一个样本 = 表示样本词元数据的浮点值 1D 张量)。这个层旨在处理自然语言输入。要处理简单的字符串输入(分类字符串或预分词字符串),请参阅 tf.keras.layers.StringLookup。
层的词汇表必须在构建时提供或通过 adapt() 学习。当这个层被 adapt 时,它将分析数据集,确定单个字符串值的频率,并从中创建一个词汇表。这个词汇表的大小可以无限或有上限,取决于该层的配置选项;如果输入中的唯一值数量超过最大词汇表大小,则将使用最频繁的词语来创建词汇表。
每个样本的处理包括以下步骤
关于传递可调用对象以自定义此层的分割和标准化的注意事项
tf.keras.saving.register_keras_serializable)。standardize 时,可调用对象接收到的数据将与传递给此层的数据完全相同。可调用对象应返回与输入具有相同形状的张量。split 时,可调用对象接收到的数据将挤压掉第一个维度 - 例如,可调用对象接收到的不是 [["string to split"], ["another string to split"]],而是 ["string to split", "another string to split"]。可调用对象应返回一个张量,其第一个维度包含分割后的词元 - 在此示例中,我们应看到类似 [["string", "to", "split"], ["another", "string", "to", "split"]] 的内容。这使得可调用对象能够与 tf.strings.split() 原生兼容。有关预处理层的概述和完整列表,请参阅预处理指南。
参数
pad_to_max_tokens=True 时指定。请注意,此词汇表包含 1 个 OOV 词元,因此有效词元数量为 (max_tokens - 1 - (1 if output_mode == "int" else 0))。None:不进行标准化。"lower_and_strip_punctuation":文本将被转换为小写并移除所有标点符号。"lower":文本将被转换为小写。"strip_punctuation":移除所有标点符号。None:不进行分割。"whitespace":按空格分割。"character":按每个 Unicode 字符分割。"int", "multi_hot", "count" 或 "tf_idf",配置如下"int":输出整数索引,每个分割后的字符串词元对应一个整数索引。当 output_mode == "int" 时,0 保留用于被屏蔽的位置;这将词汇表大小减少到 max_tokens - 2 而不是 max_tokens - 1。"multi_hot":每批输出一个整数数组,大小为 vocab_size 或 max_tokens,在批次项中至少存在一次的词元对应的索引处包含 1。"count":类似于 "multi_hot",但整数数组包含该索引处词元在批次项中出现的次数计数。"tf_idf":类似于 "multi_hot",但应用 TF-IDF 算法来计算每个词元槽的值。对于 "int" 输出模式,支持任何形状的输入和输出。对于所有其他输出模式,目前仅支持 rank 1 输入(以及分割后的 rank 2 输出)。output_sequence_length 个值,无论分割步骤产生了多少词元,结果张量形状都将是 (batch_size, output_sequence_length)。默认为 None。"multi_hot", "count" 和 "tf_idf" 模式下有效。如果为 True,即使词汇表中的唯一词元数量小于 max_tokens,输出的特征轴也将被填充到 max_tokens,无论词汇表大小如何,结果张量形状都将是 (batch_size, max_tokens)。默认为 False。adapt() 该层。output_mode 为 "tf_idf" 时有效。与词汇表长度相同的元组、列表、一维 numpy 数组或一维张量,包含浮点逆文档频率权重,该权重将乘以每个样本的词语计数以得到最终的 tf_idf 权重。如果设置了 vocabulary 参数,并且 output_mode 为 "tf_idf",则必须提供此参数。"int" 输出模式。如果为 True,则返回 RaggedTensor 而不是密集 Tensor,其中每个序列在字符串分割后可能具有不同的长度。默认为 False。"multi_hot", "count" 和 "tf_idf" 输出模式。如果为 True,则返回 SparseTensor 而不是密集 Tensor。默认为 False。"utf-8"。示例
此示例实例化了一个 TextVectorization 层,该层将文本转换为小写,按空格分割,去除标点符号,并输出整数词汇索引。
>>> text_dataset = tf.data.Dataset.from_tensor_slices(["foo", "bar", "baz"])
>>> max_features = 5000 # Maximum vocab size.
>>> max_len = 4 # Sequence length to pad the outputs to.
>>>
>>> # Create the layer.
>>> vectorize_layer = tf.keras.layers.TextVectorization(
... max_tokens=max_features,
... output_mode='int',
... output_sequence_length=max_len)
>>>
>>> # Now that the vocab layer has been created, call `adapt` on the
>>> # text-only dataset to create the vocabulary. You don't have to batch,
>>> # but for large datasets this means we're not keeping spare copies of
>>> # the dataset.
>>> vectorize_layer.adapt(text_dataset.batch(64))
>>>
>>> # Create the model that uses the vectorize text layer
>>> model = tf.keras.models.Sequential()
>>>
>>> # Start by creating an explicit input layer. It needs to have a shape of
>>> # (1,) (because we need to guarantee that there is exactly one string
>>> # input per batch), and the dtype needs to be 'string'.
>>> model.add(tf.keras.Input(shape=(1,), dtype=tf.string))
>>>
>>> # The first layer in our model is the vectorization layer. After this
>>> # layer, we have a tensor of shape (batch_size, max_len) containing
>>> # vocab indices.
>>> model.add(vectorize_layer)
>>>
>>> # Now, the model can map strings to integers, and you can add an
>>> # embedding layer to map these integers to learned embeddings.
>>> input_data = [["foo qux bar"], ["qux baz"]]
>>> model.predict(input_data)
array([[2, 1, 4, 0],
[1, 3, 0, 0]])
示例
此示例通过将词汇项列表传递给层的 __init__() 方法来实例化一个 TextVectorization 层。
>>> vocab_data = ["earth", "wind", "and", "fire"]
>>> max_len = 4 # Sequence length to pad the outputs to.
>>>
>>> # Create the layer, passing the vocab directly. You can also pass the
>>> # vocabulary arg a path to a file containing one vocabulary word per
>>> # line.
>>> vectorize_layer = tf.keras.layers.TextVectorization(
... max_tokens=max_features,
... output_mode='int',
... output_sequence_length=max_len,
... vocabulary=vocab_data)
>>>
>>> # Because we've passed the vocabulary directly, we don't need to adapt
>>> # the layer - the vocabulary is already set. The vocabulary contains the
>>> # padding token ('') and OOV token ('[UNK]') as well as the passed
>>> # tokens.
>>> vectorize_layer.get_vocabulary()
['', '[UNK]', 'earth', 'wind', 'and', 'fire']