Views
No views yet
1import torch
2import torchvision.models as models
3from torchvision import transforms
4from PIL import Image
5
6# Load model
7checkpoint = torch.load('model.pth')
8model = models.resnet18()
9model.fc = torch.nn.Linear(512, 7)
10model.load_state_dict(checkpoint['state_dict'])
11model.eval()
12
13# Preprocess image
14transform = transforms.Compose([
15 transforms.Resize(256),
16 transforms.CenterCrop(224),
17 transforms.ToTensor(),
18 transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
19])
20
21# Predict
22img = Image.open('maize_leaf.jpg').convert('RGB')
23img_tensor = transform(img).unsqueeze(0)
24
25with torch.no_grad():
26 output = model(img_tensor)
27 probabilities = torch.nn.functional.softmax(output[0], dim=0)
28 pred_class = output.argmax(1).item()
29
30print(f"Prediction: {checkpoint['class_names'][pred_class]}")
31print(f"Confidence: {probabilities[pred_class]:.2%}")