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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Thyroid Ultrasound Evaluation + Grad-CAM (Pure PyTorch, no Trainer)
|
| 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 sklearn.metrics import accuracy_score, precision_recall_fscore_support, roc_auc_score, confusion_matrix
|
| 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 = "./eval_outputs"
|
| 23 |
+
SEED = 42
|
| 24 |
+
BATCH_SIZE = 16
|
| 25 |
+
|
| 26 |
+
random.seed(SEED)
|
| 27 |
+
np.random.seed(SEED)
|
| 28 |
+
torch.manual_seed(SEED)
|
| 29 |
+
|
| 30 |
+
def main():
|
| 31 |
+
print("=" * 60)
|
| 32 |
+
print("Thyroid Ultrasound Evaluation + Grad-CAM")
|
| 33 |
+
print("=" * 60)
|
| 34 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 35 |
+
|
| 36 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 37 |
+
print(f"\nDevice: {device}")
|
| 38 |
+
print(f"Loading model: {MODEL_NAME}")
|
| 39 |
+
processor = AutoImageProcessor.from_pretrained(MODEL_NAME)
|
| 40 |
+
model = AutoModelForImageClassification.from_pretrained(MODEL_NAME).to(device).eval()
|
| 41 |
+
print(f"Model loaded: {sum(p.numel() for p in model.parameters())/1e6:.1f}M params")
|
| 42 |
+
|
| 43 |
+
print(f"\nLoading dataset: {DATASET_NAME}")
|
| 44 |
+
ds = load_dataset(DATASET_NAME, split="train")
|
| 45 |
+
ds = ds.shuffle(seed=SEED)
|
| 46 |
+
train_test = ds.train_test_split(test_size=0.2, stratify_by_column="label", seed=SEED)
|
| 47 |
+
test_ds = train_test["test"]
|
| 48 |
+
print(f"Test samples: {len(test_ds)} (Benign: {sum(1 for x in test_ds if x['label']==0)}, Malignant: {sum(1 for x in test_ds if x['label']==1)})")
|
| 49 |
+
|
| 50 |
+
id2label = model.config.id2label
|
| 51 |
+
|
| 52 |
+
# Simple inference loop
|
| 53 |
+
all_logits, all_labels = [], []
|
| 54 |
+
print("\nRunning inference...")
|
| 55 |
+
for i in range(0, len(test_ds), BATCH_SIZE):
|
| 56 |
+
batch_items = [test_ds[j] for j in range(i, min(i+BATCH_SIZE, len(test_ds)))]
|
| 57 |
+
images = [item["image"].convert("RGB") if item["image"].mode != "RGB" else item["image"] for item in batch_items]
|
| 58 |
+
inputs = processor(images, return_tensors="pt")
|
| 59 |
+
pixel_values = inputs["pixel_values"].to(device)
|
| 60 |
+
with torch.no_grad():
|
| 61 |
+
outputs = model(pixel_values=pixel_values)
|
| 62 |
+
all_logits.extend(outputs.logits.cpu().numpy())
|
| 63 |
+
all_labels.extend([item["label"] for item in batch_items])
|
| 64 |
+
if (i // BATCH_SIZE) % 5 == 0:
|
| 65 |
+
print(f" Batch {i//BATCH_SIZE + 1}/{(len(test_ds)+BATCH_SIZE-1)//BATCH_SIZE}")
|
| 66 |
+
|
| 67 |
+
y_true = np.array(all_labels)
|
| 68 |
+
y_logits = np.array(all_logits)
|
| 69 |
+
y_pred = np.argmax(y_logits, axis=1)
|
| 70 |
+
probs = F.softmax(torch.from_numpy(y_logits), dim=1).numpy()
|
| 71 |
+
|
| 72 |
+
acc = accuracy_score(y_true, y_pred)
|
| 73 |
+
prec, rec, f1, _ = precision_recall_fscore_support(y_true, y_pred, average="weighted", zero_division=0)
|
| 74 |
+
try:
|
| 75 |
+
auc = roc_auc_score(y_true, probs[:, 1])
|
| 76 |
+
except Exception:
|
| 77 |
+
auc = roc_auc_score(y_true, probs[:, 0])
|
| 78 |
+
cm = confusion_matrix(y_true, y_pred)
|
| 79 |
+
sens = cm[1,1] / (cm[1,1] + cm[1,0]) if (cm[1,1] + cm[1,0]) > 0 else 0
|
| 80 |
+
spec = cm[0,0] / (cm[0,0] + cm[0,1]) if (cm[0,0] + cm[0,1]) > 0 else 0
|
| 81 |
+
|
| 82 |
+
final = {
|
| 83 |
+
"test_accuracy": float(acc),
|
| 84 |
+
"test_weighted_f1": float(f1),
|
| 85 |
+
"test_weighted_precision": float(prec),
|
| 86 |
+
"test_weighted_recall": float(rec),
|
| 87 |
+
"test_roc_auc": float(auc),
|
| 88 |
+
"test_sensitivity": float(sens),
|
| 89 |
+
"test_specificity": float(spec),
|
| 90 |
+
"test_confusion_matrix": cm.tolist(),
|
| 91 |
+
}
|
| 92 |
+
print(f"\n{'='*60}")
|
| 93 |
+
print("FINAL TEST METRICS")
|
| 94 |
+
print(f"{'='*60}")
|
| 95 |
+
for k, v in final.items():
|
| 96 |
+
print(f" {k}: {v}")
|
| 97 |
+
with open(f"{OUTPUT_DIR}/test_metrics.json", "w") as f:
|
| 98 |
+
json.dump(final, f, indent=2)
|
| 99 |
+
print(f"\nSaved to {OUTPUT_DIR}/test_metrics.json")
|
| 100 |
+
|
| 101 |
+
# Grad-CAM
|
| 102 |
+
correct_idx = [i for i in range(len(y_true)) if y_true[i] == y_pred[i]]
|
| 103 |
+
incorrect_idx = [i for i in range(len(y_true)) if y_true[i] != y_pred[i]]
|
| 104 |
+
random.shuffle(correct_idx)
|
| 105 |
+
random.shuffle(incorrect_idx)
|
| 106 |
+
selected = correct_idx[:5] + incorrect_idx[:5]
|
| 107 |
+
print(f"\nGenerating Grad-CAM for {len(selected)} samples ({len(correct_idx[:5])} correct, {len(incorrect_idx[:5])} incorrect)...")
|
| 108 |
+
|
| 109 |
+
gradcam_data = {}
|
| 110 |
+
def fwd_hook(module, input, output):
|
| 111 |
+
gradcam_data["feat"] = output.detach()
|
| 112 |
+
def bwd_hook(module, grad_input, grad_output):
|
| 113 |
+
gradcam_data["grad"] = grad_output[0].detach()
|
| 114 |
+
|
| 115 |
+
target_layer = model.swinv2.encoder.layers[-1].blocks[-1].layernorm_after
|
| 116 |
+
fwd_handle = target_layer.register_forward_hook(fwd_hook)
|
| 117 |
+
bwd_handle = target_layer.register_full_backward_hook(bwd_hook)
|
| 118 |
+
|
| 119 |
+
for idx in selected:
|
| 120 |
+
try:
|
| 121 |
+
item = test_ds[idx]
|
| 122 |
+
img = item["image"].convert("RGB")
|
| 123 |
+
label = item["label"]
|
| 124 |
+
inputs = processor(img, return_tensors="pt")
|
| 125 |
+
img_tensor = inputs["pixel_values"].to(device).requires_grad_(True)
|
| 126 |
+
model.zero_grad()
|
| 127 |
+
outputs = model(pixel_values=img_tensor)
|
| 128 |
+
target_class = int(y_pred[idx])
|
| 129 |
+
score = outputs.logits[0, target_class]
|
| 130 |
+
score.backward()
|
| 131 |
+
|
| 132 |
+
feat = gradcam_data["feat"][0]
|
| 133 |
+
grads = gradcam_data["grad"][0]
|
| 134 |
+
if feat.dim() == 3:
|
| 135 |
+
weights = grads.mean(dim=0, keepdim=True)
|
| 136 |
+
cam = torch.matmul(feat, weights.t()).squeeze()
|
| 137 |
+
H = W = int(math.sqrt(cam.shape[0]))
|
| 138 |
+
cam = cam.reshape(H, W)
|
| 139 |
+
else:
|
| 140 |
+
weights = grads.mean(dim=(0,1), keepdim=True)
|
| 141 |
+
cam = (feat * weights).sum(dim=-1).squeeze()
|
| 142 |
+
|
| 143 |
+
cam = F.relu(cam)
|
| 144 |
+
cam = cam - cam.min()
|
| 145 |
+
cam = cam / (cam.max() + 1e-8)
|
| 146 |
+
cam = F.interpolate(cam.unsqueeze(0).unsqueeze(0), size=(256,256), mode="bilinear", align_corners=False)
|
| 147 |
+
cam = cam.squeeze().cpu().numpy()
|
| 148 |
+
|
| 149 |
+
img_np = img_tensor.squeeze().detach().cpu().permute(1,2,0).numpy()
|
| 150 |
+
img_np = (img_np - img_np.min()) / (img_np.max() - img_np.min() + 1e-8)
|
| 151 |
+
plt.figure(figsize=(6,6))
|
| 152 |
+
plt.imshow(img_np)
|
| 153 |
+
plt.imshow(cam, cmap="jet", alpha=0.5)
|
| 154 |
+
pred_name = id2label.get(target_class, str(target_class))
|
| 155 |
+
true_name = id2label.get(label, str(label))
|
| 156 |
+
plt.title(f"Pred: {pred_name} | True: {true_name}")
|
| 157 |
+
plt.axis("off")
|
| 158 |
+
fname = f"{OUTPUT_DIR}/gradcam_sample_{idx}_pred{pred_name}_true{true_name}.png"
|
| 159 |
+
plt.savefig(fname, bbox_inches="tight", dpi=150)
|
| 160 |
+
plt.close()
|
| 161 |
+
print(f" Saved {fname}")
|
| 162 |
+
except Exception as e:
|
| 163 |
+
print(f" Skipped sample {idx}: {e}")
|
| 164 |
+
traceback.print_exc()
|
| 165 |
+
|
| 166 |
+
fwd_handle.remove()
|
| 167 |
+
bwd_handle.remove()
|
| 168 |
+
print("\nEvaluation complete.")
|
| 169 |
+
|
| 170 |
+
if __name__ == "__main__":
|
| 171 |
+
main()
|