This repository was archived by the owner on Sep 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathmodel_utils.py
More file actions
63 lines (49 loc) · 1.49 KB
/
model_utils.py
File metadata and controls
63 lines (49 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import torch
import intel_extension_for_pytorch
from torchvision import transforms
from torchvision.datasets import ImageFolder
from torch.utils.data import DataLoader
from model import FireFinder
device = "xpu" if torch.xpu.is_available() else "cpu"
print(f"using device: {device}")
# Image transformations
transform = transforms.Compose(
[
transforms.Resize(224),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]
)
def save_model(model, path):
model.to("cpu")
torch.save(model.state_dict(), path)
def convert_save_torchscript(model, path):
model.to("cpu")
model = torch.jit.script(model)
model.save(path)
return model
def load_model(path):
model = FireFinder()
model.load_state_dict(torch.load(path))
model.eval()
return model
def load_torchscript_model(path):
model = torch.jit.load(path)
model.eval()
return model
def load_data(path):
dataset = ImageFolder(path, transform=transform)
dataloader = DataLoader(dataset, batch_size=64, shuffle=False)
return dataloader
def run_inference(model, dataloader):
results = []
model = model.eval()
model = model.to(device)
with torch.no_grad():
for inputs, _ in dataloader:
inputs = inputs.to(device)
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
results.extend(preds.tolist())
return results