在 Keras 中使用自定义步骤激活函数会导致"An operation has `None` for gradient."错误。如何解决这个问题?



我正在构建自动编码器,我想将我的值编码到逻辑矩阵中。但是,当我在其中一个中间层中使用自定义步骤激活函数时(所有其他层都使用"relu"(,keras 会引发此错误:

An operation has `None` for gradient.

我尝试使用硬 sigmoid 函数,但它不适合我的问题,因为当我只需要二进制时,它仍然会产生中间值。我知道,在大多数点上我的函数没有梯度,但是是否可以使用其他函数进行梯度计算,并且仍然使用阶跃函数进行精度和损失计算?

我的激活功能:

def binary_activation(x):
    ones = tf.ones(tf.shape(x), dtype=x.dtype.base_dtype)
    zeros = tf.zeros(tf.shape(x), dtype=x.dtype.base_dtype)
    return keras.backend.switch(x > 0.5, ones, zeros)

我希望能够使用二进制步骤激活函数来训练网络,然后将其用作典型的自动编码器。本文中使用的类似于二进制特征图的东西。

如此处所述,您可以使用tf.custom_gradient为激活函数定义"反向传播"梯度。

也许像这样:

@tf.custom_gradient
def binary_activation(x):
    ones = tf.ones(tf.shape(x), dtype=x.dtype.base_dtype)
    zeros = tf.zeros(tf.shape(x), dtype=x.dtype.base_dtype)
    def grad(dy):
        return ...  # TODO define gradient
  return keras.backend.switch(x > 0.5, ones, zeros), grad

相关内容

最新更新