CategoryEncoding
类keras.layers.CategoryEncoding(
num_tokens=None, output_mode="multi_hot", sparse=False, **kwargs
)
一个预处理层,用于编码整数特征。
当预先知道令牌总数时,此层提供了将数据压缩为类别编码的选项。它接受整数值作为输入,并输出这些输入的密集或稀疏表示。对于令牌总数未知的整数输入,请改用 keras.layers.IntegerLookup
。
注意: 此层可以安全地在 tf.data
管道中使用(与您使用的后端无关)。
示例
独热编码数据
>>> layer = keras.layers.CategoryEncoding(
... num_tokens=4, output_mode="one_hot")
>>> layer([3, 2, 0, 1])
array([[0., 0., 0., 1.],
[0., 0., 1., 0.],
[1., 0., 0., 0.],
[0., 1., 0., 0.]]>
多热编码数据
>>> layer = keras.layers.CategoryEncoding(
... num_tokens=4, output_mode="multi_hot")
>>> layer([[0, 1], [0, 0], [1, 2], [3, 1]])
array([[1., 1., 0., 0.],
[1., 0., 0., 0.],
[0., 1., 1., 0.],
[0., 1., 0., 1.]]>
在 "count"
模式下使用加权输入
>>> layer = 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)
array([[0.1, 0.2, 0. , 0. ],
[0.2, 0. , 0. , 0. ],
[0. , 0.2, 0.3, 0. ],
[0. , 0.2, 0. , 0.4]]>
参数
0 <= value < num_tokens
范围内的整数,否则将抛出错误。"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"
。调用参数
inputs
形状相同的张量,指示在 count
模式下求和时每个样本值的权重。不在 "multi_hot"
或 "one_hot"
模式下使用。