How to fix random seed to calculate gradient (gradient tape)?
[Environment]
OS: Windows 10
Tensorflow 2.6.0
[Issue]
I show GradCAM image like this sample code.
  
      

      keras.io
  

  
    

Keras documentation: Grad-CAM class activation visualization 1



  

  
    
    
  

  


It uses GradientTape to get gradient, and the result is different each time in spite of same source image and logit values of inference.
So heatmap image is different in each time with this issue.
I fixed random seed like below,  but I couldn’t fix random seed for gradient tape.

import os
import random
os.environ[‘TF_DETERMINISTIC_OPS’] = ‘1’
SEED = 42
random.seed(SEED)
np.random.seed(SEED)
tf.random.set_seed(SEED)
os.environ[“PYTHONHASHSEED”] = str(SEED)

Calc gradient and Get heatmap like below:

def make_gradcam_heatmap(img_array, model, last_conv_layer_name, pred_index=None):
with tf.GradientTape() as tape:
last_conv_layer_output, preds = grad_model(img_array)#this preds’ value is same in every time with fix random seed
if pred_index is None:
pred_index = tf.argmax(preds[0])
class_channel = preds[:, pred_index]
# This is the gradient of the output neuron (top predicted or chosen)
# with regard to the output feature map of the last conv layer
grads = tape.gradient(class_channel, last_conv_layer_output)