用keras来实现Grad-CAM

Grad-CAM是一种用于理解卷积神经网络(CNN)图像分类决策的可视化技术,通过显示图像中影响分类的区域。本文介绍了Grad-CAM的概念,其工作原理以及如何用keras进行实现,包括关键的梯度计算步骤,并提供了代码参考和资源链接。
摘要由CSDN通过智能技术生成
  • Grad-CAM是什么?
    英语的全称是Gradient-weighted Class Activation Mapping
    直接翻译是【梯度加权分类激活映射】
    简单说就是用CNN做图像分类的时候,到底是根据图像的哪里来判断属于这个分类的,给明确映射出来。
    如下图被分类为狗(拳师犬),CNN是根据哪里来判断是狗的呢?我们使用Grad-CAM可以看出是根据头部特征来判断的。 在这里插入图片描述

  • Grad-CAM的实现方法
    整体流程如下图,算法的主要的难点在于最后卷积层的梯度算出,也就是下图红框部分。
    梯度这个词数学基础不太扎实的同学可能已经忘记了。说说几个词
    【导数】指的是一元函数中,函数y=f(x)在某一点处沿x轴正方向的变化率;
    【偏导数】指的是多元函数中,函数y=f(x1,x2,…,xn)在某一点处沿某一坐标轴(x1,x2,…,xn)正方向的变化率。
    【方向导数】不止是坐标轴方向的变化率,坐标轴以外的其他方向的变化率
    【梯度】众多方向导数中最大的那个向量
    具体可以参考一下文章导数,偏导,方向倒数,梯度
    关于反向梯度的算出方法,可以参考我的另一篇文章 一步一步教你反向传播<

Grad-CAM是一种用于解释深度学习模型预测结果的方法,它可以帮助我们理解模型在做出决策时所关注的图像区域。以下是用Python编写的Grad-CAM代码: ```python import cv2 import numpy as np import tensorflow as tf from tensorflow.keras.preprocessing import image from tensorflow.keras.applications.vgg16 import VGG16 from tensorflow.keras.applications.vgg16 import preprocess_input from tensorflow.keras import backend as K def grad_cam(input_model, image, class_index): # 获取模型输入和输出张量 img_width, img_height = image.shape[1], image.shape[0] layer_name = input_model.layers[-1].name last_conv_layer = input_model.get_layer(layer_name) last_conv_layer_model = tf.keras.Model(inputs=input_model.inputs, outputs=last_conv_layer.output) classifier_input = tf.keras.Input(shape=last_conv_layer.output.shape[1:]) x = classifier_input preds = input_model.layers[-1](x) grad_model = tf.keras.Model(inputs=classifier_input, outputs=preds) # 计算梯度 with tf.GradientTape() as tape: last_conv_layer_output = last_conv_layer_model(image[np.newaxis, ...]) tape.watch(last_conv_layer_output) preds = grad_model(last_conv_layer_output) output = preds[:, class_index] grads = tape.gradient(output, last_conv_layer_output) pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2)) # 计算权重 heatmap = tf.reduce_mean(last_conv_layer_output, axis=-1) heatmap = tf.maximum(heatmap, 0) heatmap /= tf.reduce_max(heatmap) # 生成Grad-CAM图像 heatmap = tf.expand_dims(heatmap, axis=-1) heatmap = tf.image.resize(heatmap, (img_height, img_width)) heatmap = tf.cast(heatmap, dtype=tf.float32) heatmap = tf.reshape(heatmap, (1, img_height, img_width, 1)) image = tf.cast(image, dtype=tf.float32) heatmap = tf.image.resize(heatmap, (img_height, img_width)) cam = tf.multiply(heatmap, image) cam /= tf.reduce_max(cam) return cam.numpy()[0] # 加载预训练的VGG16模型 model = VGG16(weights='imagenet') # 加载图像 img_path = 'image.jpg' img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) # 获取Grad-CAM图像 cam = grad_cam(model, x, 0) # 选取第0类作为敏感特征 # 可视化Grad-CAM图像 cam = cv2.resize(cam, (img.shape[1], img.shape[0])) heatmap = cv2.applyColorMap(np.uint8(255 * cam), cv2.COLORMAP_JET) output_image = cv2.addWeighted(cv2.cvtColor(img.astype('uint8'), cv2.COLOR_RGB2BGR), 0.7, heatmap, 0.3, 0) cv2.imshow("Grad-CAM", output_image) cv2.waitKey(0) cv2.destroyAllWindows() ``` 以上代码中调用了VGG16模型作为示例,可以根据自己的需求替换为其他模型。这段代码会加载一张图像,提取出对应类别的Grad-CAM图像,并最终可视化出来。
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值