Yolov5中使用EigenCAM实现特征图可视乎

EigenCAM是一种用于提升卷积神经网络(CNN)模型解释性的方法,它可以应用于任何CNN模型,无需修改结构。通过层析分解,EigenCAM能突出显示影响分类决策的图像区域,提供对模型决策的理解,增强模型的透明度。文章还展示了如何结合YOLOv5进行目标检测,并使用Python库实现特征图的可视化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

EigenCAM介绍

是的,我了解EigenCAM,它是一种用于使卷积神经网络(CNN)模型更具解释性的方法。

EigenCAM的主要思想是:

  • 通过层析分解的方法找出输入图像在CNN中间层特征图中激活程度最高的区域。

  • 将中间层特征图中每个特征通道的激活作为输入图像不同区域的重要性权重。

  • 权重映射回输入图像,就可以高亮显示对CNN分类决策影响最大的图像区域。

相比普通的类别激活映射(CAM),EigenCAM具有以下优点:

  • 可以用于任意的CNN模型,无需修改模型结构。

  • 计算效率高,可以快速生成类激活映射。

  • 对模型Fine-tuning的依赖较小,更稳定可靠。

  • 高亮区域与目标类别相关性较强,解释性更好。

通过EigenCAM生成的类别关注区域,我们可以理解CNN为何输出某分类结果,提高模型透明度和可解释性。它是使复杂CNN模型对人类更可理解的有价值工具。

Yolov5版本

使用官方的YOLOv5,版本是v7.0
YOLOv5
在这里插入图片描述

使用已有的库实现

Advanced AI explainability for PyTorch

pip install grad-cam

多种可视化方法

代码

# 导入相关库
import warnings
warnings.filterwarnings('ignore')
warnings.simplefilter('ignore')
import torch    
import cv2
import numpy as np
import requests
import torchvision.transforms as transforms
from pytorch_grad_cam import EigenCAM, GradCAM
from pytorch_grad_cam.utils.image import show_cam_on_image, scale_cam_image
from PIL import Image
# 设置目标锚框的颜色
COLORS = np.random.uniform(0, 255, size=(80, 3))
# 取出模型预测的目标的值
def parse_detections(results):
    detections = results.pandas().xyxy[0]
    detections = detections.to_dict()
    boxes, colors, names = [], [], []

    for i in range(len(detections["xmin"])):
        confidence = detections["confidence"][i]
        if confidence < 0.2:
            continue
        xmin = int(detections["xmin"][i])
        ymin = int(detections["ymin"][i])
        xmax = int(detections["xmax"][i])
        ymax = int(detections["ymax"][i])
        name = detections["name"][i]
        category = int(detections["class"][i])
        color = COLORS[category]

        boxes.append((xmin, ymin, xmax, ymax))
        colors.append(color)
        names.append(name)
    return boxes, colors, names
# 绘制目标框
def draw_detections(boxes, colors, names, img):
    for box, color, name in zip(boxes, colors, names):
        xmin, ymin, xmax, ymax = box
        cv2.rectangle(
            img,
            (xmin, ymin),
            (xmax, ymax),
            color, 
            2)

        cv2.putText(img, name, (xmin, ymin - 5),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2,
                    lineType=cv2.LINE_AA)
    return img
# 读取图片
img = cv2.imread('xxx.jpg')
img = cv2.resize(img, (640, 640))
rgb_img = img.copy()
img = np.float32(img) / 255
transform = transforms.ToTensor()
tensor = transform(img).unsqueeze(0)

model.model.model.model[-2]表示的是模型P5检测头输出的特征图,[-5]是P4检测头的特征图,[-8]是P3浅层检测头的特征图,可以自己打印print(model)看模型结构,打印自己想要的特征图。

# ./yolov5表示你的yolov5代码的文件夹在哪里,custom表示模型是基于自己数据集训练的,path是你的模型的位置
model = torch.hub.load('./yolov5', 'custom', path='./best.pt', source='local')
model.eval()
model.cpu()
target_layers = [model.model.model.model[-2]] 
# 模型推理并绘制出图片
results = model([rgb_img])
boxes, colors, names = parse_detections(results)
detections = draw_detections(boxes, colors, names, rgb_img.copy())
Image.fromarray(detections)

