Views
No views yet
1import torch
2from torchvision import transforms
3from PIL import Image
4
5# Load model
6model = torch.load("best.pt", map_location="cpu")
7model.eval()
8
9# Class names
10CLASSES = [
11 "jollof_rice", "egusi_soup", "moi_moi", "akara", "suya", "efo_riro",
12 "okra_soup", "ofada_rice", "pounded_yam", "banga_soup", "pepper_soup",
13 "nkwobi", "amala", "ewedu_soup", "ogbono_soup", "yam_porridge",
14 "puff_puff", "chin_chin"
15]
16
17# Preprocessing (ImageNet-style)
18preprocess = transforms.Compose([
19 transforms.Resize(380),
20 transforms.CenterCrop(380),
21 transforms.ToTensor(),
22 transforms.Normalize(mean=[0.485, 0.456, 0.406],
23 std=[0.229, 0.224, 0.225]),
24])
25
26def predict(image_path, topk=5, device="cpu"):
27 img = Image.open(image_path).convert("RGB")
28 x = preprocess(img).unsqueeze(0)
29 x = x.to(device)
30 with torch.no_grad():
31 logits = model(x)
32 probs = logits.softmax(dim=1).squeeze(0)
33 topk_probs, topk_idx = probs.topk(topk)
34 return [(CLASSES[i], float(topk_probs[j])) for j, i in enumerate(topk_idx)]
35
36print(predict("examples/jollof.jpg"))1from torch import autocast
2
3device = torch.device("mps" if torch.backends.mps.is_available() else "cpu")
4model.to(device)
5
6def predict_fp16(image_path, topk=5):
7 img = Image.open(image_path).convert("RGB")
8 x = preprocess(img).unsqueeze(0).to(device)
9 with torch.no_grad(), autocast(device_type="mps", dtype=torch.float16):
10 logits = model(x)
11 probs = logits.softmax(dim=1).squeeze(0)
12 topk_probs, topk_idx = probs.topk(topk)
13 return [(CLASSES[i], float(topk_probs[j])) for j, i in enumerate(topk_idx)]examples/.