• pytorch 神经网络特征可视化


    可参考博客

    Pytorch可视化模型任意中间层的类激活热力图(Grad-CAM)_潜行隐耀的博客-CSDN博客_pytorch热力图

    Pytorch输出网络中间层特征可视化_Joker-Tong的博客-CSDN博客_输出网络中间特征图

    GitHub - utkuozbulak/pytorch-cnn-visualizations: Pytorch implementation of convolutional neural network visualization techniques

    keras可视化中间层特征_joyce_peng的博客-CSDN博客_中间层特征可视化

    图像处理特征可视化方法总结(特征图、卷积核、类可视化CAM)

    神经网络之特征图可视化_AI bro的博客-CSDN博客_特征图的可视化

    PyTorch模型训练特征图可视化(TensorboardX) - 知乎

    PyTorch下的可视化工具 - 知乎 (zhihu.com)

     

    图像特征可视化方法总结

    (1)特征图可视化

            特征图可视化有两类方法,一类是直接将某一层的feature map映射到0-255的范围,变成图像。另一类是使用一个预训练的反卷积网络(反卷积、反池化)将feature map变成图像,从而达到可视化feature map的目的。

    (2)卷积核可视化

        卷积的过程就是特征提取的过程,每一个卷积核代表着一种特征。如果图像中某块区域与某个卷积核的结果越大,那么该区域就越“像”该卷积核。基于以上的推论,如果我们找到一张图像,能够使得这张图像对某个卷积核的输出最大,那么我们就说找到了该卷积核最感兴趣的图像。

    (3)类别激活可视化(Class Activation Mapping,CAM)

        CAM(Class Activation Mapping,类别激活映射图),亦称为类别热力图或显著性图。它的大小与原图一致,像素值表示原始图片的对应区域对预测输出的影响程度,值越大贡献越大。目前常用的CAM系列包括:CAM、Grad-CAM、Grad-CAM++。

    (4)注意力特征可视化

        与CAM类似,只不过每个特征图所占权重来自于注意力,而不是最后层的全连接,基于注意力的特征可视化方法近年有比较多的研究。

    (5)一些技术工具

        tensorflow框架提供了模型和特征可视化的工具tensorboard,可使用pytorch框架引入。

    tfrom torch.utils.tensorboard import SummaryWriter

    更多使用细节参考PyTorch模型训练特征图可视化(TensorboardX) - 知乎

    github代码

    GitHub - utkuozbulak/pytorch-cnn-visualizations: Pytorch implementation of convolutional neural network visualization techniques

    GitHub - ZhugeKongan/TorchCAM: CAM', 'ScoreCAM', 'SSCAM', 'ISCAM' 'GradCAM', 'GradCAMpp', 'SmoothGradCAMpp', 'XGradCAM', 'LayerCAM' using by PyTorch.

    下载包:

    1. # python >= 3.6
    2. # Stable release
    3. # You can install the last stable release of the package using pypi as follows:
    4. pip install torchcam
    5. # or using conda:
    6. conda install -c frgfm torchcam
    7. # Developer installation
    8. # Alternatively, if you wish to use the latest features of the project that haven't made their way to a release yet, you can install the package from source:
    9. git clone https://github.com/frgfm/torch-cam.git
    10. pip install -e torch-cam/.

    使用:

    1. # CAM
    2. # Learning Deep Features for Discriminative Localization: the original CAM paper
    3. # https://arxiv.org/abs/1512.04150
    4. from torchvision.models import resnet18
    5. from torchcam.cams import CAM
    6. model = resnet18(pretrained=True).eval()
    7. cam = CAM(model, 'layer4', 'fc')
    8. with torch.no_grad(): out = model(input_tensor)
    9. cam(class_idx=100)
    10. #Please note that by default, the layer at which the CAM is retrieved is set to the last non-reduced convolutional layer. If you wish to investigate a specific layer, use the target_layer argument in the constructor.
    11. # ScoreCAM
    12. # paper:Score-CAM:Score-Weighted Visual Explanations for Convolutional Neural Networks
    13. # https://arxiv.org/pdf/1910.01279.pdf
    14. from torchvision.models import resnet18
    15. from torchcam.cams import ScoreCAM
    16. model = resnet18(pretrained=True).eval()
    17. cam = ScoreCAM(model, 'layer4', 'fc')
    18. with torch.no_grad(): out = model(input_tensor)
    19. cam(class_idx=100)
    20. # SSCAM
    21. # paper:SS-CAM: Smoothed Score-CAM for Sharper Visual Feature Localization
    22. # https://arxiv.org/pdf/2006.14255.pdf
    23. from torchvision.models import resnet18
    24. from torchcam.cams import SSCAM
    25. model = resnet18(pretrained=True).eval()
    26. cam = SSCAM(model, 'layer4', 'fc')
    27. with torch.no_grad(): out = model(input_tensor)
    28. cam(class_idx=100)
    29. # ISCAM
    30. # paper:IS-CAM: Integrated Score-CAM for axiomatic-based explanations
    31. # https://arxiv.org/pdf/2010.03023.pdf
    32. from torchvision.models import resnet18
    33. from torchcam.cams import ISCAM
    34. model = resnet18(pretrained=True).eval()
    35. cam = ISCAM(model, 'layer4', 'fc')
    36. with torch.no_grad(): out = model(input_tensor)
    37. cam(class_idx=100)
    38. # GradCAM
    39. # paper:Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization
    40. # https://arxiv.org/pdf/1610.02391.pdf
    41. from torchvision.models import resnet18
    42. from torchcam.cams import GradCAM
    43. model = resnet18(pretrained=True).eval()
    44. cam = GradCAM(model, 'layer4')
    45. scores = model(input_tensor)
    46. cam(class_idx=100, scores=scores)
    47. # Grad-CAM++
    48. # paper:Grad-CAM++: Improved Visual Explanations for Deep Convolutional Networks
    49. # https://arxiv.org/pdf/1710.11063.pdf
    50. from torchvision.models import resnet18
    51. from torchcam.cams import GradCAMpp
    52. model = resnet18(pretrained=True).eval()
    53. cam = GradCAMpp(model, 'layer4')
    54. scores = model(input_tensor)
    55. cam(class_idx=100, scores=scores)
    56. # Smooth Grad-CAM++
    57. # paper:Smooth Grad-CAM++: An Enhanced Inference Level Visualization Technique for Deep Convolutional Neural Network Models
    58. # https://arxiv.org/pdf/1908.01224.pdf
    59. from torchvision.models import resnet18
    60. from torchcam.cams import SmoothGradCAMpp
    61. model = resnet18(pretrained=True).eval()
    62. cam = SmoothGradCAMpp(model, 'layer4')
    63. scores = model(input_tensor)
    64. cam(class_idx=100, scores=scores)
    65. # XGradCAM
    66. # paper:Axiom-based Grad-CAM: Towards Accurate Visualization and Explanation of CNNs
    67. # https://arxiv.org/pdf/2008.02312.pdf
    68. from torchvision.models import resnet18
    69. from torchcam.cams import XGradCAM
    70. model = resnet18(pretrained=True).eval()
    71. cam = XGradCAM(model, 'layer4')
    72. scores = model(input_tensor)
    73. cam(class_idx=100, scores=scores)
    74. # LayerCAM
    75. # paper:LayerCAM: Exploring Hierarchical Class Activation Maps for Localization
    76. # http://mmcheng.net/mftp/Papers/21TIP_LayerCAM.pdf
    77. from torchvision.models import resnet18
    78. from torchcam.cams import LayerCAM
    79. model = resnet18(pretrained=True).eval()
    80. cam = LayerCAM(model, 'layer4')
    81. scores = model(input_tensor)
    82. cam(class_idx=100, scores=scores)
    83. # Retrieving the class activation map
    84. # Once your CAM extractor is set, you only need to use your model to infer on your data as usual. If any additional information is required, the extractor will get it for you automatically.
    85. from torchvision.io.image import read_image
    86. from torchvision.transforms.functional import normalize, resize, to_pil_image
    87. from torchvision.models import resnet18
    88. from torchcam.cams import SmoothGradCAMpp
    89. model = resnet18(pretrained=True).eval()
    90. cam_extractor = SmoothGradCAMpp(model)
    91. # Get your input
    92. img = read_image("path/to/your/image.png")
    93. # Preprocess it for your chosen model
    94. input_tensor = normalize(resize(img, (224, 224)) / 255., [0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    95. # Preprocess your data and feed it to the model
    96. out = model(input_tensor.unsqueeze(0))
    97. # Retrieve the CAM by passing the class index and the model output
    98. activation_map = cam_extractor(out.squeeze(0).argmax().item(), out)
    99. # If you want to visualize your heatmap, you only need to cast the CAM to a numpy ndarray:
    100. import matplotlib.pyplot as plt
    101. # Visualize the raw CAM
    102. plt.imshow(activation_map.numpy()); plt.axis('off'); plt.tight_layout(); plt.show()
    103. # Or if you wish to overlay it on your input image:
    104. import matplotlib.pyplot as plt
    105. from torchcam.utils import overlay_mask
    106. # Resize the CAM and overlay it
    107. result = overlay_mask(to_pil_image(img), to_pil_image(activation_map, mode='F'), alpha=0.5)
    108. # Display it
    109. plt.imshow(result); plt.axis('off'); plt.tight_layout(); plt.show()

    可视化heatmap或者叠加原图:

    1. # Retrieving the class activation map
    2. # Once your CAM extractor is set, you only need to use your model to infer on your data as usual. If any additional information is required, the extractor will get it for you automatically.
    3. from torchvision.io.image import read_image
    4. from torchvision.transforms.functional import normalize, resize, to_pil_image
    5. from torchvision.models import resnet18
    6. from torchcam.cams import SmoothGradCAMpp
    7. model = resnet18(pretrained=True).eval()
    8. cam_extractor = SmoothGradCAMpp(model)
    9. # Get your input
    10. img = read_image("path/to/your/image.png")
    11. # Preprocess it for your chosen model
    12. input_tensor = normalize(resize(img, (224, 224)) / 255., [0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    13. # Preprocess your data and feed it to the model
    14. out = model(input_tensor.unsqueeze(0))
    15. # Retrieve the CAM by passing the class index and the model output
    16. activation_map = cam_extractor(out.squeeze(0).argmax().item(), out)
    17. # If you want to visualize your heatmap, you only need to cast the CAM to a numpy ndarray:
    18. import matplotlib.pyplot as plt
    19. # Visualize the raw CAM
    20. plt.imshow(activation_map.numpy()); plt.axis('off'); plt.tight_layout(); plt.show()
    21. # Or if you wish to overlay it on your input image:
    22. import matplotlib.pyplot as plt
    23. from torchcam.utils import overlay_mask
    24. # Resize the CAM and overlay it
    25. result = overlay_mask(to_pil_image(img), to_pil_image(activation_map, mode='F'), alpha=0.5)
    26. # Display it
    27. plt.imshow(result); plt.axis('off'); plt.tight_layout(); plt.show()

     CAM Zoo:

    This project is developed and maintained by the repo owner, but the implementation was based on the following research papers:

    • Learning Deep Features for Discriminative Localization: the original CAM paper
    • Grad-CAM: GradCAM paper, generalizing CAM to models without global average pooling.
    • Grad-CAM++: improvement of GradCAM++ for more accurate pixel-level contribution to the activation.
    • Smooth Grad-CAM++: SmoothGrad mechanism coupled with GradCAM.
    • Score-CAM: score-weighting of class activation for better interpretability.
    • SS-CAM: SmoothGrad mechanism coupled with Score-CAM.
    • IS-CAM: integration-based variant of Score-CAM.
    • XGrad-CAM: improved version of Grad-CAM in terms of sensitivity and conservation.
    • Layer-CAM: Grad-CAM alternative leveraging pixel-wise contribution of the gradient to the activation.
  • 相关阅读:
    Kubernetes - 一键安装部署 K8S(附:Kubernetes Dashboard)
    能源监测管理系统有哪些作用与效果?
    三台机器搭建redis集群过程及问题记录
    微信小程序开发教学系列(12)- 实战项目案例
    成电少年学fpga培训就业班怎么样
    SpringMvc请求原理流程
    数字化智慧公厕:开创城市数智化治理新时代
    InVEST模型在固碳、生境质量、产水等领域案例分析
    2021-2022 机器学习结语(李宏毅
    HTML学生个人网站作业设计——中华美食(HTML+CSS) 美食静态网页制作 WEB前端美食网站设计与实现
  • 原文地址:https://blog.csdn.net/m0_61899108/article/details/127340090