Ниже приведен код: (можно использовать прикрепленное изображение)
Код: Выделить всё
from transformers import AutoModelForImageClassification, AutoImageProcessor
from pytorch_grad_cam import GradCAM
from pytorch_grad_cam.utils.image import show_cam_on_image
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
import torch
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
# Load a pre-trained Swin Transformer model and processor
swin_model = AutoModelForImageClassification.from_pretrained('microsoft/swin-tiny-patch4-window7-224').eval()
swin_processor = AutoImageProcessor.from_pretrained('microsoft/swin-tiny-patch4-window7-224')
# Load an image and convert to RGB if needed
img_path = "/content/ILSVRC2012_test_00099929.JPEG" # Change to your image path
img = Image.open(img_path)
# Ensure the image is in RGB format
if img.mode != 'RGB':
img = img.convert('RGB')
# Preprocess the image for Swin
swin_input = swin_processor(images=img, return_tensors="pt")["pixel_values"]
# Set device to GPU if available, else CPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
swin_model = swin_model.to(device)
swin_input = swin_input.to(device)
# Perform forward pass and get logits
outputs = swin_model(swin_input)
logits = outputs.logits if hasattr(outputs, 'logits') else outputs # Correct extraction of logits
# Get the predicted class
pred_class = logits.argmax(dim=-1).item()
# Ensure model output is a tensor (logits)
print("Logits:", logits)
# Inspect the model to see available layers
print(swin_model)
# Choose the correct target layer from the last Swin stage
swin_target_layer = swin_model.swin.encoder.layers[-1].blocks[-1].layernorm_after # Target layer for Grad-CAM
# Function to visualize Grad-CAM on an image
def visualize_cam_on_image(model, target_layer, input_tensor, original_image):
# Initialize Grad-CAM
cam = GradCAM(model=model, target_layers=[target_layer])
# Set the target class for Grad-CAM visualization
targets = [ClassifierOutputTarget(pred_class)]
# Generate Grad-CAM heatmap
grayscale_cam = cam(input_tensor, targets=targets)[0] # For batch size 1, get the first result
# Convert the original input image to a NumPy array and normalize to [0, 1]
img_np = np.array(original_image) / 255.0 # Ensure it's in [0, 1] range
# Overlay the heatmap on the original image
visualization = show_cam_on_image(img_np, grayscale_cam, use_rgb=True)
# Display the result
plt.imshow(visualization)
plt.axis('off')
plt.show()
# Apply Grad-CAM on the Swin Transformer
visualize_cam_on_image(swin_model, swin_target_layer, swin_input, img)
Подробнее здесь: https://stackoverflow.com/questions/789 ... ransformer