一个热输入到keras的softmax输出

时间:2018-09-20 19:45:07

标签: python machine-learning neural-network keras softmax

我有一个神经网络,其中一热m * n向量作为输入,行代表类别,而列则代表位置。

我想训练一个网络,以在输出层输出具有相同m * n形状的另一个(随机)矢量,每列的概率总计为1。想法是使用softmax最后一层,但是我是否需要分别构建每列并连接like here?还是有可能在Keras中(例如单线)更简单地做到这一点?

1 个答案:

答案 0 :(得分:1)

如果模型的输出形状为(None, m, n),并且您想计算第二个轴上的softmax,则可以简单地使用softmax激活方法并将axis参数传递给它(在您的情况下,它必须为axis=1):

from keras import activations

def the_softmax(axis):
    def my_softmax(x):
        return activations.softmax(x, axis=axis)
    return my_softmax

# sequential model
model.add(Dense(..., activation=the_softmax(1)))

# functional model
output = Dense(..., activation=the_softmax(1))(prev_layer_output)

或者,如果您想将其用作独立层,则可以使用Lambda层和后端softmax函数:

from keras import backend as K

def the_softmax(axis):
    def my_softmax(x):
        return K.softmax(x, axis=axis)
    return my_softmax

# sequential model
model.add(Lambda(the_softmax(1)))

# functional model
output = Lambda(the_softmax(1))(prev_layer_output)