如何在PyTorch上使用GradCAM進行神經網路分類依據視覺化?

dataclasses==0.8
dicom-factory==0.0.3
numpy==1.19.5
Pillow==8.1.1
torch==1.7.1
torchvision==0.8.2
typing-extensions==3.7.4.3
ttach
tqdm
# 正常安裝
pip install grad-cam
# aiForge
pip uninstall -y enum34
pip install grad-cam
pip install ttach
Resnet18 and 50: target_layer = model.layer4[-1]VGG and densenet161: target_layer = model.features[-1]mnasnet1_0: target_layer = model.layers[-1]ViT: target_layer = model.blocks[-1].norm1SwinT: target_layer = model.layers[-1].blocks[-1].norm1# 如果是Custom的網路架構,就必須另外寫。
# 例如
Transfer-Learning-Library的神經網路架構是自定義的,就要寫成:target_layer = model.backbone.layer4[-1]
$ nano /opt/conda/lib/python3.6/site-packages/pytorch_grad_cam/base_cam.py#修改前的
if target_category is None:
target_category = np.argmax(output.cpu().data.numpy(), axis=-1)
#修改後的
if target_category is None:
output = output[0]
target_category = np.argmax(output.cpu().data.numpy(), axis=-1)
1. Load your own model2. Define target_layer =, one of the layers in the model.

--

--

--

Machine Learning | Deep Learning | https://linktr.ee/yanwei

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Yanwei Liu

Yanwei Liu

Machine Learning | Deep Learning | https://linktr.ee/yanwei

More from Medium

Crowdsourcing — A Step Towards Advanced Deep Learning

A Quick note of EfficientNet

Simulation of X-ray Computed Tomography