【问题标题】:How to specify the axis when using the softmax activation in a Keras layer?在 Keras 层中使用 softmax 激活时如何指定轴?
【发布时间】:2018-02-07 09:11:14
【问题描述】:

softmax 激活的 Keras docs 声明我可以指定激活应用于哪个轴。我的模型应该通过 k 矩阵 M 输出一个 n,其中 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)'))

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

【问题讨论】:

    标签: deep-learning keras activation-function


    【解决方案1】:

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

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

    激活函数可以在keras.activations 中找到,它们在the help file 中列出。

    from keras.activations import softmax
    
    def softMaxAxis1(x):
        return softmax(x,axis=1)
    
    ..... 
    ......
    model.add(layers.Dense(output_dim=n, activation=softMaxAxis1))
    

    甚至是自定义轴:

    def softMaxAxis(axis):
        def soft(x):
            return softmax(x,axis=axis)
        return soft
    
    ...
    model.add(layers.Dense(output_dim=n, activation=softMaxAxis(1)))
    

    【讨论】:

    • 执行此操作后出现错误“softmax() got an unexpected keyword argument 'axis'”。
    • 嗯...也许您需要更新的 keras/tensorflow 版本...您也可以结合Permute 层将所需的轴移动到最后,使用softmax 和另一个@987654327 @ 恢复旧位置。
    • 或者你可以直接从backend获取softmax而不是activations
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 2017-07-30
    • 1970-01-01
    • 2019-05-09
    • 2018-05-26
    相关资源
    最近更新 更多