A lightweight custom CNN for binary classification of chest X-rays (Normal vs Pneumonia) with Grad-CAM explainability.
1import torch
2from huggingface_hub import hf_hub_download
3from pneumonia_classifier.ml.model.arch import Net
4
5# Download model
6model_path = hf_hub_download(
7 repo_id="24f2004275/pneumonia_classifier",
8 filename="pneumonia_classifier_cnn_uza7heywpgthvahb.pt"
9)
10
11# Load model
12model = Net()
13model.load_state_dict(torch.load(model_path, map_location="cpu", weights_only=False))
14model.eval()
15
16# Inference
17from torchvision import transforms
18
19transform = transforms.Compose([
20 transforms.Resize((224, 224)),
21 transforms.ToTensor(),
22 transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
23])
24
25# image = Image.open("chest_xray.jpg").convert("RGB")
26# tensor = transform(image).unsqueeze(0)
27# with torch.no_grad():
28# output = model(tensor)
29# probs = torch.exp(output)
30# prediction = "Pneumonia" if probs.argmax() == 1 else "Normal"
1@misc{pneumonia_classifier,
2 title={Pneumonia Detection from Chest X-Rays using Custom CNN with Grad-CAM},
3 author={Ayush Dubey},
4 year={2024},
5 url={https://huggingface.co/24f2004275/pneumonia_classifier}
6}