[英]tf.gradients is not supported when eager execution is enabled. Use tf.GradientTape instead
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]
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
我无法执行grads = K.gradients(loss, model.input)[0]
,它会生成错误: tf.gradients is not supported when eager execution is enabled. Use tf.GradientTape instead
tf.gradients is not supported when eager execution is enabled. Use tf.GradientTape instead
You have two options too resolve this error:您也有两个选项可以解决此错误:
.gradients is drepracted in TF2 - Replace gradients with GradientTape as suggested here https://github.com/tensorflow/tensorflow/issues/33135 .gradients 在 TF2 中使用 - 用 GradientTape 替换渐变,如此处的建议https://github.com/tensorflow/tensorflow/issues/33135
Simply disable the eager-execution constrain form tf2 with the compat mode for tf1只需使用 tf1 的兼容模式禁用急切执行约束形式 tf2
Example running code for solution 2:解决方案 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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.