我有一个神经网络,以 one-hot m*n 向量作为输入,行代表类别,列代表位置。
我想训练一个网络,在输出层输出另一个具有相同 m*n 形状的(随机)向量,每列的概率总和为 1。这个想法是使用 softmax 最后一层,但是我需要单独构建每一列并连接 like here ?或者是否可以在 Keras 中(例如单行)更简单地执行此操作?
最佳答案
如果您的模型的输出形状为(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)
关于python - keras 中 softmax 输出的一个热输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52432258/