tf.gradients is not supported when eager execution is enabled. Use tf.GradientTape instead

Issue

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

Solution

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]

Answered By – T1Berger

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published