Skip to content

7.2.3章节的class activation map可视化方法代码问题 #33

Answered by clorisqiu1
clorisqiu1 asked this question in Q&A
Discussion options

You must be logged in to vote

from pytorch_grad_cam import GradCAM,ScoreCAM,GradCAMPlusPlus,AblationCAM,XGradCAM,EigenCAM,FullGrad
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
from pytorch_grad_cam.utils.image import show_cam_on_image

img_tensor = torch.Tensor(rgb_img) # 这里需要先把图像转换成tensor格式,上面PIL.Image读取的图片格式不能直接放入模型训练
print(img_tensor.shape) # 打印一下图片的shape是224×224×3,模型需要的是1×3×224×224形状
img_tensor = img_tensor.unsqueeze(0) # 这里先用unsequeeze将图片增加1维,变成1×224×224×3
img_tensor = img_tensor.permute(0, 3, 1, 2) # 用permute将图片shape调成 1×3×224×224形状
print(img_tensor.shape)

target_layers = [model.features[-1]] # 选取合适的类激活图,但是ScoreCAM和AblationCAM需要batch_size
cam = GradCAM(model=model,target_layers=target_l…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by ZhikangNiu
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
1 participant