使用参数自定义激活

时间:2018-10-29 17:04:17

标签: python machine-learning keras keras-layer activation-function

我正在尝试在Keras中创建一个激活函数,该函数可以像这样输入参数beta

from keras import backend as K
from keras.utils.generic_utils import get_custom_objects
from keras.layers import Activation

class Swish(Activation):

    def __init__(self, activation, beta, **kwargs):
        super(Swish, self).__init__(activation, **kwargs)
        self.__name__ = 'swish'
        self.beta = beta


def swish(x):
    return (K.sigmoid(beta*x) * x)

get_custom_objects().update({'swish': Swish(swish, beta=1.)})

在没有beta参数的情况下可以正常运行,但是如何在激活定义中包括该参数?我还希望在执行model.to_json()时(例如用于ELU激活)保存该值。


更新:我根据@today的答案编写了以下代码:

from keras.layers import Layer
from keras import backend as K

class Swish(Layer):
    def __init__(self, beta, **kwargs):
        super(Swish, self).__init__(**kwargs)
        self.beta = K.cast_to_floatx(beta)
        self.__name__ = 'swish'

    def call(self, inputs):
        return K.sigmoid(self.beta * inputs) * inputs

    def get_config(self):
        config = {'beta': float(self.beta)}
        base_config = super(Swish, self).get_config()
        return dict(list(base_config.items()) + list(config.items()))

    def compute_output_shape(self, input_shape):
        return input_shape

from keras.utils.generic_utils import get_custom_objects
get_custom_objects().update({'swish': Swish(beta=1.)})
gnn = keras.models.load_model("Model.h5")
arch = gnn.to_json()
with open(directory + 'architecture.json', 'w') as arch_file:
    arch_file.write(arch)

但是,它当前不将beta值保存在.json文件中。如何保存它的值?

1 个答案:

答案 0 :(得分:4)

由于在序列化模型时要保存激活函数的参数,我认为最好将激活函数定义为advanced activations which have been defined in Keras之类的层。您可以这样做:

from keras.layers import Layer
from keras import backend as K

class Swish(Layer):
    def __init__(self, beta, **kwargs):
        super(Swish, self).__init__(**kwargs)
        self.beta = K.cast_to_floatx(beta)

    def call(self, inputs):
        return K.sigmoid(self.beta * inputs) * inputs

    def get_config(self):
        config = {'beta': float(self.beta)}
        base_config = super(Swish, self).get_config()
        return dict(list(base_config.items()) + list(config.items()))

    def compute_output_shape(self, input_shape):
        return input_shape

然后,您可以像使用Keras层一样使用它:

# ...
model.add(Swish(beta=0.3))

由于已经在其定义中实现了get_config()方法,因此在使用betato_json()之类的方法时,参数save()将被保存。