Migrate legacy code with K.gradient to GradientTape with only the model output and layer output

I am migrating a legacy code which uses `DenseNet121` of a pretrained model and weights. I only have the model.output and output tensor of a layer. How do I migrate `K.gradients(y_c, spatial_map_layer)` to use gradient without the loss function?

Hi @khteh, To migrate your legacy code with only the model output and layer output , you can create the model and compute gradients within GradientTape following the approach used in the Grad-CAM example.

grad_model = keras.models.Model(
        model.inputs, [model.get_layer(last_conv_layer_name).output, model.output]
    )

    with tf.GradientTape() as tape:
        last_conv_layer_output, preds = grad_model(img_array)
        if pred_index is None:
            pred_index = tf.argmax(preds[0])
        class_channel = preds[:, pred_index]

    grads = tape.gradient(class_channel, last_conv_layer_output)

Kindly refer to the official Grad-CAM example documentation
Thank you!

Yes, this was resolved.