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"
,但整数数组包含该索引处的令牌在样本中出现的次数计数。对于所有输出模式,目前仅支持最高秩为 2 的输出。默认为 "multi_hot"
。调用参数
inputs
相同的张量,在 count
模式下求和时指示每个样本值的权重。在 "multi_hot"
或 "one_hot"
模式下不使用此参数。