Classification
Sample inference script for exported torchscript image classifier
The following sample code should be run from the export directory:
sample_classifier.py
1
import torch
2
import numpy as np
3
from PIL import Image
4
import json
5
6
with open('class_mapping.json') as data:
7
mappings = json.load(data)
8
9
class_mapping = {item['model_idx']: item['class_name'] for item in mappings}
10
11
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
12
13
model = torch.jit.load('model.pt').to(device)
14
15
image_path = '/path/to/your/image'
16
image = Image.open(image_path)
17
# Transform your image according to the transforms.json as in
18
# https://help.hasty.ai/model-playground/image-transformations
19
image = np.array(image)
20
# Convert to torch tensor
21
x = torch.from_numpy(image).to(device)
22
with torch.no_grad():
23
# Convert to channels first, add batch dimension, convert to float datatype
24
x = x.permute(2, 0, 1).unsqueeze(dim=0).float()
25
y = model(x)
26
# if model is classifier:
27
y = y.argmax(dim=1).squeeze().item()
28
predicted_class = class_mapping[y]
29
print("Predicted class for image:", predicted_class)
Copied!
Copy link