This repository has been archived by the owner on Nov 23, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
test.py
54 lines (46 loc) · 1.51 KB
/
test.py
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
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import torchvision.models as models
from torch.utils.data import DataLoader
import sys
import os
from tqdm import tqdm
@torch.no_grad()
def run_test(model, loader, device):
model.eval()
correct, total = 0, 0
for _, (inputs, targets) in enumerate(tqdm(loader)):
inputs, targets = inputs.to(device), targets.to(device)
outputs = model(inputs)
_, predicted = outputs.max(1)
total += targets.size(0)
correct += predicted.eq(targets).sum().item()
return (correct/total)
if __name__ == "__main__":
# pass arguments
assert 2 <= len(sys.argv) <= 3, "Not enough arguments"
assert os.path.exists(sys.argv[1]), "Path to load weights does not exist"
path = sys.argv[1]
gpu = sys.argv[2] if len(sys.argv) > 2 else 0
device = torch.device("cuda:" + str(gpu))
# data loaders
dataset_transforms = transforms.Compose([
transforms.Resize(224),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
dataset = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=dataset_transforms)
loader = DataLoader(dataset, batch_size = 128, shuffle = False,
num_workers = 16, pin_memory = True, generator = torch.Generator().manual_seed(42))
# define the model
model = models.resnet18()
model.fc = nn.Linear(512, 10)
# load the weights
model = torch.load(path)
model.to(device)
# check the accuracy
acc = run_test(model, loader, device)
print(f'Accuracy is {100*acc}')