在这里插入图片描述

# 绘制并展示特征图
cam = EigenCAM(model, target_layers, use_cuda=False)
grayscale_cam = cam(tensor)[0, :, :]
cam_image = show_cam_on_image(img, grayscale_cam, use_rgb=True)
Image.fromarray(cam_image)

注意要将图像通道转换一下再保存图片

copy = cam_image.copy()
copy = cv2.cvtColor(copy , cv2.COLOR_BGR2RGB)
cv2.imwrite("xxx.png", copy)

P2层的可视化

# 目标框图和特征图融合的可视化
def renormalize_cam_in_bounding_boxes(boxes, colors, names, image_float_np, grayscale_cam):
    renormalized_cam = np.zeros(grayscale_cam.shape, dtype=np.float32)
    for x1, y1, x2, y2 in boxes:
        renormalized_cam[y1:y2, x1:x2] = scale_cam_image(grayscale_cam[y1:y2, x1:x2].copy())    
    renormalized_cam = scale_cam_image(renormalized_cam)
    eigencam_image_renormalized = show_cam_on_image(image_float_np, renormalized_cam, use_rgb=True)
    image_with_bounding_boxes = draw_detections(boxes, colors, names, eigencam_image_renormalized)
    return image_with_bounding_boxes


renormalized_cam_image = renormalize_cam_in_bounding_boxes(boxes, colors, names, img, grayscale_cam)
Image.fromarray(renormalized_cam_image)
# 彩色图、目标框图、特征图可视化汇总
Image.fromarray(np.hstack((rgb_img, cam_image, renormalized_cam_image)))
### 关于Spring Cloud Alibaba Nacos Discovery的配置与使用 Nacos 是阿里巴巴开源的一个动态服务发现、配置管理和服务管理平台。`spring-cloud-starter-alibaba-nacos-discovery` 提供了基于 Spring Cloud 的集成支持,使得微服务可以轻松实现注册与发现功能。 #### Maven依赖引入 为了在项目中启用 `nacos-discovery` 功能,需在项目的 `pom.xml` 文件中添加如下依赖: ```xml <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> <version>2023.1.0</version> <!-- 版本号应根据实际需求调整 --> </dependency> ``` 上述代码片段展示了如何通过Maven构建工具来引入必要的starter包[^1]。 #### 配置文件设置 在应用的 `application.yml` 或者 `application.properties` 中进行相应的配置以连接到Nacos服务器并完成服务注册和发现操作。下面是一个典型的YAML格式配置实例: ```yaml spring: application: name: example-service # 定义服务名称 cloud: nacos: discovery: server-addr: localhost:8848 # 设置Nacos Server地址 namespace: public # 可选命名空间ID,默认为空字符串"" group: DEFAULT_GROUP # 组名,默认为DEFAULT_GROUP metadata: # 自定义元数据键值对 version: v1 # 示例版本信息 environment: dev # 运行环境标记(dev/test/prod等) ``` 此部分描述了基本的服务端口以及网络位置参数设定方式[^2]。 #### 启动类注解声明 为了让应用程序能够自动向Nacos注册自己作为一个可用的服务节点,在主启动类上加上特定的@Enable...系列注解即可激活该特性: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.alibaba.cloud.nacos.NacosDiscoveryProperties; @SpringBootApplication public class ExampleApplication { public static void main(String[] args) { SpringApplication.run(ExampleApplication.class, args); } } ``` 注意这里并没有显式调用任何额外的方法去手动触发注册过程;这是因为当检测到classpath下存在相关组件时,框架会替开发者处理好这一切逻辑细节[^3]。 另外如果希望进一步定制化行为比如修改默认心跳间隔时间,则可以通过重写某些bean定义或者直接扩展官方提供的接口类来达成目的。 ---
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值