【发布时间】:2019-10-07 14:37:58
【问题描述】:
借助“旧”Keras 库,我使用 keras.backend.gradients() 函数为我的 CNN 创建了热图,如下所示:
# load model and image, then predict the class this image belongs to
model = load_model(os.path.join(model_folder, "custom_model.h5"))
image = image.load_img(image_path)
img_tensor = image.img_to_array(image)
img_tensor = np.expand_dims(img_tensor, axis=0)
img_tensor = preprocess_input(img_tensor)
preds = model.predict(img_tensor)
model_prediction = model.output[:, np.argmax(preds[0])]
# Calculate pooled grads for heatmap
conv_layer = model.get_layer("block5_conv3") # last conv. layer
grads = K.gradients(model_prediction, conv_layer.output)[0]
pooled_grads = K.mean(grads, axis=(0, 1, 2))
# Get values of pooled grads and model conv. layer output as Numpy arrays
input_layer = model.get_layer("model_input")
iterate = K.function([input_layer], [pooled_grads, conv_layer.output[0]])
pooled_grads_value, conv_layer_output_value = iterate([img_tensor])
# Continue with heatmap generation ...
现在我切换到 TF2.0,它是内置的 Keras 实现。一切正常,但是,使用该代码调用K.gradients() 时出现以下错误:
tf.gradients is not supported when eager execution is enabled. Use tf.GradientTape instead.
我做了一些研究并试图了解如何使用GradientTape,但不幸的是我对 TF 和 TF2.0 了解不多 - 我一直使用 Keras。你们能指导我如何通过我的设置使这个梯度计算再次起作用吗?
【问题讨论】:
-
这里有完整的GradCAM官方教程。 keras.io/examples/vision/grad_cam
标签: python tensorflow keras conv-neural-network tensorflow2.0