自定义图层Keras:在特定位置变换输出

2024-05-15 17:00:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在Keras中编写一个自定义层(带有tensorflow后端),使某些位置成为二进制的

例如,假设我有[0.6,0.8,0.9,0.2],位置1和3必须是二进制的,我希望有一个输出[0.6,1,0.9,0]的层

例如,输出[pos]>;0.5则输出[pos]=1,否则输出[pos]=0

我写了这篇文章,但它根本不起作用

...Layers of the net...
x = Lambda(self.adjust_positions)(x)

这里是我写的函数

    def update_1(self, x, pos):
        with tf.control_dependencies([tf.assign(x[pos],[1])]):
                return tf.identity(x)

    def update_0(self, x, pos):
        with tf.control_dependencies([tf.assign(x[pos],[0])]):
                return tf.identity(x)

    def adjust_positions(self, x):
        for pos in indexes:
            tf.cond(tf.gather(x, pos)<[0.5], self.update_0(x, pos), self.update_1(x,pos))
        return x

我得到的错误是:

ValueError: Sliced assignment is only supported for variables
     55     def update_0(self, x, pos):
---> 56         with tf.control_dependencies([tf.assign(x[pos],[0])]):
     57                 return tf.identity(x)

如何实现此功能?我所做的是合理的吗


Tags: posselfforreturntfdefwith二进制