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" 类似,但 int 数组包含该索引处的标记在样本中出现的次数。对于所有输出模式,目前仅支持输出最多 2 个维度。默认为 "multi_hot"
  • sparse: 布尔值。如果为真,则返回 SparseTensor 而不是密集 Tensor。默认为 False

调用参数

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