Views
No views yet
transformers and torch libraries.1import torch
2from huggingface_hub import hf_hub_download
3from torchvision import transforms
4from PIL import Image
5import requests
6
7# Download the model weights from Hugging Face Hub
8model_path = hf_hub_download(repo_id="izeeek/resnet18_pneumonia_classifier", filename="resnet18_pneumonia_classifier.pth")
9
10# Load the model architecture (ResNet18)
11model = torch.hub.load('pytorch/vision:v0.10.0', 'resnet18', pretrained=False)
12
13# Adjust the final layer for binary classification (if necessary)
14model.fc = torch.nn.Linear(model.fc.in_features, 2)
15
16# Load the downloaded weights
17model.load_state_dict(torch.load(model_path))
18
19# Set the model to evaluation mode
20model.eval()
21
22# Image preprocessing
23transform = transforms.Compose([
24 transforms.Grayscale(num_output_channels=3),
25 transforms.Resize((224, 224)),
26 transforms.ToTensor(),
27 transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
28])
29
30# Sample Image (replace with your own image URL)
31url = 'https://storage.googleapis.com/kagglesdsdata/datasets/17810/23812/chest_xray/test/NORMAL/IM-0005-0001.jpeg?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=databundle-worker-v2%40kaggle-161607.iam.gserviceaccount.com%2F20240913%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20240913T014624Z&X-Goog-Expires=345600&X-Goog-SignedHeaders=host&X-Goog-Signature=1f6b37d181f12d083ffc951657e85fea087bb4e81ab955ec955dafcdae49c0d53ce20bc0be93605e2672b9bdd59e752eba9d5a3a0da2e3b3a03c888580b88d63d87611b4e4cec8b8802d53abd53fda165dd04765b8d9f30ddd4e908cd7a2a389ce8244fca7bfa36b3c9cff79d7c5e3f9ee7d59d5b9ef97a2e5c083997892ee3023302313fafff48ded58232db57d6affcfaee704eebba55f2b0abac40b14a38137275ad19cdb1b787930d134f7c30710e29c409bd765ca02e46851470a871cc697f614d464086373f43f5462f241eaf023cfd31e217d7b11e24e1ff34857deb200f5dc1a8c28c8115048ee840be8481f1bd79a2d8e2de1b30cb71420c007d32c'
32img = Image.open(requests.get(url, stream=True).raw)
33
34# Preprocess the image
35input_img = transform(img).unsqueeze(0)
36
37# Inference
38with torch.no_grad():
39 output = model(input_img)
40 _, predicted = torch.max(output, 1)
41
42# Labels for classification
43labels = {0: 'Pneumonia', 1: 'Normal'}
44print(f'Predicted label: {labels[predicted.item()]}')