Views
No views yet
1# Import libraries
2import torch
3import torch.nn as nn
4import torchvision.models as models
5from torchvision.transforms import v2
6from safetensors.torch import load_file
7from PIL import Image
8import json
9from huggingface_hub import hf_hub_download
10
11# Download my files
12hf_hub_download(
13 repo_id="Lumia101/Food101-EfficientNet-B0",
14 filename="config.json",
15 local_dir='.'
16)
17
18hf_hub_download(
19 repo_id="Lumia101/Food101-EfficientNet-B0",
20 filename="model.safetensors",
21 local_dir='.'
22)
23
24# Load classes
25with open("config.json") as f:
26 config = json.load(f)
27id2label = config["id2label"]
28
29# Make model
30model = models.efficientnet_b0(weights=None)
31model.classifier = nn.Sequential(
32 nn.Dropout(p=0.2, inplace=True),
33 nn.Linear(1280, 512),
34 nn.SiLU(),
35 nn.Dropout(0.2),
36 nn.Linear(512, 101)
37)
38
39# Load weights
40state_dict = load_file("model.safetensors")
41model.load_state_dict(state_dict)
42model.eval()
43
44# Transform it
45transform = v2.Compose([
46 v2.Resize(160),
47 v2.CenterCrop(128),
48 v2.ToImage(),
49 v2.ToDtype(torch.float32, scale=True),
50 v2.Normalize(
51 mean=(0.485, 0.456, 0.406),
52 std=(0.229, 0.224, 0.225),
53 ),
54])
55
56# Inference code
57def predict(image_path, top_k=5):
58 img = Image.open(image_path).convert("RGB")
59 tensor = transform(img).unsqueeze(0)
60
61 with torch.no_grad():
62 output = model(tensor)
63 probs = torch.softmax(output, dim=1)
64 top = torch.topk(probs, top_k)
65
66 return [(id2label[str(i.item())], round(p.item() * 100, 2))
67 for i, p in zip(top.indices[0], top.values[0])]
68
69# Classify it!
70results = predict("your_own_picture.png")
71for label, prob in results:
72 print(f"{label}: {prob}%")