在 Keras 层中使用 softmax 激活时如何指定轴?

Rob*_*eph 6 deep-learning keras activation-function

用于 softmax 激活的 Keras文档指出,我可以指定激活应用于哪个轴。我的模型应该输出一个n × k矩阵M,其中Mij是第i个字母是符号j的概率。

n = 7 # number of symbols in the ouput string (fixed)
k = len("0123456789") # the number of possible symbols

model = models.Sequential()
model.add(layers.Dense(16, activation='relu', input_shape=((N,))))
...
model.add(layers.Dense(n * k, activation=None))
model.add(layers.Reshape((n, k)))

model.add(layers.Dense(output_dim=n, activation='softmax(x, axis=1)'))
Run Code Online (Sandbox Code Playgroud)

最后一行代码无法编译,因为我不知道如何k为 softmax 激活正确指定轴(在我的情况下为轴)。

Dan*_*ler 7

您必须在那里使用实际函数,而不是字符串。

为方便起见,Keras 允许您使用一些字符串。

激活函数可以在keras.activations 中找到,它们列在帮助文件中

from keras.activations import softmax

def softMaxAxis1(x):
    return softmax(x,axis=1)

..... 
......
model.add(layers.Dense(output_dim=n, activation=softMaxAxis1))
Run Code Online (Sandbox Code Playgroud)

甚至自定义轴:

def softMaxAxis(axis):
    def soft(x):
        return softmax(x,axis=axis)
    return soft

...
model.add(layers.Dense(output_dim=n, activation=softMaxAxis(1)))
Run Code Online (Sandbox Code Playgroud)