使用 keras utils to_categorical 将分类数据转换回数字

Shi*_*esh 6 python deep-learning keras

我正在使用to_categoricalfromkeras.utils对列表中的数字进行一次性编码。如何从分类数据中取回数字?是否有任何可用的功能。

Y=to_categorical(y, num_classes=79)
Run Code Online (Sandbox Code Playgroud)

Ami*_*mir 5

你可以简单地通过np.argmax()

import numpy as np
y = [0, 1, 2, 0, 4, 5]
Y = to_categorical(y, num_classes=len(y))
print(Y)
y = np.argmax(Y, axis=-1)
print(y)
# [0, 1, 2, 0, 4, 5]
Run Code Online (Sandbox Code Playgroud)

为什么使用argmax(axis=-1)

在上面的例子中,to_categorical返回一个形状为 (6,6) 的矩阵。设置axis=-1意味着,在每一行中提取最大的索引。

[[1. 0. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0. 0.]
 [0. 0. 1. 0. 0. 0.]
 [1. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 1. 0.]
 [0. 0. 0. 0. 0. 1.]]
Run Code Online (Sandbox Code Playgroud)

此处查看有关索引的更多信息。

如果我的数据有多个维度怎么办?

没有不同。初步列表中的每个条目都转换为one-hot编码,其大小[1, nb_classes]只有一个索引为1,其余为0。与上面的例子类似,当你在每一行中找到最大值时,它会转换为原始列表。

y = [[0, 1], [2, 0], [4, 5]]
Y = keras.utils.to_categorical(y, num_classes=6)

#[[[1. 0. 0. 0. 0. 0.]
#  [0. 1. 0. 0. 0. 0.]]
#
# [[0. 0. 1. 0. 0. 0.]
#  [1. 0. 0. 0. 0. 0.]]
#
# [[0. 0. 0. 0. 1. 0.]
#  [0. 0. 0. 0. 0. 1.]]]

y = np.argmax(Y, axis=-1)

#[[0 1]
# [2 0]
# [4 5]]
Run Code Online (Sandbox Code Playgroud)