Views
No views yet
torch, torchvision, and huggingface_hub.1import torch
2import torchvision.models as models
3from torchvision.models import EfficientNet_B0_Weights # Or the specific version used
4from PIL import Image
5from torchvision import transforms
6import json
7import requests
8from huggingface_hub import hf_hub_download
9import os
10
11# --- 1. Define Model Loading Function ---
12def load_model_from_hf(repo_id, model_filename="pytorch_model.bin", config_filename="config.json"):
13 """Loads model state_dict and config from Hugging Face Hub."""
14
15 # Download config file
16 config_path = hf_hub_download(repo_id=repo_id, filename=config_filename)
17 with open(config_path, 'r') as f:
18 config = json.load(f)
19
20 num_labels = config['num_labels']
21 id2label = config['id2label'] # Load label mapping
22
23 # Instantiate the correct architecture (EfficientNet-B0)
24 # Load architecture without pre-trained weights, as we'll load our fine-tuned ones
25 model = models.efficientnet_b0(weights=None)
26
27 # Modify the classifier head to match the number of classes used during training
28 num_ftrs = model.classifier[1].in_features
29 model.classifier[1] = torch.nn.Linear(num_ftrs, num_labels)
30
31 # Download model weights
32 model_path = hf_hub_download(repo_id=repo_id, filename=model_filename)
33
34 # Load the state dict
35 # Ensure map_location handles CPU/GPU as needed
36 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
37 state_dict = torch.load(model_path, map_location=device)
38 model.load_state_dict(state_dict)
39
40 model.eval() # Set to evaluation mode
41 print(f"Model loaded successfully from {repo_id} and set to evaluation mode.")
42 return model, config, id2label
43
44# --- 2. Define Preprocessing ---
45# Use the same transformations as validation during training
46IMG_SIZE = (224, 224) # Standard EfficientNet input size
47# ImageNet stats often used with EfficientNet pre-training
48mean=[0.485, 0.456, 0.406]
49std=[0.229, 0.224, 0.225]
50
51preprocess = transforms.Compose([
52 transforms.Resize(IMG_SIZE),
53 transforms.ToTensor(),
54 transforms.Normalize(mean=mean, std=std),
55])
56
57# --- 3. Load Model ---
58repo_id_to_load = "Bhumong/fruit-classifier-efficientnet-b0" # Your repo ID
59model, config, id2label = load_model_from_hf(repo_id_to_load)
60device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
61model.to(device)
62
63
64# --- 4. Prepare Input Image ---
65# Example: Load an image file (replace with your image path)
66image_path = "path/to/your/fruit_image.jpg" # <-- REPLACE WITH YOUR IMAGE PATH
67
68if not os.path.exists(image_path):
69 print(f"Warning: Image path not found: {image_path}")
70 print("Skipping prediction. Please provide a valid image path.")
71 input_batch = None
72else:
73 try:
74 img = Image.open(image_path).convert("RGB")
75 input_tensor = preprocess(img)
76 # Add batch dimension (model expects batches)
77 input_batch = input_tensor.unsqueeze(0)
78 input_batch = input_batch.to(device)
79 except Exception as e:
80 print(f"Error processing image {image_path}: {e}")
81 input_batch = None
82
83# --- 5. Make Prediction ---
84if input_batch is not None:
85 with torch.no_grad(): # Disable gradient calculations for inference
86 output = model(input_batch)
87 probabilities = torch.nn.functional.softmax(output[0], dim=0)
88 top_prob, top_catid = torch.max(probabilities, dim=0)
89
90 predicted_label_index = top_catid.item()
91 # Use the id2label mapping loaded from config
92 predicted_label = id2label.get(str(predicted_label_index), "Unknown Label")
93 confidence = top_prob.item()
94
95 print(f"\nPrediction for: {os.path.basename(image_path)}")
96 print(f"Predicted Label Index: {predicted_label_index}")
97 print(f"Predicted Label: {predicted_label}")
98 print(f"Confidence: {confidence:.4f}")
99
100