what is the corresponding function of K.gradients for tensorflow 2.0?

Viewed 1630

I want to visualize the classification result with tensorflow2.0. For keras, it need the following code for cam:

import tensorflow as tf
import keras.backend as K
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.vgg16 import preprocess_input, decodpredictions
import numpy as np
import cv2

img_path = 'image/test.jpg'

model = VGG16(weights='imagenet')
img = image.load_img('image/test.jpg', target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = model.predict(x)
print('Predicted:', decode_predictions(preds, top=3)[0])
print np.argmax(preds[0])
african_elephant_output = model.output[:, 386]
last_conv_layer = model.get_layer('block5_conv3')
grads = K.gradients(african_elephant_output, last_conv_layer.output)[0]

But when I use tensorflow2.0, it seem no such gradient function. So what is the corresponding function for K.gradients for tensorflow2.0?

1 Answers

Here:

import keras.backend as K
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.vgg16 import preprocess_input, decodpredictions

You are mixing the keras and tf.keras packages, which are NOT compatible with each other. You should import backend from tf.keras:

import tensorflow.keras.backend as K
Related