Home > Blockchain >  RuntimeError: tf.gradients is not supported when eager execution is enabled. Use tf.GradientTape ins
RuntimeError: tf.gradients is not supported when eager execution is enabled. Use tf.GradientTape ins

Time:05-21

Hi I was trying to reproduce results from this link Keras CNN Chexpert

and I encounter this error RuntimeError: tf.gradients is not supported when eager execution is enabled. Use tf.GradientTape instead when I was running this line of code

grads = K.gradients(class_output, last_conv_layer.output)[0] 

However when I change to this line of code

grads = tf.GradientTape(class_output, last_conv_layer.output)[0]

I get this error " ----> 2 grads = tf.GradientTape(class_output, last_conv_layer.output)[0] TypeError: 'GradientTape' object is not subscriptable".

Appreciate it if someone can guide me in correcting this.

below is a snippet of the codes

# get the first image of the testing dataset
x = test_generator[0][0]
preds = model.predict(x)

preds = y_pred_keras[1,:]
class_idx = np.argmax(preds)
class_output = model.output[:, class_idx]
#import the last convolutional layer of the model, this depends on the model
last_conv_layer = model.get_layer("conv5_block16_concat")

# grads = K.gradients(class_output, last_conv_layer.output)[0] 
grads = tf.GradientTape(class_output, last_conv_layer.output)[0]
pooled_grads = K.mean(grads, axis=(0, 1, 2))
iterate = K.function([model.input], [pooled_grads, last_conv_layer.output[0]])
pooled_grads_value, conv_layer_output_value = iterate([x])
for i in range(1024):
    conv_layer_output_value[:, :, i] *= pooled_grads_value[i]

CodePudding user response:

So I manage to find a guide to work around and implement the tensorflow v2 codes for the gradCAM, via these 2 links. Hope it helps anyone facing the same issue.

Pyimage GradCam

How to implement Grad-CAM on a trained network

  • Related