-
Notifications
You must be signed in to change notification settings - Fork 3
/
evaluate.py
executable file
·178 lines (159 loc) · 6.61 KB
/
evaluate.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
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import argparse
import numpy as np
import pprint
from tqdm import tqdm
import torch
from torch.utils.data import Dataset, DataLoader
import sklearn.metrics as metrics
from dataset import ModelNet40, ModelNetC
from model import PCC
def eval(args):
device = torch.device('cuda')
test_loader = DataLoader(
ModelNet40(
data_root=args.modelnet_root,
partition='test',
num_points=args.num_points),
num_workers=8,
batch_size=args.test_batch_size,
shuffle=False,
drop_last=False)
model = PCC(voxel_size=args.voxel_size).to(device)
model.load_state_dict(torch.load(args.ckpt, map_location=device))
model.eval()
test_true, test_pred = [], []
with torch.no_grad():
for data, label in tqdm(test_loader):
data, label = data.to(device), label.to(device).squeeze()
data = data.permute(0, 2, 1)
batch_size = data.size()[0]
logits = model(data)
preds = logits.max(dim=1)[1]
test_true.append(label.cpu().numpy())
test_pred.append(preds.detach().cpu().numpy())
test_true = np.concatenate(test_true)
test_pred = np.concatenate(test_pred)
test_acc = metrics.accuracy_score(test_true, test_pred)
print('acc: ', test_acc)
def eval_corrupt_wrapper(model, fn_test_corrupt, args_test_corrupt):
"""
The wrapper helps to repeat the original testing function on all corrupted test sets.
It also helps to compute metrics.
:param model: model
:param fn_test_corrupt: original evaluation function, returns a dict of metrics, e.g., {'acc': 0.93}
:param args_test_corrupt: a dict of arguments to fn_test_corrupt, e.g., {'test_loader': loader}
:return:
"""
corruptions = [
'clean',
'scale',
'jitter',
'rotate',
'dropout_global',
'dropout_local',
'add_global',
'add_local',
]
DGCNN_OA = {
'clean': 0.926,
'scale': 0.906,
'jitter': 0.684,
'rotate': 0.785,
'dropout_global': 0.752,
'dropout_local': 0.793,
'add_global': 0.705,
'add_local': 0.725
}
OA_clean = None
perf_all = {'OA': [], 'CE': [], 'RCE': []}
for corruption_type in corruptions:
perf_corrupt = {'OA': []}
for level in range(5):
if corruption_type == 'clean':
split = "clean"
else:
split = corruption_type + '_' + str(level)
test_perf = fn_test_corrupt(split=split, model=model, **args_test_corrupt)
if not isinstance(test_perf, dict):
test_perf = {'acc': test_perf}
perf_corrupt['OA'].append(test_perf['acc'])
test_perf['corruption'] = corruption_type
if corruption_type != 'clean':
test_perf['level'] = level
pprint.pprint(test_perf, width=200)
if corruption_type == 'clean':
OA_clean = round(test_perf['acc'], 3)
break
for k in perf_corrupt:
perf_corrupt[k] = sum(perf_corrupt[k]) / len(perf_corrupt[k])
perf_corrupt[k] = round(perf_corrupt[k], 3)
if corruption_type != 'clean':
perf_corrupt['CE'] = (1 - perf_corrupt['OA']) / (1 - DGCNN_OA[corruption_type])
perf_corrupt['RCE'] = (OA_clean - perf_corrupt['OA']) / (DGCNN_OA['clean'] - DGCNN_OA[corruption_type])
for k in perf_all:
perf_corrupt[k] = round(perf_corrupt[k], 3)
perf_all[k].append(perf_corrupt[k])
perf_corrupt['corruption'] = corruption_type
perf_corrupt['level'] = 'Overall'
pprint.pprint(perf_corrupt, width=200)
for k in perf_all:
perf_all[k] = sum(perf_all[k]) / len(perf_all[k])
perf_all[k] = round(perf_all[k], 3)
perf_all['mCE'] = perf_all.pop('CE')
perf_all['RmCE'] = perf_all.pop('RCE')
perf_all['mOA'] = perf_all.pop('OA')
pprint.pprint(perf_all, width=200)
return perf_all
def eval_corrupt(args, model=None):
device = torch.device('cuda')
if model is None:
model = PCC(voxel_size=args.voxel_size).to(device)
model.load_state_dict(torch.load(args.ckpt, map_location=device))
model.eval()
def test_corrupt(args, split, model):
test_loader = DataLoader(
ModelNetC(data_root=args.modelnetc_root, split=split),
batch_size=args.test_batch_size,
shuffle=True,
drop_last=False
)
test_true = []
test_pred = []
with torch.no_grad():
for data, label in test_loader:
data, label = data.to(device), label.to(device).squeeze()
data = data.permute(0, 2, 1)
logits = model(data)
preds = logits.max(dim=1)[1]
test_true.append(label.cpu().numpy())
test_pred.append(preds.detach().cpu().numpy())
test_true = np.concatenate(test_true)
test_pred = np.concatenate(test_pred)
test_acc = metrics.accuracy_score(test_true, test_pred)
avg_per_class_acc = metrics.balanced_accuracy_score(test_true, test_pred)
return {'acc': test_acc, 'avg_per_class_acc': avg_per_class_acc}
perf_all = eval_corrupt_wrapper(model, test_corrupt, {'args': args})
return perf_all['mOA']
if __name__ == '__main__':
# Dataset settings
parser = argparse.ArgumentParser(description='Extra ModelNet-C Prediction')
parser.add_argument('--modelnet_root', type=str, default='/mnt/ssd1/lifa_rdata/cls/modelnet40_ply_hdf5_2048')
parser.add_argument('--modelnetc_root', type=str, default='/mnt/ssd1/lifa_rdata/PointCloud-C/modelnet_c')
parser.add_argument('--test_batch_size', type=int, default=32, metavar='batch_size',
help='Size of batch)')
parser.add_argument('--eval', action='store_true',
help='evaluate the model')
parser.add_argument('--eval_corrupt', action='store_true',
help='evaluate the model under corruption')
parser.add_argument('--num_points', type=int, default=1024,
help='num of points to use')
# Model settings
parser.add_argument('--voxel_size', type=float, default=0.05, help='down sample voxel size')
parser.add_argument('--ckpt', type=str, metavar='N', help='the trained checkpoint path')
args = parser.parse_args()
if args.eval and args.eval_corrupt:
raise ValueError('--eval and --eval_corrupt cannot be both specified')
if args.eval:
eval(args)
elif args.eval_corrupt:
eval_corrupt(args)