CategoryEncoding 層

[原始碼]

CategoryEncoding 類別

tf_keras.layers.CategoryEncoding(
    num_tokens=None, output_mode="multi_hot", sparse=False, **kwargs
)

一個預處理層,用於編碼整數特徵。

當預先知道 token 的總數時,此層提供將資料濃縮為類別編碼的選項。它接受整數值作為輸入,並輸出這些輸入的密集或稀疏表示。對於不知道 token 總數的整數輸入,請改用 tf.keras.layers.IntegerLookup

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

範例

獨熱編碼資料

>>> layer = tf.keras.layers.CategoryEncoding(
...           num_tokens=4, output_mode="one_hot")
>>> layer([3, 2, 0, 1])
<tf.Tensor: shape=(4, 4), dtype=float32, numpy=
  array([[0., 0., 0., 1.],
         [0., 0., 1., 0.],
         [1., 0., 0., 0.],
         [0., 1., 0., 0.]], dtype=float32)>

多熱編碼資料

>>> layer = tf.keras.layers.CategoryEncoding(
...           num_tokens=4, output_mode="multi_hot")
>>> layer([[0, 1], [0, 0], [1, 2], [3, 1]])
<tf.Tensor: shape=(4, 4), dtype=float32, numpy=
  array([[1., 1., 0., 0.],
         [1., 0., 0., 0.],
         [0., 1., 1., 0.],
         [0., 1., 0., 1.]], dtype=float32)>

"count" 模式中使用加權輸入

>>> layer = tf.keras.layers.CategoryEncoding(
...           num_tokens=4, output_mode="count")
>>> count_weights = np.array([[.1, .2], [.1, .1], [.2, .3], [.4, .2]])
>>> layer([[0, 1], [0, 0], [1, 2], [3, 1]], count_weights=count_weights)
<tf.Tensor: shape=(4, 4), dtype=float64, numpy=
  array([[0.1, 0.2, 0. , 0. ],
         [0.2, 0. , 0. , 0. ],
         [0. , 0.2, 0.3, 0. ],
         [0. , 0.2, 0. , 0.4]], dtype=float32)>

參數

  • num_tokens: 此層應支援的 token 總數。此層的所有輸入都必須是 0 <= value < num_tokens 範圍內的整數,否則會拋出錯誤。
  • output_mode: 此層輸出的規格。值可以是 "one_hot""multi_hot""count",配置此層如下:
    • "one_hot": 將輸入中的每個個別元素編碼為大小為 num_tokens 的陣列,其中元素索引處為 1。如果最後一個維度的大小為 1,則將在該維度上編碼。如果最後一個維度的大小不是 1,則將為編碼輸出附加一個新維度。
    • "multi_hot": 將輸入中的每個樣本編碼為大小為 num_tokens 的單個陣列,其中每個存在於樣本中的詞彙項為 1。如果輸入形狀為 (..., sample_length),則將最後一個維度視為樣本維度,輸出形狀將為 (..., num_tokens)
    • "count": 與 "multi_hot" 類似,但整數陣列包含該索引處的 token 在樣本中出現的次數。對於所有輸出模式,目前僅支援最多 rank 2 的輸出。預設為 "multi_hot"
  • sparse: 布林值。如果為 true,則返回 SparseTensor 而不是密集 Tensor。預設為 False

呼叫參數

  • inputs: 整數輸入的一維或二維張量。
  • count_weights: 形狀與 inputs 相同的張量,表示在 count 模式下求和時每個樣本值的權重。不在 "multi_hot""one_hot" 模式中使用。