首页 > 解决方案 > 在 Tensorflow 和 Keras 的两个通道上生成 softmax

问题描述

我的网络倒数第二层的形状(U, C)C通道数。我想分别在每个通道上应用 softmax 函数。

例如,如果U=2C=3,并且层产生[ [1 2 3], [10 20 30] ],我希望输出softmax(1, 2, 3)对通道 0 和softmax(10, 20, 30)通道 1 执行。

有没有办法用 Keras 做到这一点?我使用 TensorFlow 作为后端。

更新

还请解释如何确保损失是两个交叉熵的总和,以及我如何验证这一点?(也就是说,我不希望优化器只针对其中一个 softmax 的损失进行训练,而是针对每个的交叉熵损失的总和进行训练)。该模型使用 Keras 内置categorical_crossentropy的损失函数。

标签: pythontensorflowkerassoftmax

解决方案


对多个输出使用功能 api。https://keras.io/getting-started/functional-api-guide/

input = Input(...)
...
t = some_tensor
t0 = t0[:,:,0]
t1 = t0[:,:,1]
soft0 = Softmax(output_shape)(t0)
soft1 = Softmax(output_shape)(t1)
outputs = [soft0,soft1]
model = Model(inputs=input, outputs=outputs)
model.compile(...)
model.fit(x_train, [y_train0, ytrain1], epoch = 10, batch_size=32)

推荐阅读