forked from stevenygd/PointFlow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
216 lines (182 loc) · 6.98 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
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
from datasets import get_datasets, synsetid_to_cate
from args import get_args
from pprint import pprint
from metrics.evaluation_metrics import EMD_CD
from metrics.evaluation_metrics import jsd_between_point_cloud_sets as JSD
from metrics.evaluation_metrics import compute_all_metrics
from collections import defaultdict
from models.networks import PointFlow
import os
import torch
import numpy as np
import torch.nn as nn
from normalization import normalize
def get_test_loader(args):
_, te_dataset = get_datasets(args)
if args.resume_dataset_mean is not None and args.resume_dataset_std is not None:
mean = np.load(args.resume_dataset_mean)
std = np.load(args.resume_dataset_std)
te_dataset.renormalize(mean, std)
loader = torch.utils.data.DataLoader(
dataset=te_dataset,
batch_size=args.batch_size,
shuffle=False,
num_workers=0,
pin_memory=True,
drop_last=False,
)
return loader
def evaluate_recon(model, args):
# TODO: make this memory efficient
if "all" in args.cates:
cates = list(synsetid_to_cate.values())
else:
cates = args.cates
all_results = {}
cate_to_len = {}
save_dir = os.path.dirname(args.resume_checkpoint)
for cate in cates:
args.cates = [cate]
loader = get_test_loader(args)
all_sample = []
all_ref = []
for data in loader:
idx_b, tr_pc, te_pc = data["idx"], data["train_points"], data["test_points"]
te_pc = te_pc.cuda() # if args.gpu is None else te_pc.cuda(args.gpu)
tr_pc = tr_pc.cuda() # if args.gpu is None else tr_pc.cuda(args.gpu)
B, N = te_pc.size(0), te_pc.size(1)
out_pc = model.reconstruct(tr_pc, num_points=N)
m, s = data["mean"].float(), data["std"].float()
m = m.cuda() if args.gpu is None else m.cuda(args.gpu)
s = s.cuda() if args.gpu is None else s.cuda(args.gpu)
out_pc = out_pc * s + m
te_pc = te_pc * s + m
all_sample.append(out_pc)
all_ref.append(te_pc)
sample_pcs = torch.cat(all_sample, dim=0)
ref_pcs = torch.cat(all_ref, dim=0)
# print("================NORMS======================")
# print(ref_pcs.shape)
# pprint(torch.mean(ref_pcs, axis=-2))
# refs = ref_pcs - torch.mean(ref_pcs, axis=-2).unsqueeze(1)
# ref_norms = refs.norm(dim=-1).max(dim=-1)[0]
# print(ref_norms)
# print("================+++++======================")
# print(sample_pcs.shape)
# pprint(torch.mean(sample_pcs, axis=-2))
# samp = sample_pcs - torch.mean(sample_pcs, axis=-2).unsqueeze(1)
# print(samp.norm(dim=-1).max(dim=-1)[0])
# print("================+++++======================")
cate_to_len[cate] = int(sample_pcs.size(0))
print(
"Cate=%s Total Sample size:%s Ref size: %s"
% (cate, sample_pcs.size(), ref_pcs.size())
)
# Save it
np.save(
os.path.join(save_dir, "%s_out_smp.npy" % cate),
sample_pcs.cpu().detach().numpy(),
)
np.save(
os.path.join(save_dir, "%s_out_ref.npy" % cate),
ref_pcs.cpu().detach().numpy(),
)
results = EMD_CD(
sample_pcs, ref_pcs, args.batch_size, reduced=True, accelerated_cd=True
)
# results = {
# k: (v.cpu().detach().item() if not isinstance(v, float) else v)
# for k, v in results.items()
# }
results = {
k: (v.cpu().detach() if not isinstance(v, float) else v)
for k, v in results.items()
}
pprint(results)
all_results[cate] = results
# torch.save(results["MMD-EMD"], "emd.pt")
# Save final results
print("=" * 80)
print("All category results:")
print("=" * 80)
pprint(all_results)
save_path = os.path.join(save_dir, "percate_results.npy")
np.save(save_path, all_results)
return all_results
def evaluate_gen(model, args):
loader = get_test_loader(args)
all_sample = []
all_ref = []
for data in loader:
idx_b, te_pc, tr_pc = data["idx"], data["test_points"], data["train_points"]
te_pc = te_pc.cuda() if args.gpu is None else te_pc.cuda(args.gpu)
B, N = te_pc.size(0), te_pc.size(1)
_, out_pc = model.sample(B, N)
# denormalize
m, s = data["mean"].float(), data["std"].float()
m = m.cuda() if args.gpu is None else m.cuda(args.gpu)
s = s.cuda() if args.gpu is None else s.cuda(args.gpu)
out_pc = out_pc * s + m
te_pc = te_pc * s + m
out_pc = normalize(out_pc)
te_pc = normalize(te_pc)
all_sample.append(out_pc)
all_ref.append(te_pc)
sample_pcs = torch.cat(all_sample, dim=0)
ref_pcs = torch.cat(all_ref, dim=0)
print(
"Generation sample size:%s reference size: %s"
% (sample_pcs.size(), ref_pcs.size())
)
# Save the generative output
save_dir = os.path.dirname(args.resume_checkpoint)
np.save(
os.path.join(save_dir, "model_out_smp.npy"), sample_pcs.cpu().detach().numpy()
)
np.save(os.path.join(save_dir, "model_out_ref.npy"), ref_pcs.cpu().detach().numpy())
# Compute metrics
results = compute_all_metrics(
sample_pcs, ref_pcs, args.batch_size, accelerated_cd=True
)
results = {
k: (v.cpu().detach().item() if not isinstance(v, float) else v)
for k, v in results.items()
}
pprint(results)
sample_pcl_npy = sample_pcs.cpu().detach().numpy()
ref_pcl_npy = ref_pcs.cpu().detach().numpy()
jsd = JSD(sample_pcl_npy, ref_pcl_npy)
print("JSD:%s" % jsd)
def main(args):
model = PointFlow(args)
def _transform_(m):
return nn.DataParallel(m, device_ids=[0])
model = model.cuda()
model.multi_gpu_wrapper(_transform_)
print("Resume Path:%s" % args.resume_checkpoint)
checkpoint = torch.load(args.resume_checkpoint)
model.load_state_dict(checkpoint)
model.eval()
with torch.no_grad():
if args.evaluate_recon:
# Evaluate reconstruction
res = [evaluate_recon(model, args) for _ in range(10)]
res_cd = torch.stack([r[args.cates[0]]["MMD-CD"] for r in res])
res_emd = torch.stack([r[args.cates[0]]["MMD-EMD"] for r in res])
res_cd_mean = res_cd.mean()
res_cd_std = res_cd.std()
res_emd_mean = res_emd.mean()
res_emd_std = res_emd.std()
print("===========RESULTS=============")
print("MMD-CD-Mean", res_cd_mean.item())
print("MMD-CD-STD", res_cd_std.item())
print("MMD-EMD-Mean", res_emd_mean.item())
print("MMD-EMD-STD", res_emd_std.item())
print("===============================")
torch.save(res, "res_pointflow")
else:
# Evaluate generation
evaluate_gen(model, args)
if __name__ == "__main__":
args = get_args()
main(args)