egecandrsn commited on
Commit
6c1aaee
1 Parent(s): a852064

Create utils.py

Browse files
Files changed (1) hide show
  1. utils.py +31 -0
utils.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # utils.py
2
+ import torch
3
+ import json
4
+ from torchvision import transforms
5
+
6
+ with open('label_mapping.json', 'r') as json_file:
7
+ label_mapping = json.load(json_file)
8
+
9
+ def load_model(path):
10
+ model = torch.jit.load(path, map_location=torch.device("cpu"))
11
+ return model
12
+
13
+ def predict(model, image):
14
+ model.eval()
15
+
16
+ # Transform the image
17
+ transform = transforms.Compose([transforms.Resize((224, 224)), transforms.ToTensor()])
18
+
19
+ image = transform(image)
20
+
21
+ with torch.no_grad():
22
+ image = image.unsqueeze(0)
23
+ output = model(image)
24
+ probabilities = torch.nn.functional.softmax(output, dim=1)
25
+ _, predicted_class = torch.max(probabilities, 1)
26
+
27
+ # Convert predicted class index to label name using label_mapping
28
+ predicted_label = label_mapping[f"{predicted_class.item()}"]
29
+ probability= probabilities[0][predicted_class].item()
30
+
31
+ return predicted_label, round(probability, 2)