【发布时间】:2021-05-22 19:39:24
【问题描述】:
我正在尝试使用带有以下代码的 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。请改用 tf.GradientTape。
还尝试使用tf.GradientTape 引发另一个错误:
with tf.GradientTape() as gtape:
grads = gtape.gradient(loss, model.input)
AttributeError: 'KerasTensor' 对象没有属性 '_id'
尝试禁用急切执行也不起作用:
tf.compat.v1.disable_eager_execution()
因为它将渐变返回为无。 我将不胜感激有关解决此问题的任何方式的任何信息。 提前致谢。
【问题讨论】:
-
可能听起来很愚蠢,但请尝试在您的导入中用 tf.keras 替换所有 keras。然后通过 tf.GradientTape
标签: python tensorflow keras gradient