【问题标题】:How to add a custom layer in keras如何在 keras 中添加自定义图层
【发布时间】:2019-03-20 04:11:31
【问题描述】:

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

【问题讨论】:

  • 你的意思是all the element of previous layer从上一层激活

标签: tensorflow keras layer


【解决方案1】:

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

输出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 和 0,则 (x==0.5) 被评估为 1。

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

【讨论】:

    猜你喜欢
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多