Views
No views yet
south_ontario_bird_model.pth state dictionary file and the label_map.json file.1import torch
2import torch.nn as nn
3import torchvision.models as models
4import torchvision.transforms as transforms
5from PIL import Image
6import json
7
8# Define the model architecture (must match the trained model)
9def GetCleanModel(dropoutNum):
10 model_tuned = models.resnet50(weights=models.ResNet50_Weights.IMAGENET1K_V1)
11 num_ftrs_tuned = model_tuned.fc.in_features
12 model_tuned.fc = torch.nn.Sequential(
13 nn.Dropout(p=dropoutNum),
14 torch.nn.Linear(num_ftrs_tuned, 37) # 37 classes for bird families
15 )
16 return model_tuned
17
18# Load the saved model state dictionary
19model_save_path = 'south_ontario_bird_model.pth' # Path to your saved model file
20loaded_model = GetCleanModel(dropoutNum = 0.6) # Create a new model instance with the same architecture and dropout
21loaded_model.load_state_dict(torch.load(model_save_path))
22loaded_model.eval() # Set the model to evaluation mode
23
24# Load the label map
25label_map_save_path = 'label_map.json' # Path to your saved label map file
26with open(label_map_save_path, 'r') as f:
27 reverse_label_map = json.load(f)
28# Convert keys back to integers if they were saved as strings
29reverse_label_map = {int(k): v for k, v in reverse_label_map.items()}
30
31
32# Set device
33device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
34loaded_model.to(device)
35
36print("Model and label map loaded successfully.")1# Define the same transformations used for validation/testing
2inference_transforms = transforms.Compose([
3 transforms.Resize(256),
4 transforms.CenterCrop(224),
5 transforms.ToTensor(),
6 transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
7])
8
9# Example: Load and preprocess a new image
10new_image_path = 'path/to/your/new_bird_image.jpg' # Replace with the actual path to your new image
11
12try:
13 new_image = Image.open(new_image_path).convert('RGB') # Ensure image is RGB
14 input_tensor = inference_transforms(new_image).unsqueeze(0) # Add batch dimension
15 input_tensor = input_tensor.to(device)
16 print("Image preprocessed successfully.")
17
18except FileNotFoundError:
19 print(f"Error: New image not found at {new_image_path}")
20except Exception as e:
21 print(f"An error occurred during image preprocessing: {e}")1# Make a prediction
2if 'input_tensor' in locals(): # Check if input_tensor was created successfully
3 with torch.no_grad():
4 output = loaded_model(input_tensor)
5 _, predicted_class_index = torch.max(output, 1);
6
7 # Convert the predicted class index back to the bird family name
8 predicted_bird_family = reverse_label_map[predicted_class_index.item()]
9
10 print(f"The predicted bird family for the new image is: {predicted_bird_family}")