CategoryEncoding 层

[源代码]

CategoryEncoding

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

一个用于编码整数特征的预处理层。

该层提供了在词汇量总数已知的情况下将数据压缩为类别编码的选项。它接受整数值作为输入,并输出这些输入的密集或稀疏表示。对于词汇量总数未知的整数输入,请使用 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: 该层应支持的总词汇量。层的所有输入必须是范围为 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",但整数数组包含样本中出现的词汇项计数的数量。对于所有输出模式,目前仅支持最多 rank 2 的输出。默认为 "multi_hot"
  • sparse: 布尔值。如果为 True,则返回 SparseTensor 而不是密集 Tensor。默认为 False

调用参数

  • inputs: 一个 1D 或 2D 的整数输入张量。
  • count_weights: 与 inputs 形状相同的张量,指示在 count 模式下求和时每个样本值的权重。在 "multi_hot""one_hot" 模式下不使用。