如何在keras中添加自定义图层

问题描述 投票:0回答:1

我想添加一个图层,前一层<0.5的所有元素都是0,前一层>=0.5的所有元素都是1。 你知道怎么做吗?

tensorflow keras layer
1个回答
0
投票

您可以在一些除法运算中使用Modified ReLU激活。以下解决方案几乎没有修改,因为它输出0表示x == 0.5。

输出O(x)可以重写为

现在自定义图层将是



class CustomReLU(Layer):

    def __init__(self, **kwargs):
        super(CustomReLU, self).__init__(**kwargs)

    def build(self, input_shape):

        super(CustomReLU, self).build(input_shape)  

    def call(self, x):
        relu = ReLU()
        output = relu(x-0.5)/(x-0.5)
        return output

    def compute_output_shape(self, input_shape):
        return input_shape

编辑:

对于x = 0.5,上述等式和代码可以很容易地修改为以下内容。 , 其中(x==0.5)被评估为1,如果x等于0.5和0。

import keras.backend as K

class CustomReLU(Layer):

    def __init__(self, **kwargs):
        super(CustomReLU, self).__init__(**kwargs)

    def build(self, input_shape):

        super(CustomReLU, self).build(input_shape)  

    def call(self, x):
        relu = ReLU()
        output = relu(x-0.5)/(x-0.5) + K.cast(K.equal(x, 0.5), K.floatx())
        return output

    def compute_output_shape(self, input_shape):
        return input_shape
© www.soinside.com 2019 - 2024. All rights reserved.