Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 745
Muhammad Qasim Avatar asked Dec 31 '22 16:12

Muhammad Qasim


1 Answers

You have two options too resolve this error:

  1. .gradients is drepracted in TF2 - Replace gradients with GradientTape as suggested here https://github.com/tensorflow/tensorflow/issues/33135

  2. 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]
like image 124
T1Berger Avatar answered May 12 '23 16:05

T1Berger