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)
# 目标框图和特征图融合的可视化
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)))