-
Notifications
You must be signed in to change notification settings - Fork 11
/
test.py
84 lines (63 loc) · 1.95 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
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
import os
import torch.backends.cudnn as cudnn
import torch.utils.data
from torch.autograd import Variable
from torchvision import transforms
from torchvision import datasets
def test(epoch):
model_root = 'models'
image_root = os.path.join('dataset', 'mnist')
cuda = True
cudnn.benchmark = True
batch_size = 64
image_size = 32
# load data
img_transform = transforms.Compose([
transforms.Resize(image_size),
transforms.ToTensor()
])
dataset = datasets.MNIST(
root=image_root,
train=False,
transform=img_transform
)
data_loader = torch.utils.data.DataLoader(
dataset=dataset,
batch_size=batch_size,
shuffle=False,
num_workers=8
)
# test
my_net = torch.load(os.path.join(
model_root, 'svhn_mnist_model_epoch_' + str(epoch) + '.pth')
)
my_net = my_net.eval()
if cuda:
my_net = my_net.cuda()
len_dataloader = len(data_loader)
data_iter = iter(data_loader)
i = 0
n_total = 0
n_correct = 0
while i < len_dataloader:
data = data_iter.next()
img, label = data
batch_size = len(label)
input_img = torch.FloatTensor(batch_size, 1, image_size, image_size)
class_label = torch.LongTensor(batch_size)
if cuda:
img = img.cuda()
label = label.cuda()
input_img = input_img.cuda()
class_label = class_label.cuda()
input_img.resize_as_(img).copy_(img)
class_label.resize_as_(label).copy_(label)
inputv_img = Variable(input_img)
classv_label = Variable(class_label)
pred_label, _ = my_net(input_data=inputv_img)
pred = pred_label.data.max(1, keepdim=True)[1]
n_correct += pred.eq(classv_label.data.view_as(pred)).cpu().sum()
n_total += batch_size
i += 1
accu = n_correct * 1.0 / n_total
print 'epoch: %d, accuracy: %f' %(epoch, accu)