code: def main():
      # 注意输入的图片必须是32的整数倍
      # 否则由于padding的原因会出现注意力飘逸的问题
      img_size = 224
      assert img_size % 32 == 0
  
      model = swin_base_patch4_window7_224()
      # https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_base_patch4_window7_224.pth
      weights_path = "./swin_base_patch4_window7_224.pth"
      model.load_state_dict(
          torch.load(weights_path, map_location="cpu")["model"],
          strict=False,
      )
  
      target_layers = [model.norm]
  
      data_transform = transforms.Compose(
          [
              transforms.ToTensor(),
              transforms.Normalize(
                  [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]
              ),
          ]
      )
      # load image
      img_path = "both.png"
      assert os.path.exists(
          img_path
      ), "file: '{}' dose not exist.".format(img_path)
      img = Image.open(img_path).convert("RGB")
      img = np.array(img, dtype=np.uint8)
      img = center_crop_img(img, img_size)
  
      # [C, H, W]
      img_tensor = data_transform(img)
      # expand batch dimension
      # [C, H, W] -> [N, C, H, W]
      input_tensor = torch.unsqueeze(img_tensor, dim=0)
  
      cam = GradCAM(
          model=model,
          target_layers=target_layers,
          use_cuda=False,
          reshape_transform=ResizeTransform(
              im_h=img_size, im_w=img_size
          ),
      )
      target_category = 281  # tabby, tabby cat
      # target_category = 254  # pug, pug-dog
  
      grayscale_cam = cam(
          input_tensor=input_tensor, target_category=target_category
      )
  
      grayscale_cam = grayscale_cam[0, :]
      visualization = show_cam_on_image(
          img / 255.0, grayscale_cam, use_rgb=True
      )
      plt.imshow(visualization)
      plt.show()
  
file_path: deep-learning-for-image-processing/pytorch_classification/grad_cam/main_swin.py
imports: import os
  import math
  import numpy
  import torch
  from PIL import Image
  import matplotlib.pyplot
  from torchvision import transforms
  from utils import GradCAM, show_cam_on_image, center_crop_img
  from swin_model import swin_base_patch4_window7_224
label_desc: Use image node_id 1 for calling a global function with example usage: main() without return types