计算 Keras 的 Upsample2D 层的第二个梯度

时间:2021-01-17 15:57:30

标签: tensorflow keras image-resizing backpropagation

我试图复制和调整代码,以便为我的 CNN 模型查找 Hessian-Vector 乘积,如“An Investigation into Neural Net Optimization via Hessian Eigenvalue Density”中所做的那样。 然后,我注意到它抛出了一个错误; “LookupError: gradient registry has no entry for: ResizeBilinearGrad”。经过一些调试和搜索,我发现问题出在我的模型中的 Keras Upsampling2D 层。一阶导数计算工作正常,但是当我尝试计算第二个梯度(第一个梯度的导数)时,它会引发此错误。 我发现“ResizeBilinearGrad”操作的梯度函数没有在 Tensorflow 中实现,这导致了上述错误。我发现可以使用 @tf.RegisterGradient(“ResizeBilinearGrad”) 注册自定义渐变,但我不知道它到底应该返回什么。所需的梯度函数应具有以下形式:

@tf.RegisterGradient(“ResizeBilinearGrad”)
def _ResizeBilinearGradGrad(op, grad):
    return (A,B)

哪里,
grad - 梯度 w.r.t 到 ResizeBilinearGrad op
的输出 op - ‘ResizeBilinearGrad’
A - 梯度 w.r.t 第一个输入到操作
B - 梯度 w.r.t 输入图像

“ResizeBilinearGrad”操作的输入是:
A - 计算到那个点的梯度
B - 原始输入图像

有人可以为这个问题提供一些指导吗?
您可以使用下面给出的代码检查此问题:

import keras
from keras.models import Sequential
from keras.layers import UpSampling2D
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf

# Generate some data
input_flattened = np.arange(2, 4, 0.5)#can vary input -  no change in grad
input_image = np.reshape(input_flattened, (2, 2, 1))
input_image_shape = np.shape(input_image)
input_image_shape = (input_image_shape[0], input_image_shape[1], 1)

# Create the model
model = Sequential()
model.add(UpSampling2D((2, 2), interpolation='bilinear'))

model_inputs = tf.Variable([input_image])
with tf.GradientTape() as out:
    with tf.GradientTape() as inn:
        inn.watch(model_inputs)
        outputs_upsampled = model(model_inputs)
    grad = inn.gradient(tf.cast(outputs_upsampled,tf.float32),model_inputs)
grad2 = out.gradient(grad,model_inputs,unconnected_gradients=tf.UnconnectedGradients.ZERO)

0 个答案:

没有答案