Tensorflow急切执行-计算顺序模型两层之间的梯度

时间:2019-06-22 00:11:18

标签: python tensorflow eager-execution

我正在尝试使用Tensorflow的新的急切执行模式来遵循http://www.hackevolve.com/where-cnn-is-looking-grad-cam/上的指南。特别是一行让我感到难过:

grads = K.gradients(class_output, last_conv_layer.output)[0]

我知道它正在查找最后一个卷积层和特定类输出之间的梯度。但是,我无法弄清楚如何使用GradientTape完成此操作,因为(a)都是张量而不是变量,并且(b)一个不是直接从另一个张量派生的(它们的特征图已经存在,因此没有图它们实际上是独立的)。

编辑:更多信息。 尚未有任何参与者回答,因此,我将继续添加自发布问题以来我尝试过的内容:

显而易见的步骤是通过热切的执行来重现第一部分。

import numpy as np
import cv2
import tensorflow as tf
tf.enable_eager_execution()

model = tf.keras.models.load_model("model.h5")
print(type(model))
# tensorflow.python.keras.engine.sequential.Sequential

from dataset import prepare_dataset
_, ds, _, _, _, _ = prepare_dataset() # ds is a tf.data.Dataset
print(type(ds))
# tensorflow.python.data.ops.dataset_ops.DatasetV1Adapter

it = train_ds.make_one_shot_iterator()
img, label = it.get_next()
print(type(img), img.shape)
# <class 'tensorflow.python.framework.ops.EagerTensor'> (192, 192, 3)

print(type(label), label.shape)
# <class 'tensorflow.python.framework.ops.EagerTensor'> (2,)

img = np.expand_dims(img, axis=0)
print(img.shape)
# (1, 192, 192, 3)

predictions = model.predict(img)
print(predictions)
# array([[0.9711799 , 0.02882008]], dtype=float32)

class_idx = np.argmax(predictions[0])
print(class_idx)
# 0

class_output = model.output[:, class_idx]
print(model.output, class_output)
# Tensor("Softmax:0", shape=(?, 2), dtype=float32) Tensor("strided_slice_5:0", dtype=float32)

# I use tf.keras.layers.Activation instead of the activation parameter of conv2d,
# so last_conv_layer actually points to the layer after the last conv layer.
# Is that not correct?
last_conv_layer = model.get_layer('activation_6') 

"""
Now, the fun part: how do I compute the gradient of class_output with respect to
the output of the last convolutional layer?
"""

一种尝试是使用reduce_sum并乘以得到所需的梯度(忽略class_output步骤):

with tf.GradientTape() as tape: 
    print(label)
    # tf.Tensor([1. 0.], shape=(2,), dtype=float32)
    y_c = tf.reduce_sum(tf.multiply(model.output, label))
    print(y_c)
    # Tensor("Sum_4:0", shape=(), dtype=float32)
    last_conv_layer = model.get_layer('activation_6')

grad = tape.gradient(y_c, last_conv_layer.output)

但是,在此设置中,gradNone

1 个答案:

答案 0 :(得分:0)

您是否尝试过将predictions = model.predict(img)以后的代码放入GradientTape上下文管理器中?

问题是,如果您没有记录从last_conv_layer.outputmodel.output的渐变,则反向传播链实际上会断裂。