-
Notifications
You must be signed in to change notification settings - Fork 3
/
pointhop.py
executable file
·527 lines (463 loc) · 21.1 KB
/
pointhop.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
import math
import sklearn
import numpy as np
from sklearn.decomposition import PCA
from numpy import linalg as LA
import point_utils
import threading
from sklearn.cluster import KMeans
def sample_knn(point_data, n_newpoint, n_sample):
point_num = point_data.shape[1]
if n_newpoint == point_num:
new_xyz = point_data
else:
new_xyz = point_utils.furthest_point_sample(point_data, n_newpoint)
idx = point_utils.knn(new_xyz, point_data, n_sample)
return new_xyz, idx
def tree(Train, Bias, point_data, data, grouped_feature, idx, pre_energy, threshold, params):
if grouped_feature is None:
grouped_feature = data
grouped_feature = point_utils.gather_fea(idx, point_data, grouped_feature)
s1 = grouped_feature.shape[0]
s2 = grouped_feature.shape[1]
grouped_feature = grouped_feature.reshape(s1 * s2, -1)
if Train is True:
kernels, mean, energy = find_kernels_pca(grouped_feature)
bias = LA.norm(grouped_feature, axis=1)
bias = np.max(bias)
if pre_energy is not None:
energy = energy * pre_energy
num_node = np.sum(energy > threshold)
params = {}
params['bias'] = bias
params['kernel'] = kernels
params['pca_mean'] = mean
params['energy'] = energy
params['num_node'] = num_node
else:
kernels = params['kernel']
mean = params['pca_mean']
bias = params['bias']
if Bias is True:
grouped_feature = grouped_feature + bias
transformed = np.matmul(grouped_feature, np.transpose(kernels))
if Bias is True:
e = np.zeros((1, kernels.shape[0]))
e[0, 0] = 1
transformed -= bias * e
transformed = transformed.reshape(s1, s2, -1)
output = []
for i in range(transformed.shape[-1]):
output.append(transformed[:, :, i].reshape(s1, s2, 1))
return params, output
def tree_multi(Train, Bias, point_data, data, grouped_feature, idx, pre_energy, threshold, params, j, index, params_t, out):
if grouped_feature is None:
grouped_feature = data
grouped_feature = point_utils.gather_fea(idx, point_data, grouped_feature)
s1 = grouped_feature.shape[0]
s2 = grouped_feature.shape[1]
grouped_feature = grouped_feature.reshape(s1 * s2, -1)
if Train is True:
kernels, mean, energy = find_kernels_pca(grouped_feature)
bias = LA.norm(grouped_feature, axis=1)
bias = np.max(bias)
if pre_energy is not None:
energy = energy * pre_energy
num_node = np.sum(energy > threshold)
params = {}
params['bias'] = bias
params['kernel'] = kernels
params['pca_mean'] = mean
params['energy'] = energy
params['num_node'] = num_node
else:
kernels = params['kernel']
mean = params['pca_mean']
bias = params['bias']
if Bias is True:
grouped_feature = grouped_feature + bias
transformed = np.matmul(grouped_feature, np.transpose(kernels))
if Bias is True:
e = np.zeros((1, kernels.shape[0]))
e[0, 0] = 1
transformed -= bias * e
transformed = transformed.reshape(s1, s2, -1)
output = []
for i in range(transformed.shape[-1]):
output.append(transformed[:, :, i].reshape(s1, s2, 1))
index.append(j)
params_t.append(params)
out.append(output)
def pointhop_train(Train, data, n_newpoint, n_sample, threshold):
'''
Train based on the provided samples.
:param train_data: [num_samples, num_point, feature_dimension]
:param n_newpoint: point numbers used in every stage
:param n_sample: k nearest neighbors
:param layer_num: num kernels to be preserved
:param energy_percent: the percent of energy to be preserved
:return: idx, new_idx, final stage feature, feature, pca_params
'''
point_data = data
Bias = [False, True, True, True]
info = {}
pca_params = {}
leaf_node = []
leaf_node_energy = []
for i in range(len(n_newpoint)):
new_xyz, idx = sample_knn(point_data, n_newpoint[i], n_sample[i])
if i == 0:
print(i)
pre_energy = 1
params, output = tree(Train, Bias[i], point_data, data, None, idx, pre_energy, threshold, None)
pca_params['Layer_{:d}_pca_params'.format(i)] = params
num_node = params['num_node']
energy = params['energy']
info['Layer_{:d}_feature'.format(i)] = output[:num_node]
info['Layer_{:d}_energy'.format(i)] = energy
info['Layer_{:d}_num_node'.format(i)] = num_node
if num_node != len(output):
for m in range(num_node, len(output), 1):
leaf_node.append(output[m])
leaf_node_energy.append(energy[m])
elif i == 1:
output = info['Layer_{:d}_feature'.format(i - 1)]
pre_energy = info['Layer_{:d}_energy'.format(i - 1)]
num_node = info['Layer_{:d}_num_node'.format(i - 1)]
s1 = 0
index = []
params_t = []
out = []
threads = []
for j in range(num_node):
threads.append(threading.Thread(target=tree_multi, args=(Train, Bias[i], point_data, data, output[j], idx,
pre_energy[j], threshold, None, j, index, params_t, out)))
for t in threads:
t.setDaemon(False)
t.start()
for t in threads:
if t.isAlive():
t.join()
for j in range(num_node):
print(i, j)
ind = np.where(np.array(index) == j)[0]
params = params_t[ind[0]]
output_t = out[ind[0]]
pca_params['Layer_{:d}_{:d}_pca_params'.format(i, j)] = params
num_node_t = params['num_node']
energy = params['energy']
info['Layer_{:d}_{:d}_feature'.format(i, j)] = output_t[:num_node_t]
info['Layer_{:d}_{:d}_energy'.format(i, j)] = energy
info['Layer_{:d}_{:d}_num_node'.format(i, j)] = num_node_t
s1 = s1 + num_node_t
if num_node_t != len(output_t):
for m in range(num_node_t, len(output_t), 1):
leaf_node.append(output_t[m])
leaf_node_energy.append(energy[m])
elif i == 2:
num_node = info['Layer_{:d}_num_node'.format(i - 2)]
for j in range(num_node):
output = info['Layer_{:d}_{:d}_feature'.format(i - 1, j)]
pre_energy = info['Layer_{:d}_{:d}_energy'.format(i - 1, j)]
num_node_t = info['Layer_{:d}_{:d}_num_node'.format(i - 1, j)]
index = []
params_t = []
out = []
threads = []
for k in range(num_node_t):
threads.append(
threading.Thread(target=tree_multi, args=(Train, Bias[i], point_data, data, output[k], idx,
pre_energy[k], threshold, None, k, index, params_t, out)))
for t in threads:
t.setDaemon(False)
t.start()
for t in threads:
if t.isAlive():
t.join()
for k in range(num_node_t):
print(i, j, k)
ind = np.where(np.array(index) == k)[0]
params = params_t[ind[0]]
output_t = out[ind[0]]
pca_params['Layer_{:d}_{:d}_{:d}_pca_params'.format(i, j, k)] = params
num_node_tt = params['num_node']
energy = params['energy']
info['Layer_{:d}_{:d}_{:d}_feature'.format(i, j, k)] = output_t[:num_node_tt]
info['Layer_{:d}_{:d}_{:d}_energy'.format(i, j, k)] = energy
info['Layer_{:d}_{:d}_{:d}_num_node'.format(i, j, k)] = num_node_tt
if num_node_tt != len(output_t):
for m in range(num_node_tt, len(output_t), 1):
leaf_node.append(output_t[m])
leaf_node_energy.append(energy[m])
elif i == 3:
num_node = info['Layer_{:d}_num_node'.format(i - 3)]
for j in range(num_node):
num_node_t = info['Layer_{:d}_{:d}_num_node'.format(i - 2, j)]
for k in range(num_node_t):
output = info['Layer_{:d}_{:d}_{:d}_feature'.format(i - 1, j, k)]
pre_energy = info['Layer_{:d}_{:d}_{:d}_energy'.format(i - 1, j, k)]
num_node_tt = info['Layer_{:d}_{:d}_{:d}_num_node'.format(i - 1, j, k)]
index = []
params_t = []
out = []
threads = []
for t in range(num_node_tt):
threads.append(
threading.Thread(target=tree_multi, args=(Train, Bias[i], point_data, data, output[t], idx,
pre_energy[t], threshold, None, t, index, params_t, out)))
for t in threads:
t.setDaemon(False)
t.start()
for t in threads:
if t.isAlive():
t.join()
for t in range(num_node_tt):
print(i, j, k, t)
ind = np.where(np.array(index) == t)[0]
params = params_t[ind[0]]
output_t = out[ind[0]]
pca_params['Layer_{:d}_{:d}_{:d}_{:d}_pca_params'.format(i, j, k, t)] = params
num_node_ttt = params['num_node']
energy = params['energy']
info['Layer_{:d}_{:d}_{:d}_{:d}_feature'.format(i, j, k, t)] = output_t[:num_node_ttt]
info['Layer_{:d}_{:d}_{:d}_{:d}_energy'.format(i, j, k, t)] = energy
info['Layer_{:d}_{:d}_{:d}_{:d}_num_node'.format(i, j, k, t)] = num_node_ttt
for m in range(len(output_t)):
leaf_node.append(output_t[m])
leaf_node_energy.append(energy[m])
point_data = new_xyz
# print(len(leaf_node))
return pca_params, leaf_node, leaf_node_energy
def pointhop_pred(Train, data, pca_params, n_newpoint, n_sample):
'''
Test based on the provided samples.
:param test_data: [num_samples, num_point, feature_dimension]
:param pca_params: pca kernel and mean
:param n_newpoint: point numbers used in every stage
:param n_sample: k nearest neighbors
:param layer_num: num kernels to be preserved
:param idx_save: knn index
:param new_xyz_save: down sample index
:return: final stage feature, feature, pca_params
'''
point_data = data
Bias = [False, True, True, True]
info_test = {}
leaf_node = []
for i in range(len(n_newpoint)):
new_xyz, idx = sample_knn(point_data, n_newpoint[i], n_sample[i])
if i == 0:
print(i)
params = pca_params['Layer_{:d}_pca_params'.format(i)]
num_node = params['num_node']
params_t, output = tree(Train, Bias[i], point_data, data, None, idx, None, None, params)
info_test['Layer_{:d}_feature'.format(i)] = output[:num_node]
info_test['Layer_{:d}_num_node'.format(i)] = num_node
if num_node != len(output):
for m in range(num_node, len(output), 1):
leaf_node.append(output[m])
elif i == 1:
output = info_test['Layer_{:d}_feature'.format(i - 1)]
num_node = info_test['Layer_{:d}_num_node'.format(i - 1)]
index = []
params_t = []
out = []
threads = []
for j in range(num_node):
threads.append(
threading.Thread(target=tree_multi, args=(Train, Bias[i], point_data, data, output[j], idx,
None, None, pca_params['Layer_{:d}_{:d}_pca_params'.format(i, j)], j, index, params_t, out)))
for t in threads:
t.setDaemon(False)
t.start()
for t in threads:
if t.isAlive():
t.join()
for j in range(num_node):
print(i, j)
ind = np.where(np.array(index) == j)[0]
output_t = out[ind[0]]
params = pca_params['Layer_{:d}_{:d}_pca_params'.format(i, j)]
num_node_t = params['num_node']
info_test['Layer_{:d}_{:d}_feature'.format(i, j)] = output_t[:num_node_t]
info_test['Layer_{:d}_{:d}_num_node'.format(i, j)] = num_node_t
if num_node_t != len(output_t):
for m in range(num_node_t, len(output_t), 1):
leaf_node.append(output_t[m])
elif i == 2:
num_node = info_test['Layer_{:d}_num_node'.format(i - 2)]
for j in range(num_node):
output = info_test['Layer_{:d}_{:d}_feature'.format(i - 1, j)]
num_node_t = info_test['Layer_{:d}_{:d}_num_node'.format(i - 1, j)]
index = []
params_t = []
out = []
threads = []
for k in range(num_node_t):
threads.append(
threading.Thread(target=tree_multi, args=(Train, Bias[i], point_data, data, output[k], idx,
None, None, pca_params['Layer_{:d}_{:d}_{:d}_pca_params'.format(i, j, k)], k, index, params_t, out)))
for t in threads:
t.setDaemon(False)
t.start()
for t in threads:
if t.isAlive():
t.join()
for k in range(num_node_t):
print(i, j, k)
params = pca_params['Layer_{:d}_{:d}_{:d}_pca_params'.format(i, j, k)]
num_node_tt = params['num_node']
ind = np.where(np.array(index) == k)[0]
output_t = out[ind[0]]
info_test['Layer_{:d}_{:d}_{:d}_feature'.format(i, j, k)] = output_t[:num_node_tt]
info_test['Layer_{:d}_{:d}_{:d}_num_node'.format(i, j, k)] = num_node_tt
if num_node_tt != len(output_t):
for m in range(num_node_tt, len(output_t), 1):
leaf_node.append(output_t[m])
elif i == 3:
num_node = info_test['Layer_{:d}_num_node'.format(i - 3)]
for j in range(num_node):
num_node_t = info_test['Layer_{:d}_{:d}_num_node'.format(i - 2, j)]
for k in range(num_node_t):
output = info_test['Layer_{:d}_{:d}_{:d}_feature'.format(i - 1, j, k)]
num_node_tt = info_test['Layer_{:d}_{:d}_{:d}_num_node'.format(i - 1, j, k)]
index = []
params_t = []
out = []
threads = []
for t in range(num_node_tt):
threads.append(
threading.Thread(target=tree_multi, args=(Train, Bias[i], point_data, data, output[t], idx,
None, None, pca_params['Layer_{:d}_{:d}_{:d}_{:d}_pca_params'.format(i, j, k, t)], t, index, params_t, out)))
for t in threads:
t.setDaemon(False)
t.start()
for t in threads:
if t.isAlive():
t.join()
for t in range(num_node_tt):
print(i, j, k, t)
params = pca_params['Layer_{:d}_{:d}_{:d}_{:d}_pca_params'.format(i, j, k, t)]
num_node_ttt = params['num_node']
ind = np.where(np.array(index) == t)[0]
output_t = out[ind[0]]
info_test['Layer_{:d}_{:d}_{:d}_{:d}_feature'.format(i, j, k, t)] = output_t[:num_node_ttt]
info_test['Layer_{:d}_{:d}_{:d}_{:d}_num_node'.format(i, j, k, t)] = num_node_ttt
for m in range(len(output_t)):
leaf_node.append(output_t[m])
point_data = new_xyz
# print(len(leaf_node))
return leaf_node
def remove_mean(features, axis):
'''
Remove the dataset mean.
:param features [num_samples,...]
:param axis the axis to compute mean
'''
feature_mean = np.mean(features, axis=axis, keepdims=True)
feature_remove_mean = features-feature_mean
return feature_remove_mean, feature_mean
def remove_zero_patch(samples):
std_var = (np.std(samples, axis=1)).reshape(-1, 1)
ind_bool = (std_var == 0)
ind = np.where(ind_bool==True)[0]
samples_new = np.delete(samples, ind, 0)
return samples_new
def find_kernels_pca(sample_patches):
'''
Do the PCA based on the provided samples.
If num_kernels is not set, will use energy_percent.
If neither is set, will preserve all kernels.
:param samples: [num_samples, feature_dimension]
:param num_kernels: num kernels to be preserved
:param energy_percent: the percent of energy to be preserved
:return: kernels, sample_mean
'''
# Remove patch mean
sample_patches_centered, dc = remove_mean(sample_patches, axis=1)
sample_patches_centered = remove_zero_patch(sample_patches_centered)
# Remove feature mean (Set E(X)=0 for each dimension)
training_data, feature_expectation = remove_mean(sample_patches_centered, axis=0)
pca = PCA(n_components=training_data.shape[1], svd_solver='full', whiten=True)
pca.fit(training_data)
num_channels = sample_patches.shape[-1]
largest_ev = [np.var(dc*np.sqrt(num_channels))]
dc_kernel = 1/np.sqrt(num_channels)*np.ones((1, num_channels))/np.sqrt(largest_ev)
kernels = pca.components_[:, :]
mean = pca.mean_
kernels = np.concatenate((dc_kernel, kernels), axis=0)[:kernels.shape[0], :]
energy = np.concatenate((largest_ev, pca.explained_variance_[:kernels.shape[0]-1]), axis=0) \
/ (np.sum(pca.explained_variance_[:kernels.shape[0]-1]) + largest_ev)
return kernels, mean, energy
def extract(feat):
'''
Do feature extraction based on the provided feature.
:param feat: [num_layer, num_samples, feature_dimension]
# :param pooling: pooling method to be used
:return: feature
'''
mean = []
maxi = []
l1 = []
l2 = []
for i in range(len(feat)):
mean.append(feat[i].mean(axis=1, keepdims=False))
maxi.append(feat[i].max(axis=1, keepdims=False))
l1.append(np.linalg.norm(feat[i], ord=1, axis=1, keepdims=False))
l2.append(np.linalg.norm(feat[i], ord=2, axis=1, keepdims=False))
mean = np.concatenate(mean, axis=-1)
maxi = np.concatenate(maxi, axis=-1)
l1 = np.concatenate(l1, axis=-1)
l2 = np.concatenate(l2, axis=-1)
return [mean, maxi, l1, l2]
def aggregate(feat, pool):
feature = []
for j in range(len(feat)):
feature.append(feat[j] * pool[j])
feature = np.concatenate(feature, axis=-1)
return feature
def average_acc(label, pred_label):
classes = np.arange(40)
acc = np.zeros(len(classes))
for i in range(len(classes)):
ind = np.where(label == classes[i])[0]
pred_test_special = pred_label[ind]
acc[i] = len(np.where(pred_test_special == classes[i])[0])/float(len(ind))
return acc
def onehot_encoding(n_class, labels):
targets = labels.reshape(-1)
one_hot_targets = np.eye(n_class)[targets]
return one_hot_targets
def KMeans_Cross_Entropy(X, Y, num_class, num_bin=32):
if np.unique(Y).shape[0] == 1:
return 0
if X.shape[0] < num_bin:
return -1
kmeans = KMeans(n_clusters=num_bin, random_state=0).fit(X)
prob = np.zeros((num_bin, num_class))
for i in range(num_bin):
idx = (kmeans.labels_ == i)
tmp = Y[idx]
for j in range(num_class):
prob[i, j] = float(tmp[tmp == j].shape[0]) / (float(Y[Y == j].shape[0]) + 1e-5)
prob = (prob) / (np.sum(prob, axis=1).reshape(-1, 1) + 1e-5)
true_indicator = onehot_encoding(num_class, Y)
probab = prob[kmeans.labels_]
return sklearn.metrics.log_loss(true_indicator, probab)/math.log(num_class)
def CE(X, Y, num_class):
H = []
for i in range(X.shape[1]):
H.append(KMeans_Cross_Entropy(X[:, i].reshape(-1, 1), Y, num_class, num_bin=40))
return np.array(H)
def llsr_train(feature, label):
A = np.ones((feature.shape[0], 1))
feature = np.concatenate((A, feature), axis=1)
y = onehot_encoding(40, label)
weight = np.matmul(LA.pinv(feature), y)
return weight
def llsr_pred(feature, weight):
A = np.ones((feature.shape[0], 1))
feature = np.concatenate((A, feature), axis=1)
feature = np.matmul(feature, weight)
pred = np.argmax(feature, axis=1)
return feature, pred