Keras 2 API 文件 / 層 API / 預處理層 / 文字預處理 / TextVectorization 層

TextVectorization 層

[原始碼]

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() 學習。當調整此層時,它將分析資料集、判斷個別字串值的頻率,並從中建立詞彙表。此詞彙表可以有無限的大小或受限,取決於此層的配置選項;如果輸入中的唯一值多於最大詞彙表大小,則將使用最常見的詞語來建立詞彙表。

每個範例的處理包含以下步驟

  1. 標準化每個範例(通常為小寫 + 移除標點符號)
  2. 將每個範例分割成子字串(通常為單字)
  3. 將子字串重新組合為詞符(通常為 n 元詞)
  4. 索引詞符(將唯一的整數值與每個詞符關聯)
  5. 使用此索引轉換每個範例,轉換為整數向量或密集浮點數向量。

關於傳遞可呼叫物件來自訂此層的分割和正規化的注意事項

  1. 任何可呼叫物件都可以傳遞到此層,但如果您要序列化此物件,則只應傳遞已註冊的 Keras 可序列化函數(如需更多詳細資訊,請參閱 tf.keras.saving.register_keras_serializable)。
  2. 當對 standardize 使用自訂可呼叫物件時,可呼叫物件接收的資料將與傳遞至此層的資料完全相同。可呼叫物件應傳回與輸入形狀相同的張量。
  3. 當對 split 使用自訂可呼叫物件時,可呼叫物件接收的資料將會擠出第 1 維度 - 可呼叫物件將看到 ["要分割的字串", "另一個要分割的字串"],而不是 [["要分割的字串"], ["另一個要分割的字串"]]。可呼叫物件應傳回一個張量,其第一維度包含分割的詞符 - 在此範例中,我們應該看到類似 [["字串", "要", "分割"], ["另一個", "字串", "要", "分割"]] 的內容。這使得可呼叫物件站點與 tf.strings.split() 自然相容。

有關預處理層的概述和完整清單,請參閱預處理指南

引數

  • max_tokens:此層的詞彙表最大大小。僅應在調整詞彙表或設定 pad_to_max_tokens=True 時指定。請注意,此詞彙表包含 1 個 OOV 詞符,因此有效詞符數為 (max_tokens - 1 - (如果 output_mode == "int" 則為 1,否則為 0))
  • standardize:用於應用於輸入文字的標準化的可選規格。值可以是
    • None:無標準化。
    • "lower_and_strip_punctuation":文字將小寫,並移除所有標點符號。
    • "lower":文字將小寫。
    • "strip_punctuation":將移除所有標點符號。
    • 可呼叫物件:輸入將傳遞給可呼叫函數,該函數應標準化並傳回。
  • split:用於分割輸入文字的可選規格。值可以是
    • None:無分割。
    • "whitespace":以空白分割。
    • "character":以每個 Unicode 字元分割。
    • 可呼叫物件:標準化輸入將傳遞給可呼叫函數,該函數應分割並傳回。
  • ngrams:用於從可能分割的輸入文字建立 n 元詞的可選規格。值可以是 None、整數或整數元組;傳遞整數將建立到該整數的 n 元詞,而傳遞整數元組將為元組中指定的值建立 n 元詞。傳遞 None 表示不會建立 n 元詞。
  • output_mode:用於設定層輸出的可選規格。值可以是 "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:僅在 INT 模式下有效。如果設定,則輸出的時間維度將會填充或截斷為恰好 output_sequence_length 個值,從而產生形狀為 (batch_size, output_sequence_length) 的張量,無論分割步驟產生多少詞符。預設為 None
  • pad_to_max_tokens:僅在 "multi_hot""count""tf_idf" 模式下有效。如果為 True,則輸出的特徵軸將會填充到 max_tokens,即使詞彙表中唯一詞符的數量小於 max_tokens,也會產生形狀為 (batch_size, max_tokens) 的張量,而與詞彙表大小無關。預設為 False
  • vocabulary:可選。字串陣列或文字檔案的字串路徑。如果傳遞陣列,則可以傳遞包含字串詞彙表的元組、清單、1D numpy 陣列或 1D 張量。如果傳遞檔案路徑,則檔案應包含詞彙表中每個詞語一行。如果設定此引數,則無需 adapt() 該層。
  • idf_weights:僅在 output_mode"tf_idf" 時有效。長度與詞彙表相同的元組、清單、1D numpy 陣列或 1D 張量,其中包含浮點數反向文件頻率權重,這些權重將乘以每個範例的詞語計數以取得最終 tf_idf 權重。如果設定 vocabulary 引數且 output_mode"tf_idf",則必須提供此引數。
  • ragged:布林值。僅適用於 "int" 輸出模式。如果為 True,則傳回 RaggedTensor 而不是密集 Tensor,其中每個序列在字串分割後可能具有不同的長度。預設為 False
  • sparse:布林值。僅適用於 "multi_hot""count""tf_idf" 輸出模式。如果為 True,則傳回 SparseTensor 而不是密集 Tensor。預設為 False
  • encoding:可選。用於解譯輸入字串的文字編碼。預設為 "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']