本文介绍了启用急切执行时不支持 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.使用 tf.GradientTape 代替
I am unable to execute grads = K.gradients(loss, model.input)[0]
, it generates an error : tf.gradients is not supported when eager execution is enabled. Use tf.GradientTape instead
推荐答案
您有两个选项也可以解决此错误:
You have two options too resolve this error:
.gradients 在 TF2 中使用 - 按照此处的建议用 GradientTape 替换渐变 https://github.com/tensorflow/tensorflow/issues/33135
只需使用 tf1 的兼容模式禁用急切执行约束形式 tf2
Simply disable the eager-execution constrain form tf2 with the compat mode for tf1
解决方案 2 的示例运行代码:
Example running code for solution 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 代替的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!