Views
No views yet
huggingface_hub library or raw PyTorch.1import torch
2import torch.nn as nn
3from torchvision import transforms, models
4from PIL import Image
5from huggingface_hub import hf_hub_download
6
7# 1. Define Model Architecture (ResNet50)
8class AdvancedResNetClassifier(nn.Module):
9 def __init__(self, num_classes=4):
10 super(AdvancedResNetClassifier, self).__init__()
11 # Load ResNet50 architecture (weights=None because we load our own state_dict)
12 self.backbone = models.resnet50(weights=None)
13
14 # Modify the fully connected layer to match the training configuration
15 num_ftrs = self.backbone.fc.in_features
16 self.backbone.fc = nn.Sequential(
17 nn.Linear(num_ftrs, 512),
18 nn.ReLU(),
19 nn.Dropout(0.48),
20 nn.Linear(512, num_classes)
21 )
22
23 def forward(self, x):
24 return self.backbone(x)
25
26# 2. Configuration
27DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
28REPO_ID = "Suphawit/brain-tumor-resnet50-finetune-with-optuna"
29FILENAME = "model.pth"
30
31# 3. Load Model
32model_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME)
33model = AdvancedResNetClassifier(num_classes=4)
34model.load_state_dict(torch.load(model_path, map_location=DEVICE))
35model.to(DEVICE)
36model.eval()
37
38# 4. Predict
39# Define Transform
40transform = transforms.Compose([
41 transforms.Resize((224, 224)),
42 transforms.ToTensor(),
43 transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
44])
45
46# Load Image
47img_path = "path_to_your_mri_scan.jpg"
48img = Image.open(img_path).convert('RGB')
49input_tensor = transform(img).unsqueeze(0).to(DEVICE)
50
51# Inference
52with torch.no_grad():
53 output = model(input_tensor)
54 probs = torch.nn.functional.softmax(output, dim=1)
55 confidence, prediction = torch.max(probs, 1)
56
57 class_names = ['glioma', 'meningioma', 'notumor', 'pituitary']
58 predicted_class = class_names[prediction.item()]
59
60 print(f"Predicted Class: {predicted_class}")
61 print(f"Confidence: {confidence.item()*100:.2f}%")