我想在 Keras 中构建一个带有 softmax 层作为输出的 CNN,但我只得到这个作为输出:
[[[[ 1.]
[ 1.]
[ 1.]]]]
我的模型是这样构建的:
model = Sequential()
model.add(Conv2D(2, (1,3), padding='valid',
input_shape=(3,3,50), init='normal', data_format='channels_first'))
model.add(Activation('relu'))
model.add(Conv2D(20, (1,48), init='normal', data_format='channels_first'))
model.add(Activation('relu'))
model.add(Conv2D(1, (1, 1), init='normal', data_format='channels_first', activation='softmax'))
我不太明白,为什么 softmax 不起作用。可能是因为输入形状错误?
请您参考如下方法:
softmax 激活将应用于最后一个轴。
查看您的 model.summary(),您的输出形状是 (None, 3, 3, 1)。
在最后一个轴上只有一个元素,您的 softmax 输出将始终为 1。
您必须选择要对哪个轴求和 1,然后正确调整输出的形状。例如,如果你想让 softmax 考虑 3 个 channel ,你需要将这些 channel 移动到最终位置:
#your last convolutional layer, without the activation:
model.add(Conv2D(3, (1, 1), kernel_initializer='normal', data_format='channels_first'))
#a permute layer to move the channels to the last position:
model.add(Permute((2,3,1)))
#the softmax, now considering that channels sum 1.
model.add(Activation('softmax'))
但是如果您的目的是整个结果总和为 1,那么您应该添加 Flatten() 而不是 Permute()。
Keras 似乎更适合使用 channels_last。在这种情况下,softmax 将自动应用于 channel ,无需额外工作。
