Johnyquest7 commited on
Commit
532037a
·
verified ·
1 Parent(s): aad59b3

Upload gradcam_and_push.py

Browse files
Files changed (1) hide show
  1. gradcam_and_push.py +149 -0
gradcam_and_push.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generate Grad-CAM visualizations and push them to Hugging Face Hub.
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
+ from huggingface_hub import HfApi, login
18
+
19
+ HF_USERNAME = "Johnyquest7"
20
+ DATASET_NAME = "BTX24/thyroid-cancer-classification-ultrasound-dataset"
21
+ MODEL_NAME = f"{HF_USERNAME}/ML-Inter_thyroid"
22
+ OUTPUT_DIR = "./gradcam_outputs"
23
+ SEED = 42
24
+ BATCH_SIZE = 16
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 Generation + Hub Upload")
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
+ print(f"Model loaded: {sum(p.numel() for p in model.parameters())/1e6:.1f}M params")
41
+
42
+ ds = load_dataset(DATASET_NAME, split="train")
43
+ ds = ds.shuffle(seed=SEED)
44
+ train_test = ds.train_test_split(test_size=0.2, stratify_by_column="label", seed=SEED)
45
+ test_ds = train_test["test"]
46
+ print(f"Test samples: {len(test_ds)}")
47
+
48
+ # Get predictions
49
+ all_logits, all_labels = [], []
50
+ for i in range(0, len(test_ds), BATCH_SIZE):
51
+ batch_items = [test_ds[j] for j in range(i, min(i+BATCH_SIZE, len(test_ds)))]
52
+ images = [item["image"].convert("RGB") for item in batch_items]
53
+ inputs = processor(images, return_tensors="pt")
54
+ with torch.no_grad():
55
+ outputs = model(pixel_values=inputs["pixel_values"].to(device))
56
+ all_logits.extend(outputs.logits.cpu().numpy())
57
+ all_labels.extend([item["label"] for item in batch_items])
58
+
59
+ y_true = np.array(all_labels)
60
+ y_pred = np.argmax(np.array(all_logits), axis=1)
61
+
62
+ correct_idx = [i for i in range(len(y_true)) if y_true[i] == y_pred[i]]
63
+ incorrect_idx = [i for i in range(len(y_true)) if y_true[i] != y_pred[i]]
64
+ random.shuffle(correct_idx)
65
+ random.shuffle(incorrect_idx)
66
+ selected = correct_idx[:5] + incorrect_idx[:5]
67
+ print(f"\nGenerating Grad-CAM for {len(selected)} samples ({len(correct_idx[:5])} correct, {len(incorrect_idx[:5])} incorrect)...")
68
+
69
+ # Hooks
70
+ gradcam_data = {}
71
+ def fwd_hook(module, input, output):
72
+ gradcam_data["feat"] = output.detach()
73
+ def bwd_hook(module, grad_input, grad_output):
74
+ gradcam_data["grad"] = grad_output[0].detach()
75
+
76
+ target_layer = model.swinv2.encoder.layers[-1].blocks[-1].layernorm_after
77
+ fwd_handle = target_layer.register_forward_hook(fwd_hook)
78
+ bwd_handle = target_layer.register_full_backward_hook(bwd_hook)
79
+
80
+ uploaded_files = []
81
+ for idx in selected:
82
+ try:
83
+ item = test_ds[idx]
84
+ img = item["image"].convert("RGB")
85
+ label = item["label"]
86
+ inputs = processor(img, return_tensors="pt")
87
+ img_tensor = inputs["pixel_values"].to(device).requires_grad_(True)
88
+ model.zero_grad()
89
+ outputs = model(pixel_values=img_tensor)
90
+ target_class = int(y_pred[idx])
91
+ score = outputs.logits[0, target_class]
92
+ score.backward()
93
+
94
+ feat = gradcam_data["feat"][0]
95
+ grads = gradcam_data["grad"][0]
96
+ weights = grads.mean(dim=0, keepdim=True)
97
+ cam = torch.matmul(feat, weights.t()).squeeze()
98
+ H = W = int(math.sqrt(cam.shape[0]))
99
+ cam = cam.reshape(H, W)
100
+ cam = F.relu(cam)
101
+ cam = cam - cam.min()
102
+ cam = cam / (cam.max() + 1e-8)
103
+ cam = F.interpolate(cam.unsqueeze(0).unsqueeze(0), size=(256, 256), mode="bilinear", align_corners=False)
104
+ cam = cam.squeeze().cpu().numpy()
105
+
106
+ img_np = img_tensor.squeeze().detach().cpu().permute(1,2,0).numpy()
107
+ img_np = (img_np - img_np.min()) / (img_np.max() - img_np.min() + 1e-8)
108
+
109
+ plt.figure(figsize=(6,6))
110
+ plt.imshow(img_np)
111
+ plt.imshow(cam, cmap="jet", alpha=0.5)
112
+ pred_name = id2label.get(target_class, str(target_class))
113
+ true_name = id2label.get(label, str(label))
114
+ status = "CORRECT" if y_true[idx] == y_pred[idx] else "WRONG"
115
+ plt.title(f"{status}: Pred={pred_name} | True={true_name}")
116
+ plt.axis("off")
117
+ fname = f"gradcam_{status}_sample{idx}_{pred_name}_vs_{true_name}.png"
118
+ fpath = os.path.join(OUTPUT_DIR, fname)
119
+ plt.savefig(fpath, bbox_inches="tight", dpi=150)
120
+ plt.close()
121
+ print(f" Saved {fpath}")
122
+
123
+ # Upload to Hub
124
+ api = HfApi()
125
+ try:
126
+ api.upload_file(
127
+ path_or_fileobj=fpath,
128
+ path_in_file=f"gradcam/{fname}",
129
+ repo_id=f"{HF_USERNAME}/thyroid-training-scripts",
130
+ repo_type="model"
131
+ )
132
+ uploaded_files.append(f"gradcam/{fname}")
133
+ print(f" Uploaded to gradcam/{fname}")
134
+ except Exception as e:
135
+ print(f" Upload failed for {fname}: {e}")
136
+ except Exception as e:
137
+ print(f" Skipped sample {idx}: {e}")
138
+ traceback.print_exc()
139
+
140
+ fwd_handle.remove()
141
+ bwd_handle.remove()
142
+
143
+ print(f"\n{'='*60}")
144
+ print(f"Done. Uploaded {len(uploaded_files)} images to:")
145
+ for f in uploaded_files:
146
+ print(f" https://huggingface.co/{HF_USERNAME}/thyroid-training-scripts/tree/main/{f}")
147
+
148
+ if __name__ == "__main__":
149
+ main()