AI工程常用技能2.使用Grad-Cam对yolov5模型进行热力图可视化
Grad-CAM(Class Activation Mapping-类别激活映射图)是非常常见的神经网络可视化的工具,用于探索模型的可解释性
grad-cam的计算,其实就是只需要两个值,一个是输出特征层,另一个是模型最后的某个类别对该特征层的梯度
类别激活映射图是一张图像,表示对预测输出的贡献分布,分数越高的地方表示原始图片对应区域对网络的响应越高、影响越大
论文:https://arxiv.org/abs/1610.02391
Grad-CAM: Visual Explanations from Deep Networks via Gradient-based
Localization
pip install grad-cam -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install --upgrade numpy==1.23.5 -i https://pypi.tuna.tsinghua.edu.cn/simple
# pip install grad-cam -i https://pypi.tuna.tsinghua.edu.cn/simple
import warnings
warnings.filterwarnings('ignore')
warnings.simplefilter('ignore')
import torch, yaml, cv2, os, shutil
import numpy as np
np.random.seed(0)
import matplotlib.pyplot as plt
from tqdm import trange
from PIL import Image
from models.yolo import Model
from utils.general import intersect_dicts
from utils.augmentations import letterbox
from utils.general import xywh2xyxy
from pytorch_grad_cam import GradCAMPlusPlus, GradCAM, XGradCAM
from pytorch_grad_cam.utils.image import show_cam_on_image
from pytorch_grad_cam.activations_and_gradients import ActivationsAndGradients
class yolov5_heatmap:
def __init__(self, weight, cfg, device, method, layer, backward_type, conf_threshold, genCAMNum):
device = torch.device(device)
ckpt = torch.load(weight)
model_names = ckpt['model'].names
csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
model = Model(cfg, ch=3, nc=len(model_names)).to(device)
csd =