-
Notifications
You must be signed in to change notification settings - Fork 60
/
RepNet.py
1611 lines (1331 loc) · 54.7 KB
/
RepNet.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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
import os
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
import torch
os.environ['CUDA_VISIBLE_DEVICES'] = '1'
device = torch.device('cuda: 0' if torch.cuda.is_available() else 'cpu')
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Parameter
import math
import random
import copy
import torchvision
from torchvision import transforms as T
import pickle
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
from torch.utils import data
# from data import VehicleID_MC, VehicleID_All, id2name
from tqdm import tqdm
import matplotlib as mpl
from matplotlib.font_manager import *
from collections import defaultdict
from InitRepNet import InitRepNet
# 解决负号'-'显示为方块的问题
mpl.rcParams['axes.unicode_minus'] = False
mpl.rcParams['font.sans-serif'] = ['SimHei']
# --------------------------------------
# VehicleID用于MDNet
class VehicleID_All(data.Dataset):
def __init__(self,
root,
transforms=None,
mode='train'):
"""
:param root:
:param transforms:
:param mode:
"""
if not os.path.isdir(root):
print('[Err]: invalid root.')
return
# 加载图像绝对路径和标签
if mode == 'train':
txt_f_path = root + '/attribute/train_all.txt'
elif mode == 'test':
txt_f_path = root + '/attribute/test_all.txt'
if not os.path.isfile(txt_f_path):
print('=> [Err]: invalid txt file.')
return
# 打开vid2TrainID和trainID2Vid映射
vid2TrainID_path = root + '/attribute/vid2TrainID.pkl'
trainID2Vid_path = root + '/attribute/trainID2Vid.pkl'
if not (os.path.isfile(vid2TrainID_path) \
and os.path.isfile(trainID2Vid_path)):
print('=> [Err]: invalid vid, train_id mapping file path.')
with open(vid2TrainID_path, 'rb') as fh_1, \
open(trainID2Vid_path, 'rb') as fh_2:
self.vid2TrainID = pickle.load(fh_1)
self.trainID2Vid = pickle.load(fh_2)
self.imgs_path, self.lables = [], []
with open(txt_f_path, 'r', encoding='utf-8') as f_h:
for line in f_h.readlines():
line = line.strip().split()
img_path = root + '/image/' + line[0] + '.jpg'
if os.path.isfile(img_path):
self.imgs_path.append(img_path)
tr_id = self.vid2TrainID[int(line[3])]
label = np.array([int(line[1]),
int(line[2]),
int(tr_id)], dtype=int)
self.lables.append(torch.Tensor(label))
assert len(self.imgs_path) == len(self.lables)
print('=> total %d samples loaded in %s mode' % (len(self.imgs_path), mode))
# 加载数据变换
if transforms is not None:
self.transforms = transforms
else:
self.transforms = T.Compose([
T.Resize(224),
T.CenterCrop(224),
T.ToTensor(),
T.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
def __getitem__(self, idx):
"""
关于数据缩放方式: 先默认使用非等比缩放
:param idx:
:return:
"""
img = Image.open(self.imgs_path[idx])
# 数据变换, 灰度图转换成'RGB'
if img.mode == 'L' or img.mode == 'I': # 8bit或32bit灰度图
img = img.convert('RGB')
# 图像数据变换
if self.transforms is not None:
img = self.transforms(img)
return img, self.lables[idx]
def __len__(self):
"""
:return:
"""
return len(self.imgs_path)
# Vehicle ID用于车型和颜色的多标签分类
class VehicleID_MC(data.Dataset):
def __init__(self,
root,
transforms=None,
mode='train'):
"""
:param root:
:param transforms:
:param mode:
"""
if not os.path.isdir(root):
print('[Err]: invalid root.')
return
# 加载图像绝对路径和标签
if mode == 'train':
txt_f_path = root + '/attribute/train.txt'
elif mode == 'test':
txt_f_path = root + '/attribute/test.txt'
if not os.path.isfile(txt_f_path):
print('=> [Err]: invalid txt file.')
return
self.imgs_path, self.lables = [], []
with open(txt_f_path, 'r', encoding='utf-8') as f_h:
for line in f_h.readlines():
line = line.strip().split()
img_path = root + '/image/' + line[0] + '.jpg'
if os.path.isfile(img_path):
self.imgs_path.append(img_path)
label = np.array([int(line[1]), int(line[2])], dtype=int)
self.lables.append(torch.Tensor(label))
assert len(self.imgs_path) == len(self.lables)
print('=> total %d samples loaded in %s mode' % (len(self.imgs_path), mode))
# 加载数据变换
if transforms is not None:
self.transforms = transforms
else:
self.transforms = T.Compose([
T.Resize(224),
T.CenterCrop(224),
T.ToTensor(),
T.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
def __getitem__(self, idx):
"""
关于数据缩放方式: 先默认使用非等比缩放
:param idx:
:return:
"""
img = Image.open(self.imgs_path[idx])
# 数据变换, 灰度图转换成'RGB'
if img.mode == 'L' or img.mode == 'I': # 8bit或32bit灰度图
img = img.convert('RGB')
# 图像数据变换
if self.transforms is not None:
img = self.transforms(img)
return img, self.lables[idx]
def __len__(self):
"""
:return:
"""
return len(self.imgs_path)
class FocalLoss(nn.Module):
"""
Focal loss: focus more on hard samples
"""
def __init__(self,
gamma=0,
eps=1e-7):
"""
:param gamma:
:param eps:
"""
super(FocalLoss, self).__init__()
self.gamma = gamma
self.eps = eps
self.ce = torch.nn.CrossEntropyLoss()
def forward(self, input, target):
"""
:param input:
:param target:
:return:
"""
log_p = self.ce(input, target)
p = torch.exp(-log_p)
loss = (1.0 - p) ** self.gamma * log_p
return loss.mean()
# -----------------------------------FC layers
class ArcFC(nn.Module):
r"""
Implement of large margin arc distance: :
Args:
in_features: size of each input sample
out_features: size of each output_layer sample
s: norm of input feature
m: margin
cos(theta + m)
"""
def __init__(self,
in_features,
out_features,
s=30.0,
m=0.50,
easy_margin=False):
"""
ArcMargin
:param in_features:
:param out_features:
:param s:
:param m:
:param easy_margin:
"""
super(ArcFC, self).__init__()
self.in_features = in_features
self.out_features = out_features
print('=> in dim: %d, out dim: %d' % (self.in_features, self.out_features))
self.s = s
self.m = m
# 根据输入输出dim确定初始化权重
self.weight = Parameter(torch.FloatTensor(out_features, in_features))
nn.init.xavier_uniform_(self.weight)
self.easy_margin = easy_margin
self.cos_m = math.cos(m)
self.sin_m = math.sin(m)
self.th = math.cos(math.pi - m)
self.mm = math.sin(math.pi - m) * m
def forward(self, input, label):
# --------------------------- cos(theta) & phi(theta) ---------------------------
# L2 normalize and calculate cosine
cosine = F.linear(F.normalize(input, p=2), F.normalize(self.weight, p=2))
sine = torch.sqrt(1.0 - torch.pow(cosine, 2))
# phi: cos(θ+m)
phi = cosine * self.cos_m - sine * self.sin_m
# ----- whether easy margin
if self.easy_margin:
phi = torch.where(cosine > 0, phi, cosine)
else:
phi = torch.where(cosine > self.th, phi, cosine - self.mm)
# --------------------------- convert label to one-hot ---------------------------
# one_hot = torch.zeros(cosine.size(), requires_grad=True, device='cuda')
one_hot = torch.zeros(cosine.size(), device=device) # device='cuda'
one_hot.scatter_(1, label.view(-1, 1).long(), 1)
# -------------torch.where(out_i = {x_i if condition_i else y_i) -------------
# you can use torch.where if your torch.__version__ is 0.4
output = (one_hot * phi) + ((1.0 - one_hot) * cosine)
output *= self.s
# print(output_layer)
return output
# ---------- Mixed Difference Network Structure base on vgg16
class RepNet(torch.nn.Module):
def __init__(self,
out_ids,
out_attribs):
"""
Network definition
:param out_ids:
:param out_attribs:
"""
super(RepNet, self).__init__()
self.out_ids, self.out_attribs = out_ids, out_attribs
print('=> out_ids: %d, out_attribs: %d' % (self.out_ids, self.out_attribs))
# Conv1
self.conv1_1 = torch.nn.Conv2d(in_channels=3,
out_channels=64,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1)) # (0)
self.conv1_2 = torch.nn.ReLU(inplace=True) # (1)
self.conv1_3 = torch.nn.Conv2d(in_channels=64,
out_channels=64,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1)) # (2)
self.conv1_4 = torch.nn.ReLU(inplace=True) # (3)
self.conv1_5 = torch.nn.MaxPool2d(kernel_size=2,
stride=2,
padding=0,
dilation=1,
ceil_mode=False) # (4)
self.conv1 = torch.nn.Sequential(
self.conv1_1,
self.conv1_2,
self.conv1_3,
self.conv1_4,
self.conv1_5
)
# Conv2
self.conv2_1 = torch.nn.Conv2d(in_channels=64,
out_channels=128,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1)) # (5)
self.conv2_2 = torch.nn.ReLU(inplace=True) # (6)
self.conv2_3 = torch.nn.Conv2d(in_channels=128,
out_channels=128,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1)) # (7)
self.conv2_4 = torch.nn.ReLU(inplace=True) # (8)
self.conv2_5 = torch.nn.MaxPool2d(kernel_size=2,
stride=2,
padding=0,
dilation=1,
ceil_mode=False) # (9)
self.conv2 = torch.nn.Sequential(
self.conv2_1,
self.conv2_2,
self.conv2_3,
self.conv2_4,
self.conv2_5
)
# Conv3
self.conv3_1 = torch.nn.Conv2d(in_channels=128,
out_channels=256,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1)) # (10)
self.conv3_2 = torch.nn.ReLU(inplace=True) # (11)
self.conv3_3 = torch.nn.Conv2d(in_channels=256,
out_channels=256,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1)) # (12)
self.conv3_4 = torch.nn.ReLU(inplace=True) # (13)
self.conv3_5 = torch.nn.Conv2d(in_channels=256,
out_channels=256,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1)) # (14)
self.conv3_6 = torch.nn.ReLU(inplace=True) # (15)
self.conv3_7 = torch.nn.MaxPool2d(kernel_size=2,
stride=2,
padding=0,
dilation=1,
ceil_mode=False) # (16)
self.conv3 = torch.nn.Sequential(
self.conv3_1,
self.conv3_2,
self.conv3_3,
self.conv3_4,
self.conv3_5,
self.conv3_6,
self.conv3_7
)
# Conv4_1
self.conv4_1_1 = torch.nn.Conv2d(in_channels=256,
out_channels=512,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1)) # (17)
self.conv4_1_2 = torch.nn.ReLU(inplace=True) # (18)
self.conv4_1_3 = torch.nn.Conv2d(in_channels=512,
out_channels=512,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1)) # (19)
self.conv4_1_4 = torch.nn.ReLU(inplace=True) # (20)
self.conv4_1_5 = torch.nn.Conv2d(in_channels=512,
out_channels=512,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1)) # (21)
self.conv4_1_6 = torch.nn.ReLU(inplace=True) # (22)
self.conv4_1_7 = torch.nn.MaxPool2d(kernel_size=2,
stride=2,
padding=0,
dilation=1,
ceil_mode=False) # (23)
self.conv4_1 = torch.nn.Sequential(
self.conv4_1_1,
self.conv4_1_2,
self.conv4_1_3,
self.conv4_1_4,
self.conv4_1_5,
self.conv4_1_6,
self.conv4_1_7
)
# Conv4_2
self.conv4_2_1 = torch.nn.Conv2d(in_channels=256,
out_channels=512,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1)) # (17)
self.conv4_2_2 = torch.nn.ReLU(inplace=True) # (18)
self.conv4_2_3 = torch.nn.Conv2d(in_channels=512,
out_channels=512,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1)) # (19)
self.conv4_2_4 = torch.nn.ReLU(inplace=True) # (20)
self.conv4_2_5 = torch.nn.Conv2d(in_channels=512,
out_channels=512,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1)) # (21)
self.conv4_2_6 = torch.nn.ReLU(inplace=True) # (22)
self.conv4_2_7 = torch.nn.MaxPool2d(kernel_size=2,
stride=2,
padding=0,
dilation=1,
ceil_mode=False) # (23)
self.conv4_2 = torch.nn.Sequential(
self.conv4_2_1,
self.conv4_2_2,
self.conv4_2_3,
self.conv4_2_4,
self.conv4_2_5,
self.conv4_2_6,
self.conv4_2_7
)
# Conv5_1
self.conv5_1_1 = torch.nn.Conv2d(in_channels=512,
out_channels=512,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1)) # (24)
self.conv5_1_2 = torch.nn.ReLU(inplace=True) # (25)
self.conv5_1_3 = torch.nn.Conv2d(in_channels=512,
out_channels=512,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1)) # (26)
self.conv5_1_4 = torch.nn.ReLU(inplace=True) # (27)
self.conv5_1_5 = torch.nn.Conv2d(in_channels=512,
out_channels=512,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1)) # (28)
self.conv5_1_6 = torch.nn.ReLU(inplace=True) # (29)
self.conv5_1_7 = torch.nn.MaxPool2d(kernel_size=2,
stride=2,
padding=0,
dilation=1,
ceil_mode=False) # (30)
self.conv5_1 = torch.nn.Sequential(
self.conv5_1_1,
self.conv5_1_2,
self.conv5_1_3,
self.conv5_1_4,
self.conv5_1_5,
self.conv5_1_6,
self.conv5_1_7
)
# Conv5_2
self.conv5_2_1 = torch.nn.Conv2d(in_channels=512,
out_channels=512,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1)) # (24)
self.conv5_2_2 = torch.nn.ReLU(inplace=True) # (25)
self.conv5_2_3 = torch.nn.Conv2d(in_channels=512,
out_channels=512,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1)) # (26)
self.conv5_2_4 = torch.nn.ReLU(inplace=True) # (27)
self.conv5_2_5 = torch.nn.Conv2d(in_channels=512,
out_channels=512,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1)) # (28)
self.conv5_2_6 = torch.nn.ReLU(inplace=True) # (29)
self.conv5_2_7 = torch.nn.MaxPool2d(kernel_size=2,
stride=2,
padding=0,
dilation=1,
ceil_mode=False) # (30)
self.conv5_2 = torch.nn.Sequential(
self.conv5_2_1,
self.conv5_2_2,
self.conv5_2_3,
self.conv5_2_4,
self.conv5_2_5,
self.conv5_2_6,
self.conv5_2_7
)
# FC6_1
self.FC6_1_1 = torch.nn.Linear(in_features=25088,
out_features=4096,
bias=True) # (0)
self.FC6_1_2 = torch.nn.ReLU(inplace=True) # (1)
self.FC6_1_3 = torch.nn.Dropout(p=0.5) # (2)
self.FC6_1_4 = torch.nn.Linear(in_features=4096,
out_features=4096,
bias=True) # (3)
self.FC6_1_5 = torch.nn.ReLU(inplace=True) # (4)
self.FC6_1_6 = torch.nn.Dropout(p=0.5) # (5)
self.FC6_1 = torch.nn.Sequential(
self.FC6_1_1,
self.FC6_1_2,
self.FC6_1_3,
self.FC6_1_4,
self.FC6_1_5,
self.FC6_1_6
)
# FC6_2
self.FC6_2_1 = copy.deepcopy(self.FC6_1_1)
self.FC6_2_2 = copy.deepcopy(self.FC6_1_2)
self.FC6_2_3 = copy.deepcopy(self.FC6_1_3)
self.FC6_2_4 = copy.deepcopy(self.FC6_1_4)
self.FC6_2_5 = copy.deepcopy(self.FC6_1_5)
self.FC6_2_6 = copy.deepcopy(self.FC6_1_6)
self.FC6_2 = torch.nn.Sequential(
self.FC6_2_1,
self.FC6_2_2,
self.FC6_2_3,
self.FC6_2_4,
self.FC6_2_5,
self.FC6_2_6
)
# FC7_1
self.FC7_1 = torch.nn.Linear(in_features=4096,
out_features=1000,
bias=True) # (6): 4096, 1000
# FC7_2
self.FC7_2 = torch.nn.Linear(in_features=4096,
out_features=1000,
bias=True) # (6): 4096, 1000
# ------------------------------ extra layers: FC8 and FC9
self.FC_8 = torch.nn.Linear(in_features=2000, # 2048
out_features=1024) # 1024
# attribute classifiers: out_attribs to be decided
self.attrib_classifier = torch.nn.Linear(in_features=1000,
out_features=out_attribs)
# Arc FC layer for branch_2 and branch_3
self.arc_fc_br2 = ArcFC(in_features=1000,
out_features=out_ids,
s=30.0,
m=0.5,
easy_margin=False)
self.arc_fc_br3 = ArcFC(in_features=1024,
out_features=out_ids,
s=30.0,
m=0.5,
easy_margin=False)
# construct branches
self.shared_layers = torch.nn.Sequential(
self.conv1,
self.conv2,
self.conv3
)
self.branch_1_feats = torch.nn.Sequential(
self.shared_layers,
self.conv4_1,
self.conv5_1,
)
self.branch_1_fc = torch.nn.Sequential(
self.FC6_1,
self.FC7_1
)
self.branch_1 = torch.nn.Sequential(
self.branch_1_feats,
self.branch_1_fc
)
self.branch_2_feats = torch.nn.Sequential(
self.shared_layers,
self.conv4_2,
self.conv5_2
)
self.branch_2_fc = torch.nn.Sequential(
self.FC6_2,
self.FC7_2
)
self.branch_2 = torch.nn.Sequential(
self.branch_2_feats,
self.branch_2_fc
)
def forward(self,
X,
branch,
label=None):
"""
:param X:
:param branch:
:param label:
:return:
"""
# batch size
N = X.size(0)
if branch == 1: # train attributes classification
X = self.branch_1_feats(X)
# reshape and connect to FC layers
X = X.view(N, -1)
X = self.branch_1_fc(X)
assert X.size() == (N, 1000)
X = self.attrib_classifier(X)
assert X.size() == (N, self.out_attribs)
return X
elif branch == 2: # get vehicle fine-grained feature
if label is None:
print('=> label is None.')
return None
X = self.branch_2_feats(X)
# reshape and connect to FC layers
X = X.view(N, -1)
X = self.branch_2_fc(X)
assert X.size() == (N, 1000)
X = self.arc_fc_br2.forward(input=X, label=label)
assert X.size() == (N, self.out_ids)
return X
elif branch == 3: # overall: combine branch_1 and branch_2
if label is None:
print('=> label is None.')
return None
branch_1 = self.branch_1_feats(X)
branch_2 = self.branch_2_feats(X)
# reshape and connect to FC layers
branch_1 = branch_1.view(N, -1)
branch_2 = branch_2.view(N, -1)
branch_1 = self.branch_1_fc(branch_1)
branch_2 = self.branch_2_fc(branch_2)
assert branch_1.size() == (N, 1000) and branch_2.size() == (N, 1000)
# feature fusion
fusion_feats = torch.cat((branch_1, branch_2), dim=1)
assert fusion_feats.size() == (N, 2000)
# connect to FC8: output 1024 dim feature vector
X = self.FC_8(fusion_feats)
# connect to classifier: arc_fc_br3
X = self.arc_fc_br3.forward(input=X, label=label)
assert X.size() == (N, self.out_ids)
return X
elif branch == 4: # test pre-trained weights
# extract features
X = self.branch_1_feats(X)
# flatten and connect to FC layers
X = X.view(N, -1)
X = self.branch_1_fc(X)
assert X.size() == (N, 1000)
return X
elif branch == 5:
# 前向运算提取用于Vehicle ID的特征向量
branch_1 = self.branch_1_feats(X)
branch_2 = self.branch_2_feats(X)
# reshape and connect to FC layers
branch_1 = branch_1.view(N, -1)
branch_2 = branch_2.view(N, -1)
branch_1 = self.branch_1_fc(branch_1)
branch_2 = self.branch_2_fc(branch_2)
assert branch_1.size() == (N, 1000) and branch_2.size() == (N, 1000)
# feature fusion
fusion_feats = torch.cat((branch_1, branch_2), dim=1)
assert fusion_feats.size() == (N, 2000)
# connect to FC8: output 1024 dim feature vector
X = self.FC_8(fusion_feats)
assert X.size() == (N, 1024)
return X
else:
print('=> invalid branch')
return None
# --------------------------------------- methods
def get_predict_mc(output):
"""
softmax归一化,然后统计每一个标签最大值索引
:param output:
:return:
"""
# 计算预测值
output = output.cpu() # 从GPU拷贝出来
pred_model = output[:, :250]
pred_color = output[:, 250:]
model_idx = pred_model.max(1, keepdim=True)[1]
color_idx = pred_color.max(1, keepdim=True)[1]
# 连接pred
pred = torch.cat((model_idx, color_idx), dim=1)
return pred
def count_correct(pred, label):
"""
:param output:
:param label:
:return:
"""
assert pred.size(0) == label.size(0)
correct_num = 0
for one, two in zip(pred, label):
if torch.equal(one, two):
correct_num += 1
return correct_num
def count_attrib_correct(pred, label, idx):
"""
:param pred:
:param label:
:param idx:
:return:
"""
assert pred.size(0) == label.size(0)
correct_num = 0
for one, two in zip(pred, label):
if one[idx] == two[idx]:
correct_num += 1
return correct_num
# @TODO: 可视化分类结果...
def ivt_tensor_img(input,
title=None):
"""
Imshow for Tensor.
"""
input = input.numpy().transpose((1, 2, 0))
# 转变数组格式 RGB图像格式:rows * cols * channels
# 灰度图则不需要转换,只有(rows, cols)而不是(rows, cols, 1)
# (3, 228, 906) # (228, 906, 3)
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
# 去标准化,对应transforms
input = std * input + mean
# 修正 clip 限制inp的值,小于0则=0,大于1则=1
output = np.clip(input, 0, 1)
# plt.imshow(input)
# if title is not None:
# plt.title(title)
# plt.pause(0.001) # pause a bit so that plots are updated
return output
def viz_results(resume,
data_root):
"""
:param resume:
:param data_root:
:return:
"""
color_dict = {'black': u'黑色',
'blue': u'蓝色',
'gray': u'灰色',
'red': u'红色',
'sliver': u'银色',
'white': u'白色',
'yellow': u'黄色'}
test_set = VehicleID_All(root=data_root,
transforms=None,
mode='test')
test_loader = torch.utils.data.DataLoader(dataset=test_set,
batch_size=1,
shuffle=False,
num_workers=1)
net = RepNet(out_ids=10086,
out_attribs=257).to(device)
print('=> Mix difference network:\n', net)
# 从断点启动
if resume is not None:
if os.path.isfile(resume):
# 加载模型
net.load_state_dict(torch.load(resume))
print('=> net resume from {}'.format(resume))
else:
print('=> [Err]: invalid resume path @ %s' % resume)
# 测试模式
net.eval()
# 加载类别id映射和类别名称
modelID2name_path = data_root + '/attribute/modelID2name.pkl'
colorID2name_path = data_root + '/attribute/colorID2name.pkl'
trainID2Vid_path = data_root + '/attribute/trainID2Vid.pkl'
if not (os.path.isfile(modelID2name_path) and \
os.path.isfile(colorID2name_path) and \
os.path.isfile((trainID2Vid_path))):
print('=> [Err]: invalid file.')
return
with open(modelID2name_path, 'rb') as fh_1, \
open(colorID2name_path, 'rb') as fh_2, \
open(trainID2Vid_path, 'rb') as fh_3:
modelID2name = pickle.load(fh_1)
colorID2name = pickle.load(fh_2)
trainID2Vid = pickle.load(fh_3)
# 测试
print('=> testing...')
for i, (data, label) in enumerate(test_loader):
# 放入GPU.
data, label = data.to(device), label.to(device).long()
# 前向运算: 预测车型、车身颜色
output_attrib = net.forward(X=data,
branch=1,
label=None)
pred_mc = get_predict_mc(output_attrib).cpu()[0]
pred_m_id, pred_c_id = pred_mc[0].item(), pred_mc[1].item()
pred_m_name = modelID2name[pred_m_id]
pred_c_name = colorID2name[pred_c_id]
# 前向运算: 预测Vehicle ID
output_id = net.forward(X=data,
branch=3,
label=label[:, 2])
_, pred_tid = torch.max(output_id, 1)
pred_tid = pred_tid.cpu()[0].item()
pred_vid = trainID2Vid[pred_tid]
# 获取实际result
img_path = test_loader.dataset.imgs_path[i]
img_name = os.path.split(img_path)[-1][:-4]
result = label.cpu()[0]
res_m_id, res_c_id, res_vid = result[0].item(), result[1].item(), \
trainID2Vid[result[2].item()]
res_m_name = modelID2name[res_m_id]
res_c_name = colorID2name[res_c_id]
# 图像标题
title = 'pred: ' + pred_m_name + ' ' + color_dict[pred_c_name] \
+ ', vehicle ID ' + str(pred_vid) \
+ '\n' + 'resu: ' + res_m_name + ' ' + color_dict[res_c_name] \
+ ', vehicle ID ' + str(res_vid)
print('=> result: ', title)
# 绘图
img = ivt_tensor_img(data.cpu()[0])
fig = plt.figure(figsize=(6, 6))
plt.imshow(img)
plt.title(title)
plt.show()
def gen_test_pairs(test_txt,
dst_dir,
num=10000):
"""
生成测试pair数据: 一半positive,一半negative
:param test_txt:
:return:
"""
if not os.path.isfile(test_txt):
print('[Err]: invalid file.')
return
print('=> genarating %d samples...' % num)
with open(test_txt, 'r') as f_h:
valid_list = f_h.readlines()
print('=> %s loaded.' % test_txt)
# 映射: img_name => cls_id
valid_dict = {x.strip().split()[0]: int(x.strip().split()[3]) for x in valid_list}
# 映射: cls_id => img_list
inv_dict = defaultdict(list)
for k, v in valid_dict.items():
inv_dict[v].append(k)
# 统计样本数不少于2的id
big_ids = [k for k, v in inv_dict.items() if len(v) > 1]
# 添加测试样本
pair_set = set()
while len(pair_set) < num:
if random.random() <= 0.7: # positive
# 随机从big_ids中选择一个
pick_id = random.sample(big_ids, 1)[0] # 不放回抽取
anchor = random.sample(inv_dict[pick_id], 1)[0]
positive = random.choice(inv_dict[pick_id])
while positive == anchor:
positive = random.choice(inv_dict[pick_id])
pair_set.add(anchor + '\t' + positive + '\t1')
else: # negative