-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
660 lines (513 loc) · 23.7 KB
/
models.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
import os
import pickle
import random
import time
import numpy as np
import sklearn.metrics as metrics
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from sklearn.metrics import confusion_matrix
from torch.optim.lr_scheduler import CosineAnnealingLR, MultiStepLR
from torch.utils import data
from torchvision import transforms
from tqdm import tqdm
def batched_index_select(input, dim, index):
views = [input.shape[0]] + \
[1 if i != dim else -1 for i in range(1, len(input.shape))]
expanse = list(input.shape)
expanse[0] = -1
expanse[dim] = -1
index = index.view(views).expand(expanse)
return torch.gather(input, dim, index)
def gumbel_softmax(logits, dim, temperature=1):
"""
ST-gumple-softmax w/o random gumbel samplings
input: [*, n_class]
return: flatten --> [*, n_class] an one-hot vector
"""
y = F.softmax(logits / temperature, dim=dim)
shape = y.size()
_, ind = y.max(dim=-1)
y_hard = torch.zeros_like(y).view(-1, shape[-1])
y_hard.scatter_(1, ind.view(-1, 1), 1)
y_hard = y_hard.view(*shape)
y_hard = (y_hard - y).detach() + y
return y_hard
class Walk(nn.Module):
'''
Walk in the cloud
'''
def __init__(self, in_channel, k, curve_num, curve_length, device):
super(Walk, self).__init__()
self.curve_num = curve_num
self.curve_length = curve_length
self.k = k
self.device = device
self.agent_mlp = nn.Sequential(
nn.Conv2d(in_channel * 2,
1,
kernel_size=1,
bias=False), nn.BatchNorm2d(1))
self.momentum_mlp = nn.Sequential(
nn.Conv1d(in_channel * 2,
2,
kernel_size=1,
bias=False), nn.BatchNorm1d(2))
def crossover_suppression(self, cur, neighbor, bn, n, k):
# cur: bs*n, 3
# neighbor: bs*n, 3, k
neighbor = neighbor.detach()
cur = cur.unsqueeze(-1).detach()
dot = torch.bmm(cur.transpose(1,2), neighbor) # bs*n, 1, k
norm1 = torch.norm(cur, dim=1, keepdim=True)
norm2 = torch.norm(neighbor, dim=1, keepdim=True)
divider = torch.clamp(norm1 * norm2, min=1e-8)
ans = torch.div(dot, divider).squeeze() # bs*n, k
# normalize to [0, 1]
ans = 1. + ans
ans = torch.clamp(ans, 0., 1.0)
return ans.detach()
def forward(self, xyz, x, adj, cur):
bn, c, tot_points = x.size()
# raw point coordinates
xyz = xyz.transpose(1,2).contiguous # bs, n, 3
# point features
x = x.transpose(1,2).contiguous() # bs, n, c
flatten_x = x.view(bn * tot_points, -1)
batch_offset = torch.arange(0, bn, device=self.device).detach() * tot_points
# indices of neighbors for the starting points
tmp_adj = (adj + batch_offset.view(-1,1,1)).view(adj.size(0)*adj.size(1),-1) #bs, n, k
# batch flattened indices for teh starting points
flatten_cur = (cur + batch_offset.view(-1,1,1)).view(-1)
curves = []
# one step at a time
for step in range(self.curve_length):
if step == 0:
# get starting point features using flattend indices
starting_points = flatten_x[flatten_cur, :].contiguous()
pre_feature = starting_points.view(bn, self.curve_num, -1, 1).transpose(1,2) # bs * n, c
else:
# dynamic momentum
cat_feature = torch.cat((cur_feature.squeeze(), pre_feature.squeeze()),dim=1)
att_feature = F.softmax(self.momentum_mlp(cat_feature),dim=1).view(bn, 1, self.curve_num, 2) # bs, 1, n, 2
cat_feature = torch.cat((cur_feature, pre_feature),dim=-1) # bs, c, n, 2
# update curve descriptor
pre_feature = torch.sum(cat_feature * att_feature, dim=-1, keepdim=True) # bs, c, n
pre_feature_cos = pre_feature.transpose(1,2).contiguous().view(bn * self.curve_num, -1)
pick_idx = tmp_adj[flatten_cur] # bs*n, k
# get the neighbors of current points
pick_values = flatten_x[pick_idx.view(-1),:]
# reshape to fit crossover suppresion below
pick_values_cos = pick_values.view(bn * self.curve_num, self.k, c)
pick_values = pick_values_cos.view(bn, self.curve_num, self.k, c)
pick_values_cos = pick_values_cos.transpose(1,2).contiguous()
pick_values = pick_values.permute(0,3,1,2) # bs, c, n, k
pre_feature_expand = pre_feature.expand_as(pick_values)
# concat current point features with curve descriptors
pre_feature_expand = torch.cat((pick_values, pre_feature_expand),dim=1)
# which node to pick next?
pre_feature_expand = self.agent_mlp(pre_feature_expand) # bs, 1, n, k
if step !=0:
# cross over supression
d = self.crossover_suppression(cur_feature_cos - pre_feature_cos,
pick_values_cos - cur_feature_cos.unsqueeze(-1),
bn, self.curve_num, self.k)
d = d.view(bn, self.curve_num, self.k).unsqueeze(1) # bs, 1, n, k
pre_feature_expand = torch.mul(pre_feature_expand, d)
pre_feature_expand = gumbel_softmax(pre_feature_expand, -1) #bs, 1, n, k
cur_feature = torch.sum(pick_values * pre_feature_expand, dim=-1, keepdim=True) # bs, c, n, 1
cur_feature_cos = cur_feature.transpose(1,2).contiguous().view(bn * self.curve_num, c)
cur = torch.argmax(pre_feature_expand, dim=-1).view(-1, 1) # bs * n, 1
flatten_cur = batched_index_select(pick_idx, 1, cur).squeeze() # bs * n
# collect curve progress
curves.append(cur_feature)
return torch.cat(curves,dim=-1)
def knn(x, k):
k = k + 1
inner = -2 * torch.matmul(x.transpose(2, 1), x)
xx = torch.sum(x**2, dim=1, keepdim=True)
pairwise_distance = -xx - inner - xx.transpose(2, 1)
idx = pairwise_distance.topk(k=k, dim=-1)[1] # (batch_size, num_points, k)
return idx
def square_distance(src, dst):
"""
Calculate Euclid distance between each two points.
"""
B, N, _ = src.shape
_, M, _ = dst.shape
dist = -2 * torch.matmul(src, dst.permute(0, 2, 1))
dist += torch.sum(src ** 2, -1).view(B, N, 1)
dist += torch.sum(dst ** 2, -1).view(B, 1, M)
return dist
def index_points(points, idx):
"""
Input:
points: input points data, [B, N, C]
idx: sample index data, [B, S]
Return:
new_points:, indexed points data, [B, S, C]
"""
device = points.device
B = points.shape[0]
view_shape = list(idx.shape)
view_shape[1:] = [1] * (len(view_shape) - 1)
repeat_shape = list(idx.shape)
repeat_shape[0] = 1
batch_indices = torch.arange(B, dtype=torch.long).to(device).view(view_shape).repeat(repeat_shape)
new_points = points[batch_indices, idx, :]
return new_points
def farthest_point_sample(xyz, npoint):
"""
Input:
xyz: pointcloud data, [B, N, 3]
npoint: number of samples
Return:
centroids: sampled pointcloud index, [B, npoint]
"""
device = xyz.device
B, N, C = xyz.shape
centroids = torch.zeros(B, npoint, dtype=torch.long).to(device)
distance = torch.ones(B, N).to(device) * 1e10
farthest = torch.randint(0, N, (B,), dtype=torch.long).to(device) * 0
batch_indices = torch.arange(B, dtype=torch.long).to(device)
for i in range(npoint):
centroids[:, i] = farthest
centroid = xyz[batch_indices, farthest, :].view(B, 1, 3)
dist = torch.sum((xyz - centroid) ** 2, -1)
mask = dist < distance
distance[mask] = dist[mask]
farthest = torch.max(distance, -1)[1]
return centroids
def sample_and_group(npoint, radius, nsample, xyz, points, returnfps=False):
"""
Input:
npoint:
radius:
nsample:
xyz: input points position data, [B, N, 3]
points: input points data, [B, N, D]
Return:
new_xyz: sampled points position data, [B, npoint, nsample, 3]
new_points: sampled points data, [B, npoint, nsample, 3+D]
"""
timeout = 10
while timeout > 0:
new_xyz = index_points(xyz, farthest_point_sample(xyz, npoint))
torch.cuda.empty_cache()
idx = query_ball_point(radius, nsample, xyz, new_xyz)
torch.cuda.empty_cache()
timeout -= 1
if idx.max() < xyz.shape[1]:
break
if timeout == 0:
# replace max with max - 1 to avoid out of range
idx[idx == xyz.shape[1]] = xyz.shape[1] - 1
# Disclaimer: this is a hack to avoid timeout in sample_and_group
# Implementing a better solution is left as an exercise to the reader
# raise ValueError('Timeout in sample_and_group')
new_points = index_points(points, idx)
torch.cuda.empty_cache()
if returnfps:
return new_xyz, new_points, idx
else:
return new_xyz, new_points
def query_ball_point(radius, nsample, xyz, new_xyz):
"""
Input:
radius: local region radius
nsample: max sample number in local region
xyz: all points, [B, N, 3]
new_xyz: query points, [B, S, 3]
Return:
group_idx: grouped points index, [B, S, nsample]
"""
device = xyz.device
B, N, C = xyz.shape
_, S, _ = new_xyz.shape
group_idx = torch.arange(N, dtype=torch.long).to(device).view(1, 1, N).repeat([B, S, 1])
sqrdists = square_distance(new_xyz, xyz)
group_idx[sqrdists > radius ** 2] = N
group_idx = group_idx.sort(dim=-1)[0][:, :, :nsample]
group_first = group_idx[:, :, 0].view(B, S, 1).repeat([1, 1, nsample])
mask = group_idx == N
group_idx[mask] = group_first[mask]
return group_idx
class LPFA(nn.Module):
def __init__(self, in_channel, out_channel, k, device, mlp_num=2, initial=False,):
super(LPFA, self).__init__()
self.k = k
self.device = device
self.initial = initial
if not initial:
self.xyz2feature = nn.Sequential(
nn.Conv2d(9, in_channel, kernel_size=1, bias=False),
nn.BatchNorm2d(in_channel))
self.mlp = []
for _ in range(mlp_num):
self.mlp.append(nn.Sequential(nn.Conv2d(in_channel, out_channel, 1, bias=False),
nn.BatchNorm2d(out_channel),
nn.LeakyReLU(0.2)))
in_channel = out_channel
self.mlp = nn.Sequential(*self.mlp)
def forward(self, x, xyz, idx=None):
x = self.group_feature(x, xyz, idx)
x = self.mlp(x)
if self.initial:
x = x.max(dim=-1, keepdim=False)[0]
else:
x = x.mean(dim=-1, keepdim=False)
return x
def group_feature(self, x, xyz, idx):
batch_size, num_dims, num_points = x.size()
if idx is None:
idx = knn(xyz, k=self.k)[:,:,:self.k] # (batch_size, num_points, k)
idx_base = torch.arange(0, batch_size, device=self.device).view(-1, 1, 1) * num_points
idx = idx + idx_base
idx = idx.view(-1)
xyz = xyz.transpose(2, 1).contiguous() # bs, n, 3
point_feature = xyz.view(batch_size * num_points, -1)[idx, :]
point_feature = point_feature.view(batch_size, num_points, self.k, -1) # bs, n, k, 3
points = xyz.view(batch_size, num_points, 1, 3).expand(-1, -1, self.k, -1) # bs, n, k, 3
point_feature = torch.cat((points, point_feature, point_feature - points),
dim=3).permute(0, 3, 1, 2).contiguous()
if self.initial:
return point_feature
x = x.transpose(2, 1).contiguous() # bs, n, c
feature = x.view(batch_size * num_points, -1)[idx, :]
feature = feature.view(batch_size, num_points, self.k, num_dims) #bs, n, k, c
x = x.view(batch_size, num_points, 1, num_dims)
feature = feature - x
feature = feature.permute(0, 3, 1, 2).contiguous()
point_feature = self.xyz2feature(point_feature) #bs, c, n, k
feature = F.leaky_relu(feature + point_feature, 0.2)
return feature #bs, c, n, k
class CIC(nn.Module):
def __init__(self, npoint, radius, k, in_channels, output_channels, device, bottleneck_ratio=2, mlp_num=2, curve_config=None):
super(CIC, self).__init__()
self.in_channels = in_channels
self.output_channels = output_channels
self.bottleneck_ratio = bottleneck_ratio
self.radius = radius
self.device = device
self.k = k
self.npoint = npoint
planes = in_channels // bottleneck_ratio
self.use_curve = curve_config is not None
if self.use_curve:
self.curveaggregation = CurveAggregation(planes)
self.curvegrouping = CurveGrouping(planes, k, curve_config[0], curve_config[1], device)
self.conv1 = nn.Sequential(
nn.Conv1d(in_channels,
planes,
kernel_size=1,
bias=False),
nn.BatchNorm1d(in_channels // bottleneck_ratio),
nn.LeakyReLU(negative_slope=0.2, inplace=True))
self.conv2 = nn.Sequential(
nn.Conv1d(planes, output_channels, kernel_size=1, bias=False),
nn.BatchNorm1d(output_channels))
if in_channels != output_channels:
self.shortcut = nn.Sequential(
nn.Conv1d(in_channels,
output_channels,
kernel_size=1,
bias=False),
nn.BatchNorm1d(output_channels))
self.relu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
self.maxpool = MaskedMaxPool(npoint, radius, k)
self.lpfa = LPFA(planes, planes, k, device=device, mlp_num=mlp_num, initial=False)
def forward(self, xyz, x):
# max pool
if xyz.size(-1) != self.npoint:
xyz, x = self.maxpool(
xyz.transpose(1, 2).contiguous(), x)
xyz = xyz.transpose(1, 2)
shortcut = x
x = self.conv1(x) # bs, c', n
idx = knn(xyz, self.k)
if self.use_curve:
# curve grouping
curves = self.curvegrouping(x, xyz, idx[:,:,1:]) # avoid self-loop
# curve aggregation
x = self.curveaggregation(x, curves)
x = self.lpfa(x, xyz, idx=idx[:,:,:self.k]) #bs, c', n, k
x = self.conv2(x) # bs, c, n
if self.in_channels != self.output_channels:
shortcut = self.shortcut(shortcut)
x = self.relu(x + shortcut)
return xyz, x
class CurveAggregation(nn.Module):
def __init__(self, in_channel):
super(CurveAggregation, self).__init__()
self.in_channel = in_channel
mid_feature = in_channel // 2
self.conva = nn.Conv1d(in_channel,
mid_feature,
kernel_size=1,
bias=False)
self.convb = nn.Conv1d(in_channel,
mid_feature,
kernel_size=1,
bias=False)
self.convc = nn.Conv1d(in_channel,
mid_feature,
kernel_size=1,
bias=False)
self.convn = nn.Conv1d(mid_feature,
mid_feature,
kernel_size=1,
bias=False)
self.convl = nn.Conv1d(mid_feature,
mid_feature,
kernel_size=1,
bias=False)
self.convd = nn.Sequential(
nn.Conv1d(mid_feature * 2,
in_channel,
kernel_size=1,
bias=False),
nn.BatchNorm1d(in_channel))
self.line_conv_att = nn.Conv2d(in_channel,
1,
kernel_size=1,
bias=False)
def forward(self, x, curves):
curves_att = self.line_conv_att(curves) # bs, 1, c_n, c_l
curver_inter = torch.sum(curves * F.softmax(curves_att, dim=-1), dim=-1) #bs, c, c_n
curves_intra = torch.sum(curves * F.softmax(curves_att, dim=-2), dim=-2) #bs, c, c_l
curver_inter = self.conva(curver_inter) # bs, mid, n
curves_intra = self.convb(curves_intra) # bs, mid ,n
x_logits = self.convc(x).transpose(1, 2).contiguous()
x_inter = F.softmax(torch.bmm(x_logits, curver_inter), dim=-1) # bs, n, c_n
x_intra = F.softmax(torch.bmm(x_logits, curves_intra), dim=-1) # bs, l, c_l
curver_inter = self.convn(curver_inter).transpose(1, 2).contiguous()
curves_intra = self.convl(curves_intra).transpose(1, 2).contiguous()
x_inter = torch.bmm(x_inter, curver_inter)
x_intra = torch.bmm(x_intra, curves_intra)
curve_features = torch.cat((x_inter, x_intra),dim=-1).transpose(1, 2).contiguous()
x = x + self.convd(curve_features)
return F.leaky_relu(x, negative_slope=0.2)
class CurveGrouping(nn.Module):
def __init__(self, in_channel, k, curve_num, curve_length, device):
super(CurveGrouping, self).__init__()
self.curve_num = curve_num
self.curve_length = curve_length
self.in_channel = in_channel
self.device = device
self.k = k
self.att = nn.Conv1d(in_channel, 1, kernel_size=1, bias=False)
self.walk = Walk(in_channel, k, curve_num, curve_length, device)
def forward(self, x, xyz, idx):
# starting point selection in self attention style
x_att = torch.sigmoid(self.att(x))
x = x * x_att
_, start_index = torch.topk(x_att,
self.curve_num,
dim=2,
sorted=False)
start_index = start_index.squeeze().unsqueeze(2)
curves = self.walk(xyz, x, idx, start_index) #bs, c, c_n, c_l
return curves
class MaskedMaxPool(nn.Module):
def __init__(self, npoint, radius, k):
super(MaskedMaxPool, self).__init__()
self.npoint = npoint
self.radius = radius
self.k = k
def forward(self, xyz, features):
sub_xyz, neighborhood_features = sample_and_group(self.npoint, self.radius, self.k, xyz, features.transpose(1,2))
neighborhood_features = neighborhood_features.permute(0, 3, 1, 2).contiguous()
sub_features = F.max_pool2d(
neighborhood_features, kernel_size=[1, neighborhood_features.shape[3]]
) # bs, c, n, 1
sub_features = torch.squeeze(sub_features, -1) # bs, c, n
return sub_xyz, sub_features
def cal_loss(pred, gold, smoothing=True):
''' Calculate cross entropy loss, apply label smoothing if needed. '''
gold = gold.contiguous().view(-1)
if smoothing:
eps = 0.2
n_class = pred.size(1)
one_hot = torch.zeros_like(pred).scatter(1, gold.view(-1, 1), 1)
one_hot = one_hot * (1 - eps) + (1 - one_hot) * eps / (n_class - 1)
log_prb = F.log_softmax(pred, dim=1)
loss = -(one_hot * log_prb).sum(dim=1).mean()
else:
loss = F.cross_entropy(pred, gold, reduction='mean')
return loss
curve_config = {
'default': [[100, 5], [100, 5], None, None],
'long': [[10, 30], None, None, None]
}
class CurveNet(nn.Module):
def __init__(self, device, num_classes=2, k=20, setting='default'):
super(CurveNet, self).__init__()
assert setting in curve_config
additional_channel = 32
self.device = device
self.lpfa = LPFA(9, additional_channel, device=device, k=k, mlp_num=1, initial=True)
# encoder
self.cic11 = CIC(npoint=1024, radius=0.05, k=k, in_channels=additional_channel, output_channels=64, bottleneck_ratio=2, mlp_num=1, curve_config=curve_config[setting][0],device=device)
self.cic12 = CIC(npoint=1024, radius=0.05, k=k, in_channels=64, output_channels=64, bottleneck_ratio=4, mlp_num=1, curve_config=curve_config[setting][0],device=device)
self.cic21 = CIC(npoint=1024, radius=0.05, k=k, in_channels=64, output_channels=128, bottleneck_ratio=2, mlp_num=1, curve_config=curve_config[setting][1],device=device)
self.cic22 = CIC(npoint=1024, radius=0.1, k=k, in_channels=128, output_channels=128, bottleneck_ratio=4, mlp_num=1, curve_config=curve_config[setting][1],device=device)
self.cic31 = CIC(npoint=256, radius=0.1, k=k, in_channels=128, output_channels=256, bottleneck_ratio=2, mlp_num=1, curve_config=curve_config[setting][2],device=device)
self.cic32 = CIC(npoint=256, radius=0.2, k=k, in_channels=256, output_channels=256, bottleneck_ratio=4, mlp_num=1, curve_config=curve_config[setting][2],device=device)
self.cic41 = CIC(npoint=64, radius=0.2, k=k, in_channels=256, output_channels=512, bottleneck_ratio=2, mlp_num=1, curve_config=curve_config[setting][3],device=device)
self.cic42 = CIC(npoint=64, radius=0.4, k=k, in_channels=512, output_channels=512, bottleneck_ratio=4, mlp_num=1, curve_config=curve_config[setting][3],device=device)
self.conv0 = nn.Sequential(
nn.Conv1d(512, 1024, kernel_size=1, bias=False),
nn.BatchNorm1d(1024),
nn.ReLU(inplace=True))
self.conv1 = nn.Linear(1024 * 2, 512, bias=False)
self.conv2 = nn.Linear(512, num_classes)
self.bn1 = nn.BatchNorm1d(512)
self.dp1 = nn.Dropout(p=0.5)
self.feature_dim = 2048
def forward(self, xyz):
l0_points = self.lpfa(xyz, xyz)
l1_xyz, l1_points = self.cic11(xyz, l0_points)
l1_xyz, l1_points = self.cic12(l1_xyz, l1_points)
l2_xyz, l2_points = self.cic21(l1_xyz, l1_points)
l2_xyz, l2_points = self.cic22(l2_xyz, l2_points)
l3_xyz, l3_points = self.cic31(l2_xyz, l2_points)
l3_xyz, l3_points = self.cic32(l3_xyz, l3_points)
l4_xyz, l4_points = self.cic41(l3_xyz, l3_points)
l4_xyz, l4_points = self.cic42(l4_xyz, l4_points)
x = self.conv0(l4_points)
x_max = F.adaptive_max_pool1d(x, 1)
x_avg = F.adaptive_avg_pool1d(x, 1)
x = torch.cat((x_max, x_avg), dim=1).squeeze(-1)
x = F.relu(self.bn1(self.conv1(x).unsqueeze(-1)), inplace=True).squeeze(-1)
x = self.dp1(x)
x = self.conv2(x)
return x
def get_embedding(self, xyz):
l0_points = self.lpfa(xyz, xyz)
l1_xyz, l1_points = self.cic11(xyz, l0_points)
l1_xyz, l1_points = self.cic12(l1_xyz, l1_points)
l2_xyz, l2_points = self.cic21(l1_xyz, l1_points)
l2_xyz, l2_points = self.cic22(l2_xyz, l2_points)
l3_xyz, l3_points = self.cic31(l2_xyz, l2_points)
l3_xyz, l3_points = self.cic32(l3_xyz, l3_points)
l4_xyz, l4_points = self.cic41(l3_xyz, l3_points)
l4_xyz, l4_points = self.cic42(l4_xyz, l4_points)
x = self.conv0(l4_points)
x_max = F.adaptive_max_pool1d(x, 1)
x_avg = F.adaptive_avg_pool1d(x, 1)
x = torch.cat((x_max, x_avg), dim=1).squeeze(-1)
return x
if __name__ == "__main__":
from dataset import PointCloudData
ds = PointCloudData("data/ANIMAR_Preliminary_Data/3D_Models")
dl = data.DataLoader(ds, batch_size=4)
device = "cpu"
curvenet = CurveNet().to(device)
batch = next(iter(dl))
inputs = batch["pointcloud"] # shape (batch_size, 3, 1024)
print(inputs.shape)
curvenet.train()
embed_output = curvenet.get_embedding(inputs)
print(embed_output.shape)