-
Notifications
You must be signed in to change notification settings - Fork 46
/
test_cifar10.py
executable file
·94 lines (72 loc) · 2.81 KB
/
test_cifar10.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/usr/bin/env python
"""Test a pretrained CNN for CIFAR10."""
__author__ = 'Yuan Xu, Erdene-Ochir Tuguldur'
import argparse
import time
from tqdm import *
import torch
from torch.autograd import Variable
from torch.utils.data import DataLoader
import torchvision
from torchvision.transforms import *
import torchnet
import models
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--dataset-root", type=str, default='./datasets', help='path of train dataset')
parser.add_argument("--test-batch-size", type=int, default=100, help='test batch size')
parser.add_argument("--dataload-workers-nums", type=int, default=2, help='number of workers for dataloader')
parser.add_argument("model", help='a pretrained neural network model')
args = parser.parse_args()
print("loading model...")
model = torch.load(args.model)
model.float()
use_gpu = torch.cuda.is_available()
print('use_gpu', use_gpu)
if use_gpu:
torch.backends.cudnn.benchmark = True
model.cuda()
to_tensor_and_normalize = Compose([
ToTensor(),
Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
test_dataset = torchvision.datasets.CIFAR10(root=args.dataset_root, train=False, download=True, transform=to_tensor_and_normalize)
test_dataloader = DataLoader(test_dataset, batch_size=args.test_batch_size, shuffle=False, num_workers=args.dataload_workers_nums)
CLASSES = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
criterion = torch.nn.CrossEntropyLoss()
def test():
model.eval() # Set model to evaluate mode
running_loss = 0.0
it = 0
correct = 0
total = 0
confusion_matrix = torchnet.meter.ConfusionMeter(len(CLASSES))
pbar = tqdm(test_dataloader, unit="images", unit_scale=test_dataloader.batch_size)
for batch in pbar:
inputs, targets = batch
inputs = Variable(inputs, volatile = True)
targets = Variable(targets, requires_grad=False)
if use_gpu:
inputs = inputs.cuda()
targets = targets.cuda(async=True)
# forward
outputs = model(inputs)
loss = criterion(outputs, targets)
# statistics
running_loss += loss.data[0]
it += 1
pred = outputs.data.max(1, keepdim=True)[1]
correct += pred.eq(targets.data.view_as(pred)).sum()
total += targets.size(0)
confusion_matrix.add(pred, targets.data)
# update the progress bar
pbar.set_postfix({
'loss': "%.05f" % (running_loss / it),
'acc': "%.02f%%" % (100*correct/total)
})
accuracy = correct/total
epoch_loss = running_loss / it
print("accuracy: %f%%, loss: %f" % (100*accuracy, epoch_loss))
print("confusion matrix:")
print(confusion_matrix.value())
print("testing...")
test()