Upload gradcam_fixed.py
Browse files- gradcam_fixed.py +138 -0
gradcam_fixed.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Thyroid Grad-CAM Visualization (Fixed for SwinV2)
|
| 3 |
+
"""
|
| 4 |
+
import os, sys, math, json, random, warnings, traceback
|
| 5 |
+
warnings.filterwarnings("ignore")
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
from PIL import Image
|
| 9 |
+
import matplotlib
|
| 10 |
+
matplotlib.use("Agg")
|
| 11 |
+
import matplotlib.pyplot as plt
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn.functional as F
|
| 15 |
+
from datasets import load_dataset
|
| 16 |
+
from transformers import AutoImageProcessor, AutoModelForImageClassification
|
| 17 |
+
|
| 18 |
+
HF_USERNAME = "Johnyquest7"
|
| 19 |
+
DATASET_NAME = "BTX24/thyroid-cancer-classification-ultrasound-dataset"
|
| 20 |
+
MODEL_NAME = f"{HF_USERNAME}/ML-Inter_thyroid"
|
| 21 |
+
OUTPUT_DIR = "./gradcam_outputs"
|
| 22 |
+
SEED = 42
|
| 23 |
+
BATCH_SIZE = 16
|
| 24 |
+
|
| 25 |
+
random.seed(SEED)
|
| 26 |
+
np.random.seed(SEED)
|
| 27 |
+
torch.manual_seed(SEED)
|
| 28 |
+
|
| 29 |
+
def main():
|
| 30 |
+
print("=" * 60)
|
| 31 |
+
print("Thyroid Grad-CAM Visualization")
|
| 32 |
+
print("=" * 60)
|
| 33 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 34 |
+
|
| 35 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 36 |
+
print(f"\nDevice: {device}")
|
| 37 |
+
processor = AutoImageProcessor.from_pretrained(MODEL_NAME)
|
| 38 |
+
model = AutoModelForImageClassification.from_pretrained(MODEL_NAME).to(device).eval()
|
| 39 |
+
id2label = model.config.id2label
|
| 40 |
+
|
| 41 |
+
ds = load_dataset(DATASET_NAME, split="train")
|
| 42 |
+
ds = ds.shuffle(seed=SEED)
|
| 43 |
+
train_test = ds.train_test_split(test_size=0.2, stratify_by_column="label", seed=SEED)
|
| 44 |
+
test_ds = train_test["test"]
|
| 45 |
+
print(f"Test samples: {len(test_ds)}")
|
| 46 |
+
|
| 47 |
+
# Get predictions first
|
| 48 |
+
all_logits, all_labels = [], []
|
| 49 |
+
for i in range(0, len(test_ds), BATCH_SIZE):
|
| 50 |
+
batch_items = [test_ds[j] for j in range(i, min(i+BATCH_SIZE, len(test_ds)))]
|
| 51 |
+
images = [item["image"].convert("RGB") for item in batch_items]
|
| 52 |
+
inputs = processor(images, return_tensors="pt")
|
| 53 |
+
with torch.no_grad():
|
| 54 |
+
outputs = model(pixel_values=inputs["pixel_values"].to(device))
|
| 55 |
+
all_logits.extend(outputs.logits.cpu().numpy())
|
| 56 |
+
all_labels.extend([item["label"] for item in batch_items])
|
| 57 |
+
|
| 58 |
+
y_true = np.array(all_labels)
|
| 59 |
+
y_pred = np.argmax(np.array(all_logits), axis=1)
|
| 60 |
+
|
| 61 |
+
correct_idx = [i for i in range(len(y_true)) if y_true[i] == y_pred[i]]
|
| 62 |
+
incorrect_idx = [i for i in range(len(y_true)) if y_true[i] != y_pred[i]]
|
| 63 |
+
random.shuffle(correct_idx)
|
| 64 |
+
random.shuffle(incorrect_idx)
|
| 65 |
+
selected = correct_idx[:5] + incorrect_idx[:5]
|
| 66 |
+
print(f"\nGenerating Grad-CAM for {len(selected)} samples ({len(correct_idx[:5])} correct, {len(incorrect_idx[:5])} incorrect)...")
|
| 67 |
+
|
| 68 |
+
# Register hooks on last stage
|
| 69 |
+
gradcam_data = {}
|
| 70 |
+
def fwd_hook(module, input, output):
|
| 71 |
+
gradcam_data["feat"] = output.detach()
|
| 72 |
+
def bwd_hook(module, grad_input, grad_output):
|
| 73 |
+
gradcam_data["grad"] = grad_output[0].detach()
|
| 74 |
+
|
| 75 |
+
target_layer = model.swinv2.encoder.layers[-1].blocks[-1].layernorm_after
|
| 76 |
+
fwd_handle = target_layer.register_forward_hook(fwd_hook)
|
| 77 |
+
bwd_handle = target_layer.register_full_backward_hook(bwd_hook)
|
| 78 |
+
|
| 79 |
+
for idx in selected:
|
| 80 |
+
try:
|
| 81 |
+
item = test_ds[idx]
|
| 82 |
+
img = item["image"].convert("RGB")
|
| 83 |
+
label = item["label"]
|
| 84 |
+
inputs = processor(img, return_tensors="pt")
|
| 85 |
+
img_tensor = inputs["pixel_values"].to(device).requires_grad_(True)
|
| 86 |
+
model.zero_grad()
|
| 87 |
+
outputs = model(pixel_values=img_tensor)
|
| 88 |
+
target_class = int(y_pred[idx])
|
| 89 |
+
score = outputs.logits[0, target_class]
|
| 90 |
+
score.backward()
|
| 91 |
+
|
| 92 |
+
feat = gradcam_data["feat"][0] # shape: [H*W, C]
|
| 93 |
+
grads = gradcam_data["grad"][0] # shape: [H*W, C]
|
| 94 |
+
|
| 95 |
+
# Compute Grad-CAM: weighted sum of channels
|
| 96 |
+
weights = grads.mean(dim=0, keepdim=True) # [1, C]
|
| 97 |
+
cam = torch.matmul(feat, weights.t()).squeeze() # [H*W]
|
| 98 |
+
|
| 99 |
+
# Reshape to spatial
|
| 100 |
+
H = W = int(math.sqrt(cam.shape[0]))
|
| 101 |
+
cam = cam.reshape(H, W) # [H, W]
|
| 102 |
+
|
| 103 |
+
# Normalize
|
| 104 |
+
cam = F.relu(cam)
|
| 105 |
+
cam = cam - cam.min()
|
| 106 |
+
cam = cam / (cam.max() + 1e-8)
|
| 107 |
+
|
| 108 |
+
# Upsample to 256x256
|
| 109 |
+
cam = cam.unsqueeze(0).unsqueeze(0) # [1, 1, H, W]
|
| 110 |
+
cam = F.interpolate(cam, size=(256, 256), mode="bilinear", align_corners=False)
|
| 111 |
+
cam = cam.squeeze().cpu().numpy()
|
| 112 |
+
|
| 113 |
+
# Get image for overlay
|
| 114 |
+
img_np = img_tensor.squeeze().detach().cpu().permute(1,2,0).numpy()
|
| 115 |
+
img_np = (img_np - img_np.min()) / (img_np.max() - img_np.min() + 1e-8)
|
| 116 |
+
|
| 117 |
+
plt.figure(figsize=(6,6))
|
| 118 |
+
plt.imshow(img_np)
|
| 119 |
+
plt.imshow(cam, cmap="jet", alpha=0.5)
|
| 120 |
+
pred_name = id2label.get(target_class, str(target_class))
|
| 121 |
+
true_name = id2label.get(label, str(label))
|
| 122 |
+
status = "CORRECT" if y_true[idx] == y_pred[idx] else "WRONG"
|
| 123 |
+
plt.title(f"{status}: Pred={pred_name} | True={true_name}")
|
| 124 |
+
plt.axis("off")
|
| 125 |
+
fname = f"{OUTPUT_DIR}/gradcam_{status}_sample{idx}_{pred_name}_vs_{true_name}.png"
|
| 126 |
+
plt.savefig(fname, bbox_inches="tight", dpi=150)
|
| 127 |
+
plt.close()
|
| 128 |
+
print(f" Saved {fname}")
|
| 129 |
+
except Exception as e:
|
| 130 |
+
print(f" Skipped sample {idx}: {e}")
|
| 131 |
+
traceback.print_exc()
|
| 132 |
+
|
| 133 |
+
fwd_handle.remove()
|
| 134 |
+
bwd_handle.remove()
|
| 135 |
+
print("\nGrad-CAM complete.")
|
| 136 |
+
|
| 137 |
+
if __name__ == "__main__":
|
| 138 |
+
main()
|