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

标签 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)一个不是直接从另一个张量派生的(它们的特征图已经存在,因此没有图,它们是有效的)独立的)。

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

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

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

最佳答案

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

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

关于python - Tensorflow急切执行-计算顺序模型的两层之间的梯度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56711640/

相关文章:

python - 无法识别对 python 代码的更改

Python:捕获两个异常之一

Python筛选素数

python - `gradient` 在构建 TensorFlow 图时给出 AttributeError

tensorflow - tensorflow 失败前提条件错误

python - 使用 Tensorflow 的 tf.io.gfile.exists 检查文件路径是否存在

python - 如何更新tensorflow中的 'eagertensor"对象

python - 处理未分配的变量

javascript - Tensorflow.js 是否有所有标识符的列表

python - 使用 Tensorflow 2.0 并在没有 Keras 的情况下立即执行