我正在尝试使用 tensorflow-gpu 版本 2.4.1 和 Keras 版本 2.4.3 使用以下代码计算来自 VGG16 w.r.t 图像输入的 CNN 过滤器之一的梯度:
from keras.applications import VGG16
from keras import backend as K
model = VGG16(weights = 'imagenet',
include_top = False)
layer_name = 'block3_conv1'
filter_index = 0
layer_output = model.get_layer(layer_name).output
loss = K.mean(layer_output[:, :, :, filter_index])
grads = K.gradients(loss, model.input)[0]
这会导致以下错误:
RuntimeError: tf.gradients is not supported when eager execution is enabled. Use tf.GradientTape instead.
同时尝试使用 tf.GradientTape
引发了另一个错误:
with tf.GradientTape() as gtape:
grads = gtape.gradient(loss, model.input)
AttributeError: 'KerasTensor' object has no attribute '_id'
尝试禁用 eager execution 也不起作用:
tf.compat.v1.disable_eager_execution()
因为它将梯度返回为 None。 如果能提供有关解决此问题的任何方法的任何信息,我将不胜感激。 提前致谢。
最佳答案
让 layer = model.get_layer(layer_name)
首先需要构建模型图
from tensorflow.keras import models
heatmap_model = models.Model([model.inputs],[layer.output,model.output])
然后你需要运行tf.GradientTape()
with tf.GradientTape() as gtape:
layer_output, predictions = heatmap_model(img)
loss = predictions[:,np.argmax(predictions)]
grads = gtape.gradient(loss, layer_output)
请注意 gtape.gradient
有 layer_output
而不是 layer.output
关于python - keras(tensorflow后端)中计算梯度的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66283913/