-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinference.py
More file actions
38 lines (30 loc) · 1.24 KB
/
inference.py
File metadata and controls
38 lines (30 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import torch
import torchvision.transforms as transforms
from data_model import ExampleDataset
from model import ExampleModel
from visualization import preprocess_image, visualize_predictions
data_dir = "./model_dataset/train"
model_path = "./model/animal_7.pth"
test_image_path = "model_dataset/test/bird/image_96.jpg"
image_size = (128, 128)
num_classes = 4
def predict(model, image_tensor, device):
with torch.no_grad():
image_tensor = image_tensor.to(device)
model = model.to(device)
outputs = model(image_tensor)
probabilities = torch.nn.functional.softmax(outputs, dim=1)
return probabilities.cpu().numpy().flatten()
transform = transforms.Compose([transforms.Resize(image_size), transforms.ToTensor()])
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
model = ExampleModel(num_classes=num_classes)
model.load_state_dict(torch.load(model_path, map_location=device))
model.to(device).eval()
dataset = ExampleDataset(data_dir)
# Inference
original_image, image_tensor = preprocess_image(test_image_path, transform)
probabilities = predict(model, image_tensor, device)
# Visualization
class_names = dataset.classes
visualize_predictions(original_image, probabilities, class_names)