【问题标题】:Keras Functional API and activationsKeras 功能 API 和激活
【发布时间】:2018-08-22 01:51:55
【问题描述】:

我在尝试通过 Keras 功能 API 使用激活时遇到问题。我最初的目标是在 relu 和leaky relu 之间进行选择,所以我想出了以下代码:

def activation(x, activation_type):
    if activation_type == 'leaky_relu':
        return activations.relu(x, alpha=0.3)
    else:
        return activations.get(activation_type)(x)


# building the model

inputs = keras.Input(input_shape, dtype='float32')
x = Conv2D(filters, (3, 3), padding='same')(inputs)
x = activation(x, 'relu')

但是这样的事情会产生错误:AttributeError: 'Tensor' object has no attribute '_keras_history'。我发现这可能表明我在Model中的输入和输出没有连接。

keras.advanced_activations 是在函数式 API 中实现此类功能的唯一方法吗?

编辑:这是有效的激活功能版本:

    def activation(self, x):
        if self.activation_type == 'leaky_relu':
            act = lambda x: activations.relu(x, alpha=0.3)
        else:
            act = activations.get(self.activation_type)
        return layers.Activation(act)(x)

【问题讨论】:

    标签: keras


    【解决方案1】:

    您想通过激活向模型添加激活。目前,您正在添加一个不是 Keras Layer 的对象,这会导致您的错误。 (在 Keras 中,图层名称总是以大写字母开头)。尝试这样的事情(最小的例子):

    from keras.layers import Input, Dense, Activation
    from keras import activations
    
    def activation(x, activation_type):
        if activation_type == 'leaky_relu':
            return activations.relu(x, alpha=0.3)
        else:
            return activations.get(activation_type)(x)
    
    
    # building the model
    inputs = Input((5,), dtype='float32')
    x = Dense(128)(inputs)
    # Wrap inside an Activation layer
    x = Activation(lambda x: activation(x, 'sigmoid'))(x)
    

    【讨论】:

    • 感谢您的建议!这很有帮助,但这并不是所需要的全部。我在这篇文章stackoverflow.com/a/44330431/6745559 中找到了答案的缺失部分
    • 很好,谢谢,我已经编辑了我的答案以供将来参考。
    猜你喜欢
    • 2018-09-26
    • 2017-01-12
    • 2011-02-03
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 2019-12-03
    相关资源
    最近更新 更多