如果与 one-hot 标签和 categorical_crossentropy amnd softmax 输出一起使用,为什么 keras 模型将所有预测为一个

问题描述

我有一个简单的 tf.keras 模型:

inputs = keras.Input(shape=(9824,))
dense = layers.Dense(512,activation=keras.activations.relu,kernel_initializer=init)
x = dense(inputs)
x = layers.Dense(512,activation=keras.activations.relu)(x)
outputs = layers.Dense(3,activation=keras.activations.softmax)(x)
model = keras.Model(inputs=inputs,outputs=outputs)

当我使用稀疏分类交叉熵和实际标签编译它时,它按预期工作。 但是,当我尝试对标签进行单热编码(使用 tf.keras.utils.to_categorical)并使用 categorical_crossentropy(因此我可以在训练期间使用召回率和精度作为指标)时,模型将所有内容预测为:

>>>print(predictions)
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]
 ...
 [1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]

如果我理解正确,输出层中的 softmax 激活应该导致输出在 (0,1) 范围内并且总和为 1。 那么,怎么可能课堂预测都是 1?我一直在寻找答案,但无济于事。

编辑

这是一个简约的 example

我忘了说我使用 scikeras 包。根据 documentation 中的示例,我假设模型是隐式编译的。这是分类器构造函数

clf = KerasClassifier(
    model=keras_model_target,loss=SparseCategoricalCrossentropy(),name="model_target",optimizer=Adam(),init=GlorotUniform(),metrics=[SparseCategoricalAccuracy()],epochs=5,batch_size=128
)

我适合模型

result = clf.fit(x_train,y_train)

并预测:

predictions = clf.predict(x)

解决方法

这是 SciKeras 中的一个错误,已在 v0.3.1 版本中修复。更新到最新版本应该可以解决问题。

至于 bug 本身,这是由于我们如何索引 numpy 数组,详情参见 this diff