-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathpredict.py
More file actions
23 lines (18 loc) · 814 Bytes
/
predict.py
File metadata and controls
23 lines (18 loc) · 814 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import os
os.environ["TORCH_HOME"] = "."
import torch
from cog import BasePredictor, Input, Path
from PIL import Image
from torchvision import models
WEIGHTS = models.ResNet50_Weights.IMAGENET1K_V1
class Predictor(BasePredictor):
def setup(self):
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.model = models.resnet50(weights=WEIGHTS).to(self.device)
self.model.eval()
def predict(self, image: Path = Input(description="Image to classify")) -> dict:
img = Image.open(image).convert("RGB")
preds = self.model(WEIGHTS.transforms()(img).unsqueeze(0).to(self.device))
top3 = preds[0].softmax(0).topk(3)
categories = WEIGHTS.meta["categories"]
return {categories[i]: p.detach().item() for p, i in zip(*top3)}