【问题标题】:Keras: multiclass classificationKeras:多类分类
【发布时间】:2017-02-15 21:51:23
【问题描述】:

我正在遵循 herehere 中的示例,并且对 Keras 完全陌生。看起来很神奇 - 但我遇到了一些我不明白的事情。

我有一个 8 类分类问题。我的训练集有 5120 行和 62 列,最后一列是目标变量。

我的目标变量目前被编码为浮点数,因此我将它们转换为整数,然后使用 to_categorical 转换为模型的虚拟矩阵。结果是一个形状为 (num_samples, num_classes+1) 的 numpy.ndarray。有人知道为什么吗?

代码如下:

import numpy as np
from keras.utils.np_utils import to_categorical

dataset = np.loadtxt("train_pl.csv", delimiter=",")

# split into input (X) and output (Y) variables
X = dataset[:,0:61] #I have 5120 rows. 
Y = (dataset[:,62]).astype(int) #class labels 1 to 8 inclusive

#print Y.shape #(5120,)
#print np.unique(Y) #1 2 3 4 5 6 7 8 

y_binary = to_categorical(Y)

print y_binary.shape #(5120, 9) - why does this have 9 columns?

编辑

我不理解给出的答案的原因是我不明白 Keras 将类标签逐字解释为数字。例如,由于我的类被标记为 1 到 8,Keras 会查看标签“1”并说“这是一个 1 - 我将它放在 one-hot 向量中的“1”位置,如下所示:0 1 0 0 0 0 0 0 0。它与“2”相同:0 0 1 0 0 0 0 0 0,最多 8 个。这就是为什么有一个额外的列:处理“第 0”个情况,它没有t 存在于映射中。从技术上讲,公认的答案解释说,这只是提供了更多细节。

【问题讨论】:

    标签: python keras


    【解决方案1】:

    因为to_categorical 将类向量(整数从 0 转换为 nb_classes)为二进制类矩阵,以便与 here 中记录的 categorical_crossentropy 一起使用。

    【讨论】:

    • 虽然在教程here中,作者在定义模型时,有3个输出单元,与to_categorical结果的维数相同。我做不到 - 我的输出中不能有 9 个类。
    • 您可以尝试在训练前使用Y = Y - 1 将标签 (y) 映射到 0..7。进行预测后,将它们映射回来
    • 为什么有必要这样做呢?本教程有 3 个输出节点,以及在 to_categorical....中定义的 3 个类。
    • 本教程基本上是使用LabelEncoder (doc) 做同样的事情。它基本上将标签(Iris-setosa, Iris-versicolor, Iris-virginica) 转换为(0,1,2),然后再由to_categorical 转换为one-hot-encoding
    • 是的,该示例将三个类作为另一种数据类型,一旦将它们转换为 one-hot 编码,仍然是三个类,而不是四个。由于我没有非数字标签,我认为我不需要担心使用 LabelEncoder 进行转换(我还是尝试过,结果相同)。
    猜你喜欢
    • 2018-03-08
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 2018-08-04
    • 2019-07-20
    • 2021-07-17
    • 2017-09-27
    • 2020-10-12
    相关资源
    最近更新 更多