File size: 5,488 Bytes
242f0b3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 | """
EfficientNetB0 inference + Grad-CAM for PCOS ultrasound detection.
Mirrors the exact model architecture and preprocessing from the original notebook.
"""
import torch
import torch.nn as nn
import numpy as np
import cv2
from PIL import Image
from torchvision import models, transforms
IMG_SIZE = 224
DEVICE = torch.device("cpu") # HF Spaces free tier is CPU
PREPROCESS = transforms.Compose([
transforms.Resize((IMG_SIZE, IMG_SIZE)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std =[0.229, 0.224, 0.225]),
])
RISK_THRESHOLDS = {
"Low" : (0.00, 0.33),
"Moderate" : (0.33, 0.66),
"High" : (0.66, 1.00),
}
RECOMMENDATIONS = {
"Low" : "Low PCOS probability. Routine monitoring recommended. Repeat scan if symptoms develop.",
"Moderate" : "Moderate PCOS probability. Clinical evaluation recommended. Consider hormonal panel (FSH, LH, AMH).",
"High" : "High PCOS probability. Urgent clinical review recommended. Comprehensive hormonal workup advised.",
}
def build_model():
"""Build EfficientNetB0 with same head as training."""
model = models.efficientnet_b0(weights=None)
in_features = model.classifier[1].in_features
model.classifier[1] = nn.Linear(in_features, 2)
return model
def load_image_model(model_path: str):
"""Load trained EfficientNetB0 weights."""
model = build_model()
checkpoint = torch.load(model_path, map_location=DEVICE, weights_only=False)
# Handle both raw state_dict and checkpoint dict
if isinstance(checkpoint, dict) and "model_state" in checkpoint:
model.load_state_dict(checkpoint["model_state"])
else:
model.load_state_dict(checkpoint)
model.eval()
return model.to(DEVICE)
def predict_image(model, pil_image: Image.Image) -> dict:
"""
Run inference on a PIL image.
Returns prob_pcos, prob_not_pcos, risk_category, recommendation.
"""
tensor = PREPROCESS(pil_image.convert("RGB")).unsqueeze(0).to(DEVICE)
with torch.no_grad():
out = model(tensor)
probs = torch.softmax(out, dim=1)[0]
prob_not_pcos = round(probs[0].item(), 4)
prob_pcos = round(probs[1].item(), 4)
risk_score = round(prob_pcos * 100, 1)
category = "Low"
for cat, (lo, hi) in RISK_THRESHOLDS.items():
if lo <= prob_pcos < hi:
category = cat
break
if prob_pcos >= 0.66:
category = "High"
return {
"prob_pcos" : prob_pcos,
"prob_not_pcos" : prob_not_pcos,
"risk_score" : risk_score,
"risk_category" : category,
"recommendation": RECOMMENDATIONS[category],
"pred_label" : "PCOS" if prob_pcos >= 0.5 else "Not PCOS",
}
# =============================================================================
# GRAD-CAM
# =============================================================================
class GradCAM:
"""Grad-CAM implementation identical to original notebook."""
def __init__(self, model, target_layer):
self.model = model
self.gradients = None
self.activations = None
self._fh = target_layer.register_forward_hook(self._save_activation)
self._bh = target_layer.register_full_backward_hook(self._save_gradient)
def _save_activation(self, module, inp, output):
self.activations = output.detach()
def _save_gradient(self, module, grad_input, grad_output):
self.gradients = grad_output[0].detach()
def generate(self, tensor, class_idx=None):
"""Generate Grad-CAM heatmap. class_idx=None → uses predicted class."""
self.model.zero_grad()
out = self.model(tensor)
if class_idx is None:
class_idx = out.argmax(dim=1).item()
out[0, class_idx].backward()
grads = self.gradients[0] # (C, H, W)
acts = self.activations[0] # (C, H, W)
weights = grads.mean(dim=(1, 2)) # (C,)
cam = torch.zeros(acts.shape[1:])
for i, w in enumerate(weights):
cam += w * acts[i]
cam = torch.relu(cam).numpy()
cam -= cam.min()
if cam.max() > 0:
cam /= cam.max()
return cam
def remove(self):
self._fh.remove()
self._bh.remove()
def get_target_layer(model):
"""Return the last conv block of EfficientNetB0 for Grad-CAM."""
return model.features[-1]
def generate_gradcam_overlay(model, pil_image: Image.Image,
class_idx: int = 1) -> np.ndarray:
"""
Returns an RGB numpy array of the Grad-CAM overlay (same size as input).
class_idx=1 → PCOS class heatmap.
"""
img_rgb = np.array(pil_image.convert("RGB").resize((IMG_SIZE, IMG_SIZE)))
tensor = PREPROCESS(pil_image.convert("RGB")).unsqueeze(0).to(DEVICE)
tensor.requires_grad_(True)
target_layer = get_target_layer(model)
gcam = GradCAM(model, target_layer)
cam = gcam.generate(tensor, class_idx=class_idx)
gcam.remove()
# Resize CAM to image size
cam_resized = cv2.resize(cam, (IMG_SIZE, IMG_SIZE))
heatmap = cv2.applyColorMap(
np.uint8(255 * cam_resized), cv2.COLORMAP_JET)
heatmap_rgb = cv2.cvtColor(heatmap, cv2.COLOR_BGR2RGB)
# Overlay: 50% original + 50% heatmap
overlay = (0.5 * img_rgb + 0.5 * heatmap_rgb).astype(np.uint8)
return overlay, heatmap_rgb
|