gpt4 book ai didi

python - Keras 自定义层 : change values of tensor based on conditions

转载 作者:太空宇宙 更新时间:2023-11-04 02:11:27 24 4
gpt4 key购买 nike

我尝试编写一个自定义 keras 层,它会更改张量的值。但是,numpy 语法不起作用。我认为代码是不言自明的:

class myLayer(Layer):
def __init__(self, **kwargs):
super(myLayer, self).__init__(**kwargs)

def build(self, input_shapes):
super(myLayer, self).build(input_shapes)

def call(self, inputs, mask=None):
inputs[(inputs>0) & (inputs<1)] = 1
inputs[inputs<=0] = K.exp(inputs)
inputs[inputs>1] = K.exp(1-inputs)
return inputs

def compute_output_shape(self, input_shapes):
return input_shapes

如何使用 tensorflow 编写作业并仍然允许反向传播?

最佳答案

你的函数没有可训练的参数,因此,你应该使用 Lambda 层,这样可以省去你写这么多的麻烦(但你所做的也不是问题)。

def customCall(inputs):

ones = K.ones_like(inputs)
lower = K.exp(inputs)
higher = K.exp(1-inputs)

outputs = K.switch(K.greater(inputs,1), higher, ones)
outputs = K.switch(K.less_equal(inputs,0), lower, outputs)

return outputs

图层:

Lambda(customCall)

警告:

输出等于 1 的部分的梯度等于 0。该区域可能会卡在训练中。

关于python - Keras 自定义层 : change values of tensor based on conditions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53648742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com