Keras功能性API和激活

时间:2018-08-21 12:39:04

标签: keras

尝试在Keras Functional API上使用激活时遇到问题。我最初的目标是在relu和泄漏的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'。我发现这可能表明我在模型中的输入和输出未连接。

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)

1 个答案:

答案 0 :(得分:3)

您要通过激活图层将激活添加到模型中。当前,您正在添加的不是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)