启用急切执行时不支持tf.gradients。使用tf.GradientTape代替

from tensorflow.keras.applications import VGG16
from tensorflow.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]

我无法执行grads = K.gradients(loss, model.input)[0],它产生一个错误:tf.gradients is not supported when eager execution is enabled. Use tf.GradientTape instead

回答

您有两个选项也可以解决此错误:

  1. .gradients 在 TF2 中被 drepracted - 按照此处的建议用 GradientTape 替换梯度https://github.com/tensorflow/tensorflow/issues/33135

  2. 只需使用 tf1 的兼容模式禁用急切执行约束形式 tf2

解决方案 2 的示例运行代码:

from tensorflow.keras.applications import VGG16
from tensorflow.keras import backend as K
import tensorflow as tf
tf.compat.v1.disable_eager_execution()


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]


以上是启用急切执行时不支持tf.gradients。使用tf.GradientTape代替的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>