tensorflow 2.0的K.gradients的对应功能是什么?

时间:2019-06-27 05:20:12

标签: tensorflow keras tf.keras

我想用tensorflow2.0可视化分类结果。对于keras,它需要以下用于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]

但是当我使用tensorflow2.0时,似乎没有这样的梯度函数。那么,K.gradients的tensorflow2.0对应的函数是什么?

2 个答案:

答案 0 :(得分:0)

这里:

composer require spatie/laravel-searchable

您正在混合{strong>不兼容的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 keras软件包。您应该从tf.keras导入后端:

tf.keras

答案 1 :(得分:0)

我尝试禁用急切的执行方法,它似乎可以正常工作并且没有错误。但是我认为这不是最好的解决方案(很脏)。有更好的解决方案吗?

这是我的代码,没有错误:

import tensorflow as tf
import tensorflow.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, decodepredictions
import numpy as np
import cv2
import matplotlib.pyplot as plt
tf.compat.v1.disable_eager_execution()

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)
african_elephant_output = model.output[:, 386]
last_conv_layer = model.get_layer('block5_conv3')
preds = model.predict(x)
print('Predicted:', decode_predictions(preds, top=3)[0])
print np.argmax(preds[0])
grads = K.gradients(african_elephant_output, last_conv_layer.output)[0]