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
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
Simply disable the eager-execution constrain form tf2 with the compat mode for tf1
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With