Update inference.py
Browse files- inference.py +55 -0
inference.py
CHANGED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torchvision.models as models
|
| 4 |
+
from PIL import Image
|
| 5 |
+
from torchvision import transforms
|
| 6 |
+
|
| 7 |
+
# Device setup
|
| 8 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 9 |
+
|
| 10 |
+
# Image transformations (same as the one used during training)
|
| 11 |
+
transform = transforms.Compose([
|
| 12 |
+
transforms.Resize((224, 224)),
|
| 13 |
+
transforms.ToTensor(),
|
| 14 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # ImageNet standard
|
| 15 |
+
])
|
| 16 |
+
|
| 17 |
+
# Load models (ResNet18 and MobileNetV2)
|
| 18 |
+
def load_models():
|
| 19 |
+
# Load ResNet18 model
|
| 20 |
+
resnet18 = models.resnet18(pretrained=False)
|
| 21 |
+
resnet18.fc = nn.Linear(resnet18.fc.in_features, 11) # Modify output layer for 11 classes
|
| 22 |
+
resnet18.load_state_dict(torch.load('models/resnet18_fish_classification_model.pth'))
|
| 23 |
+
resnet18.to(device)
|
| 24 |
+
|
| 25 |
+
# Load MobileNetV2 model
|
| 26 |
+
mobilenet_v2 = models.mobilenet_v2(pretrained=False)
|
| 27 |
+
mobilenet_v2.classifier[1] = nn.Linear(1280, 11) # Modify output layer for 11 classes
|
| 28 |
+
mobilenet_v2.load_state_dict(torch.load('models/mobilenetv2_fish_classification_model.pth'))
|
| 29 |
+
mobilenet_v2.to(device)
|
| 30 |
+
|
| 31 |
+
# Return models dictionary
|
| 32 |
+
models_dict = {
|
| 33 |
+
'ResNet18': resnet18,
|
| 34 |
+
'MobileNetV2': mobilenet_v2
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
return models_dict
|
| 38 |
+
|
| 39 |
+
# Image prediction function
|
| 40 |
+
def predict_image(image_path):
|
| 41 |
+
models_dict = load_models()
|
| 42 |
+
image = Image.open(image_path).convert('RGB')
|
| 43 |
+
image = transform(image).unsqueeze(0).to(device) # Add batch dimension and move to device
|
| 44 |
+
|
| 45 |
+
predictions = {}
|
| 46 |
+
for model_name, model in models_dict.items():
|
| 47 |
+
model.eval()
|
| 48 |
+
with torch.no_grad():
|
| 49 |
+
outputs = model(image)
|
| 50 |
+
probabilities = torch.nn.functional.softmax(outputs, dim=1)
|
| 51 |
+
_, predicted_class = torch.max(probabilities, 1)
|
| 52 |
+
confidence = probabilities[0, predicted_class].item()
|
| 53 |
+
predictions[model_name] = {'predicted_class': predicted_class.item(), 'confidence': confidence}
|
| 54 |
+
|
| 55 |
+
return predictions
|