-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtest.py
More file actions
executable file
·163 lines (134 loc) · 5.74 KB
/
Copy pathtest.py
File metadata and controls
executable file
·163 lines (134 loc) · 5.74 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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import os
import sys
import copy
import numpy as np
import random
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from config import load_config
from data import partition_dataset, load_partition
from models import MeshNet2
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def test(model, device, test_loader, criterion):
print('Evaluating on ' + str(len(test_loader.dataset)) + ' meshes...')
model.eval()
running_loss = 0.0
running_corrects = 0.0
for collated_dict in test_loader:
ring_1 = torch.stack(collated_dict['ring_1']).to(device)
ring_2 = torch.stack(collated_dict['ring_2']).to(device)
ring_3 = torch.stack(collated_dict['ring_3']).to(device)
targets = torch.stack(collated_dict['target']).to(device)
meshes = collated_dict['meshes'].to(device)
#Check for empty meshes
if meshes.isempty():
raise ValueError("Meshes are empty.")
#Check valid meshes equal batch size
num_meshes = len(meshes.valid)
#Check number of faces equal num_faces
num_faces = meshes.num_faces_per_mesh().max().item()
# Each vertex is a point with x,y and z co-ordinates
verts = meshes.verts_padded()
# Normals for scaled vertices
normals = meshes.faces_normals_padded()
# Each face contains index of its corner vertex
faces = meshes.faces_padded()
if not torch.isfinite(verts).all():
raise ValueError("Mesh vertices contain nan or inf.")
if not torch.isfinite(normals).all():
raise ValueError("Mesh normals contain nan or inf.")
corners = verts[torch.arange(num_meshes)[:, None, None], faces.long()]
centers = torch.sum(corners, axis=2)/3
# Each mesh face has one center
assert centers.shape == (num_meshes, num_faces, 3)
# Each face only has 3 corners
assert corners.shape == (num_meshes, num_faces, 3, 3)
assert ring_1.shape == (num_meshes, num_faces, 3)
assert ring_2.shape == (num_meshes, num_faces, 6)
assert ring_3.shape == (num_meshes, num_faces, 12)
centers = centers.permute(0, 2, 1)
normals = normals.permute(0, 2, 1)
verts = Variable(verts)
faces = Variable(faces)
centers = Variable(centers)
normals = Variable(normals)
ring_1 = Variable(ring_1)
ring_2 = Variable(ring_2)
ring_3 = Variable(ring_3)
targets = Variable(targets.cuda())
with torch.no_grad():
outputs = model(verts=verts,
faces=faces,
centers=centers,
normals=normals,
ring_1=ring_1,
ring_2=ring_2,
ring_3=ring_3)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, targets)
running_loss += loss.item() * centers.size(0)
running_corrects += torch.sum(preds == targets.data)
test_loss = running_loss / len(test_loader.dataset)
test_acc = running_corrects / len(test_loader.dataset) * 100
print('Test loss: {:.1f}, Test Accuracy: {:.1f}'.format(test_loss, test_acc))
return test_acc
if __name__ == '__main__':
if len(sys.argv) <= 1 or len(sys.argv) > 3:
print('Use: python test.py <arch> <dataset> <section>')
print('<dataset> can be one of the following: ')
print('CUBES, SHREC11, FUTURE3D, ModelNet10, ModelNet40, MSB')
print('<section> should be used in case of SHREC11 or MSB datasets.')
print('For example:')
print('python test.py SHREC11 16-04_A')
print('python test.py ModelNet40')
exit(0)
elif len(sys.argv) == 2:
dataset = sys.argv[1]
section = ''
print('Dataset: ' + dataset)
cfg = load_config('config/{0}.yaml'.format(dataset))
cfg_dataset = cfg
elif len(sys.argv) == 3:
dataset = sys.argv[1]
section = sys.argv[2]
print('Dataset: ' + dataset + ', Section: ' + section)
cfg = load_config('config/{0}.yaml'.format(dataset))
cfg_dataset = cfg[section]
# Setup device
os.environ['CUDA_VISIBLE_DEVICES'] = cfg['cuda_devices']
device = torch.device("cuda:0")
# Load data
test_data = partition_dataset(dataset=dataset, section=section, partition='test', augment=False)
if len(test_data) != cfg_dataset['num_test']:
raise ValueError('Train/Test split incorrect. Check again!')
num_test = cfg_dataset['num_test']
print('#' * 60)
print('Number of meshes in test set: ' + str(num_test))
num_cls = cfg['num_cls']
print('Number of classes: ' + str(num_cls))
num_faces = cfg['num_faces']
print('Number of faces: ' + str(num_faces))
batch_size = cfg['batch_size']
print('Data loader batch size: ' + str(batch_size))
print('#' * 60)
test_loader = load_partition(partition_data=test_data, batch_size=batch_size)
#Load model, setup loss function, load pre-trained weights
model = MeshNet2(cfg=cfg, num_faces=num_faces, num_cls=num_cls, pool_rate=cfg['pool_rate'])
if torch.cuda.device_count() > 1:
model = nn.DataParallel(model)
model.to(device)
model.load_state_dict(torch.load(cfg_dataset['ckpt_root'] + '/MeshNet2_best.pkl'))
model.eval()
criterion = nn.CrossEntropyLoss()
print('#' * 60)
num_votes = 10
test_accs = []
for vote in range(1, num_votes + 1):
print('Vote {0} ...'.format(vote))
acc = test(model=model, device=device, test_loader=test_loader, criterion=criterion)
test_accs.append(float(acc))
best_acc = sorted(test_accs)[-1]
print('Best Accuracy: {:.1f}'.format(best_acc))