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 (ViT)
8class VitModel(nn.Module):
9 def __init__(self, num_classes=5, dropout_rate=0.0):
10 super().__init__()
11 # Load ViT-B/16 architecture
12 self.backbone = models.vit_b_16(weights=None) # No need for weights when loading custom state_dict
13
14 # Modify the head to match the training configuration
15 input_dim = self.backbone.heads[0].in_features
16 self.backbone.heads = nn.Sequential(
17 nn.Linear(input_dim, 512),
18 nn.LayerNorm(512),
19 nn.GELU(),
20 nn.Dropout(dropout_rate),
21 nn.Linear(512, num_classes)
22 )
23
24 def forward(self, x):
25 return self.backbone(x)
26
27# 2. Configuration
28DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
29# Replace with your actual Repo ID
30REPO_ID = "Suphawit/skin-disease-vit-optuna"
31FILENAME = "final_best_skin_diseases_model.pth"
32
33# 3. Load Model
34model_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME)
35model = VitModel(num_classes=5)
36model.load_state_dict(torch.load(model_path, map_location=DEVICE))
37model.to(DEVICE)
38model.eval()
39
40# 4. Predict
41# Define Transform (Same as Validation)
42transform = transforms.Compose([
43 transforms.Resize((224, 224)),
44 transforms.ToTensor(),
45 transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
46])
47
48# Load Image
49img_path = "path_to_your_skin_image.jpg"
50img = Image.open(img_path).convert('RGB')
51input_tensor = transform(img).unsqueeze(0).to(DEVICE)
52
53# Inference
54with torch.no_grad():
55 output = model(input_tensor)
56 probs = torch.nn.functional.softmax(output, dim=1)
57 confidence, prediction = torch.max(probs, 1)
58
59 print(f"Predicted Class Index: {prediction.item()}")
60 print(f"Confidence: {confidence.item()*100:.2f}%")
61