Tensorflow 2.3 / Keras-用于自定义升采样层的渐变功能?

问题描述

我编写了一个函数,该函数以与Upsampling2D不同的方式进行升采样。我将此函数包装在tf.py_function中,然后将其包装在Lambda层中以避免ValueError: UnkNown graph. Aborting.。 但是py_function需要梯度函数才能起作用,因为它在反向传播中返回None。

Invalid argument: Inputs to operation gradient_tape/SegNet/activation_23/ReluGrad of type ReluGrad must have the same size and shape. Input 0: [] != input 1: [16,16,32,32]

conv_24 = Activation("relu")(conv_24)
unpool_5 = Lambda(unpoolWrapper)(conv_24)
unpool_5 = Lambda(adjustShape,arguments={'oldshape': conv_24.shape})(unpool_5)
conv_25 = Conv2D(16,(5,5),kernel_initializer='he_normal',padding='same',data_format='channels_first')(unpool_5)

问题在第一个Lambda内部。

def unpoolWrapper(tensor):
    return py_func(unpool,[tensor],Tout=tf.float32)

我正在遵循此code解决渐变问题。 但是我不是专家,所以我不知道如何为这种层计算梯度。它只是进行上采样操作,没有需要学习的参数。有人可以建议我为此使用梯度函数吗?谢谢

def py_func(func,inp,Tout,grad=None):
    # Need to generate a unique name to avoid duplicates:
    rnd_name = 'PyFuncGrad' + str(np.random.randint(0,1E+8))

    tf.RegisterGradient(rnd_name)(grad)  # see _MySquareGrad for grad example
    g = tf.compat.v1.get_default_graph()
    with g.gradient_override_map({"PyFunc": rnd_name}):
        return tf.py_function(func,Tout)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)