python - keras(tensorflow后端)中计算梯度的错误

标签 python tensorflow keras gradient

我正在尝试使用 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.gradientlayer_output 而不是 layer.output

关于python - keras(tensorflow后端)中计算梯度的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66283913/

相关文章:

python - 使用 Python C API 将 Python 整数列表传递给 C 函数

python - 仅当输入少于 3 个字符时,WTForms 返回 None

python - 强制 LSTM Keras 使用时间序列依赖项

c++ - 计算位掩码,枚举 0

java - NotADirectoryError:[Errno 20]不是目录:'java'

python - 使 tfp.sts.fit_with_hmc 更快

python - tf.layers.conv1d 与 tf.layers.conv2d 之间的区别

python - Pandas - KeyError : '[] not in index' when training a Keras model

python - 神经网络回归预测所有测试样本的相同值

python - R 相当于 python "_"?