tensorflow2- Grad-CAM类激活可视化

Grad-CAM类激活可视化

如何获取图像分类模型的类激活热图。

import numpy as np
import tensorflow as tf
from tensorflow import keras

# Display
from IPython.display import Image, display
import matplotlib.pyplot as plt
import matplotlib.cm as cm

可配置参数

您可以将它们更改为其他模型。

要获取的值last_conv_layer_name用model.summary() 看到模型中所有层的名称。

model_builder = keras.applications.xception.Xception
img_size = (299, 299)
preprocess_input = keras.applications.xception.preprocess_input
decode_predictions = keras.applications.xception.decode_predictions

last_conv_layer_name = "block14_sepconv2_act"

# The local path to our target image
img_path = keras.utils.get_file(
    "african_elephant.jpg", "https://i.imgur.com/Bvro0YD.png"
)

display(Image(img_path))

在这里插入图片描述

Grad-CAM算法

def get_img_array(img_path, size):
    # `img` is a PIL image of size 299x299
    img = keras.preprocessing.image.load_img(img_path, target_size=size)
    # `array` is a float32 Numpy array of shape (299, 299, 3)
    array = keras.preprocessing.image.img_to_array(img)
    # We add a dimension to transform our array into a "batch"
    # of size (1, 299, 299, 3)
    array = np.expand_dims(array, axis=0)
    return array


def make_gradcam_heatmap(img_array, model, last_conv_layer_name, pred_index=None):
    # First, we create a model that maps the input image to the activations
    # of the last conv layer as well as the output predictions
    # 首先,我们创建一个模型,将输入图像映射到最后一个conv层的激活以及输出预测
    grad_model = tf.keras.models.Model(
        [model.inputs], [model.get_layer(last_conv_layer_name).output, model.output]
    )

    # Then, we compute the gradient of the top predicted class for our input image
    # with respect to the activations of the last conv layer
    #然后,我们为输入图像计算top预测类关于最后一个conv层的激活的梯度
    with tf.GradientTape() as tape:
        last_conv_layer_output, preds = grad_model(img_array)
        #如果没有传入pred_index,就计算pred[0]中最大的值对应的下标号index
        if pred_index is None:
            pred_index = tf.<
  • 10
    点赞
  • 68
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
### 回答1: Grad-CAM是一种用于可视化深度学习模型的技术,可以帮助我们理解模型的决策过程。TensorFlow是一种流行的深度学习框架,可以用于实现Grad-CAM技术。通过使用Grad-CAM,我们可以生成热力图,显示模型在决策过程中关注的区域,从而更好地理解模型的行为。 ### 回答2: Grad-CAM是一种利用梯度信息来生成激活图的技术,它能够解释卷积神经网络(CNN)对图像分的决策过程,从而令人更容易理解神经网络的工作流程。在TensorFlow中,我们可以使用Keras实现Grad-CAM可视化Grad-CAM利用反向传播算法计算出目标层特征图的梯度信息,将其加权求和作为激活图输出。通过将激活图叠加到原始图像上,我们可以直观地看到卷积神经网络在划分图像区域时的决策过程。 在TensorFlow中,我们可以使用Keras框架来构建卷积神经网络,并通过设置回调函数来实现Grad-CAM可视化。具体来说,我们需要定义一个GradCAM,包含了计算梯度信息和生成激活图的方法。然后在训练模型时,将GradCAM作为回调函数进行注册,即可在每个训练周期完成后获得激活图以及对应的原始图像。 使用Grad-CAM可视化有助于更好地理解卷积神经网络的决策过程,从而提高模型的可解释性以及调试效率。另外,Grad-CAM还可以用于优化模型设计,比如确定哪些特征对于分任务最为重要,以及如何更好地利用这些特征。总之,Grad-CAM是一项极具价值的技术,可以为卷积神经网络的研究和应用提供有力的支持。 ### 回答3: Grad-CAM (Gradient-weighted Class Activation Mapping) 是一种基于梯度的可视化技术,它可以帮助我们理解神经网络对于输入图像的预测结果的区域贡献程度,也就是通过可视化神经网络的“关注点”,让我们更好地理解神经网络的预测过程。 在 TensorFlow 中,我们可以使用 Keras 和 TensorFlow Hub 提供的预训练模型来实现 Grad-CAM 的可视化。首先,我们需要导入相应的模块: ```python import tensorflow as tf from tensorflow import keras import tensorflow_hub as hub import numpy as np import cv2 import matplotlib.pyplot as plt ``` 我们选择一个预训练的模型,例如 Inception-V3,然后加载模型并编译: ```python model = keras.Sequential([ hub.KerasLayer("https://tfhub.dev/google/imagenet/inception_v3/classification/4") ]) model.build([None, 299, 299, 3]) model.compile( optimizer=keras.optimizers.Adam(), loss=keras.losses.CategoricalCrossentropy(from_logits=True), metrics=['acc']) ``` 接下来,我们选择一张图片进行测试,例如一只猫的图片: ```python image_url = "https://i.imgur.com/denSx77.jpg" image_path = tf.keras.utils.get_file("image.jpg", image_url) image = cv2.imread(image_path) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = cv2.resize(image, (299, 299)) image = np.expand_dims(image, axis=0) ``` 然后,我们使用 Grad-CAM 对输入图片进行可视化: ```python grad_model = tf.keras.models.Model( [model.inputs], [model.get_layer("mixed7").output, model.output]) with tf.GradientTape() as tape: conv_output, predictions = grad_model(image) loss = predictions[:, np.argmax(predictions[0])] output = conv_output[0] grads = tape.gradient(loss, conv_output)[0] guided_grads = tf.cast(output > 0, "float32") * tf.cast(grads > 0, "float32") * grads weights = tf.reduce_mean(guided_grads, axis=(0, 1)) cam = np.ones(output.shape[0:2], dtype=np.float32) for i, w in enumerate(weights): cam += w * output[:, :, i] cam = cv2.resize(cam.numpy(), (299, 299)) cam = np.maximum(cam, 0) heatmap = cam / np.max(cam) plt.figure(figsize=(10, 10)) plt.imshow(image[0]) plt.imshow(heatmap, alpha=0.5, cmap='jet') plt.show() ``` 最后,我们就可以得到神经网络的可视化结果了。Grad-CAM 可以帮助我们确定网络中哪些位置对于特定别的预测是最重要的,这有助于我们更好地了解网络的行为,并确定哪些图像特征被网络更多地关注。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值