-
Notifications
You must be signed in to change notification settings - Fork 13
/
utils.py
1735 lines (1435 loc) · 64.9 KB
/
utils.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
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import Counter
from random import seed, choice, sample
import h5py
import numpy as np
import random
import re
from nltk.parse.corenlp import CoreNLPParser
from scipy.misc import imread, imresize
from tqdm import tqdm
st = CoreNLPParser()
from nltk.tokenize import word_tokenize
import nltk
import scipy.sparse as sp
from nltk.stem import WordNetLemmatizer
wordnet_lemmatizer = WordNetLemmatizer()
# from processing.categorizing import filter_titles
import PIL.Image
PIL.Image.MAX_IMAGE_PIXELS = None
from nlgeval import NLGEval
import os
import pdb
import json
import six
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from six.moves import cPickle
# from .rewards import get_scores, get_self_cider_scores
bad_endings = ['with', 'in', 'on', 'of', 'a', 'at', 'to', 'for', 'an', 'this', 'his', 'her', 'that']
bad_endings += ['the']
def random_one(impaths, imcaps, imattrs, imcate, captions_per_image=1):
got = False
while not got:
i = random.randint(0, len(impaths))
try:
img = imread(impaths[i])
# Sample captions
if len(imcaps[i]) < captions_per_image:
captions = imcaps[i] + [choice(imcaps[i]) for _ in range(
captions_per_image - len(imcaps[i]))] # choice(imcaps[i]): get one cap from imcaps[i]
attrs = imattrs[i] # choice(imattrs[i]): get one attr from imattrs[i]
else:
captions = sample(imcaps[i], k=captions_per_image) # if k = len(imcaps[i]), sample works like re-order
attrs = imattrs[i] # if k = len(imattrs[i]), sample works like re-order
got = True
return img, captions, attrs, imcate[i]
except:
got = False
# intersecting color names, e.g., bright white -> bright_white for saving in folders
def intersect_names(names):
# names should be a list
length = len(names)
if length == 1:
return names[0]
result = ''
for i in range(length-1):
result += names[i]
result += '_'
try:
result += names[-1]
except:
pdb.set_trace()
return result
def create_input_files(data_json_path, image_folder, captions_per_image, min_word_freq, output_folder,
max_len=25):
"""
Creates input files for training, validation, and test data.
:param data_json_path: path of JSON file with splits and captions
:param image_folder: folder with downloaded images
:param captions_per_image: number of captions to sample per image
:param min_word_freq: words occuring less frequently than this threshold are binned as <unk>s
:param output_folder: folder to save files
:param max_len: don't sample captions longer than this length
"""
# Read JSON
with open(data_json_path, 'r') as j:
data = json.load(j)
# Read image paths and captions for each image
train_image_paths = []
train_image_captions = []
val_image_paths = []
val_image_captions = []
test_image_paths = []
test_image_captions = []
word_freq = Counter()
for ii, img in enumerate(data):
if len(img['images']) == 0 or len(img['comments']) == 0:
continue
captions = []
for c in img['comments']:
# Update word frequency
tokens = c['phra'][0].split()
word_freq.update(tokens)
if len(tokens) <= max_len:
captions.append(tokens)
if len(captions) == 0:
continue
path = os.path.join(image_folder, str(img['id']), intersect_names(img['images'][0]['color'].replace('/', '').split()), '0.jpeg')
if ii < len(data)/10*9:
train_image_paths.append(path)
train_image_captions.append(captions)
elif ii > len(data)/10*9.5:
val_image_paths.append(path)
val_image_captions.append(captions)
else:
test_image_paths.append(path)
test_image_captions.append(captions)
# Sanity check
assert len(train_image_paths) == len(train_image_captions) # 6673
assert len(val_image_paths) == len(val_image_captions) # 832
assert len(test_image_paths) == len(test_image_captions) # 833
# Create word map
words = [w for w in word_freq.keys() if word_freq[w] > min_word_freq] # len(word_freq) = 27929
word_map = {k: v + 1 for v, k in enumerate(words)} # len(words) = 9486
word_map['<unk>'] = len(word_map) + 1 # 9487
word_map['<start>'] = len(word_map) + 1 # 9488
word_map['<end>'] = len(word_map) + 1 # 9489
word_map['<pad>'] = 0 # 0
# Create a base/root name for all output files
base_filename = 'scg' + '_' + str(captions_per_image) + '_cap_per_img_' + str(min_word_freq) + '_min_word_freq' # 'scg_5_cap_per_img_5_min_word_freq'
# Save word map to a JSON
with open(os.path.join(output_folder, 'WORDMAP_' + base_filename + '.json'), 'w') as j:
json.dump(word_map, j)
# Sample captions for each image, save images to HDF5 file, and captions and their lengths to JSON files
seed(123)
for impaths, imcaps, split in [(train_image_paths, train_image_captions, 'TRAIN'),
(val_image_paths, val_image_captions, 'VAL'),
(test_image_paths, test_image_captions, 'TEST')]:
with h5py.File(os.path.join(output_folder, split + '_IMAGES_' + base_filename + '.hdf5'), 'a') as h:
# Make a note of the number of captions we are sampling per image
h.attrs['captions_per_image'] = captions_per_image
# Create dataset inside HDF5 file to store images
images_n = []
for i, path in enumerate(tqdm(impaths)):
# Read images
try:
img = imread(impaths[i])
except FileNotFoundError:
continue
images_n.append(img)
images = h.create_dataset('images', (len(images_n), 3, 256, 256), dtype='uint8')
print("\nReading %s images and captions, storing to file...\n" % split)
enc_captions = []
caplens = []
for i, img in enumerate(tqdm(images_n)):
# Sample captions
if len(imcaps[i]) < captions_per_image:
captions = imcaps[i] + [choice(imcaps[i]) for _ in range(captions_per_image - len(imcaps[i]))] # choice(imcaps[i]): get one cap from imcaps[i]
else:
captions = sample(imcaps[i], k=captions_per_image) # if k = len(imcaps[i]), sample works like re-order
# Sanity check
assert len(captions) == captions_per_image
# Read images
# try:
# img = imread(impaths[i])
# except FileNotFoundError:
# continue
if len(img.shape) == 2:
img = img[:, :, np.newaxis]
img = np.concatenate([img, img, img], axis=2)
img = imresize(img, (256, 256))
img = img.transpose(2, 0, 1)
assert img.shape == (3, 256, 256)
assert np.max(img) <= 255
# Save image to HDF5 file
images[i] = img
for j, c in enumerate(captions):
# Encode captions
enc_c = [word_map['<start>']] + [word_map.get(word, word_map['<unk>']) for word in c] + [
word_map['<end>']] + [word_map['<pad>']] * (max_len - len(c)) # [9488, 49, 35, 1, 38, 50, 35, 43, 1, 46, 44, 9489, 0, 0, 0, ...]
# Find caption lengths
c_len = len(c) + 2
enc_captions.append(enc_c)
caplens.append(c_len)
# Sanity check
assert images.shape[0] * captions_per_image == len(enc_captions) == len(caplens)
# Save encoded captions and their lengths to JSON files
with open(os.path.join(output_folder, split + '_CAPTIONS_' + base_filename + '.json'), 'w') as j:
json.dump(enc_captions, j)
with open(os.path.join(output_folder, split + '_CAPLENS_' + base_filename + '.json'), 'w') as j:
json.dump(caplens, j)
def create_description_tokenized_files(data_json_path, image_folder, output_file):
# Read JSON
with open(data_json_path, 'r') as j:
data = json.load(j)
data_n = []
for img in data:
img_n = {}
if len(img['images']) == 0:
continue
if img['description'] is None:
continue
path = os.path.join(image_folder, str(img['id']),
intersect_names(img['images'][0]['color'].replace('/', '').split()), '0.jpeg')
if not os.path.exists(path):
continue
if len(img['images']) == 0 or len(img['description']) == 0:
continue
# 1. tokenize sentence
sent = list(st.tokenize(img['description']))
# 2. lowercase sentences
img_n['description'] = " ".join(x.lower() for x in sent)
img_n['id'] = img['id']
img_n['images'] = img['images']
data_n.append(img_n)
with open(output_file, 'w') as f:
json.dump(data_n, fp=f, indent=4, ensure_ascii=False)
def create_description_input_files(data_json_path, image_folder, captions_per_image, min_word_freq, output_folder,
max_len=50):
"""
Creates input files for training, validation, and test data.
:param data_json_path: path of JSON file with splits and captions
:param image_folder: folder with downloaded images
:param captions_per_image: number of captions to sample per image
:param min_word_freq: words occuring less frequently than this threshold are binned as <unk>s
:param output_folder: folder to save files
:param max_len: don't sample captions longer than this length
"""
# Read JSON
with open(data_json_path, 'r') as j:
data = json.load(j)
# Read image paths and captions for each image
train_image_paths = []
train_image_captions = []
train_image_attrs = []
train_image_cate = []
val_image_paths = []
val_image_captions = []
val_image_attrs = []
val_image_cate = []
test_image_paths = []
test_image_captions = []
test_image_attrs = []
test_image_cate = []
word_freq = Counter()
for ii, img in enumerate(data):
path = os.path.join(image_folder, str(img['id']), intersect_names(img['images'][0]['color'].replace('/', '').split()), '0.jpeg')
if not os.path.exists(path):
continue
captions = []
attrs = img['attrid']
tokens = img['description'].split()
tokens = [x.lower() for x in tokens]
word_freq.update(tokens)
if len(tokens) <= max_len:
captions.append(tokens)
if len(captions) == 0:
continue
if ii < len(data)/10*8:
train_image_paths.append(path)
train_image_captions.append(captions)
train_image_attrs.append(attrs)
train_image_cate.append(img['categoryid'])
elif ii > len(data)/10*9:
val_image_paths.append(path)
val_image_captions.append(captions)
val_image_attrs.append(attrs)
val_image_cate.append(img['categoryid'])
else:
test_image_paths.append(path)
test_image_captions.append(captions)
test_image_attrs.append(attrs)
test_image_cate.append(img['categoryid'])
# Sanity check
assert len(train_image_paths) == len(train_image_captions) == len(train_image_attrs) == len(train_image_cate)
assert len(val_image_paths) == len(val_image_captions) == len(val_image_attrs) == len(val_image_cate)
assert len(test_image_paths) == len(test_image_captions) == len(test_image_attrs) == len(test_image_cate)
print("# of training data: ", len(train_image_paths))
print("# of val data: ", len(val_image_paths))
print("# of test data: ", len(test_image_paths))
# Create word map
words = [w for w in word_freq.keys() if word_freq[w] > min_word_freq] # len(word_freq) = 27929
word_map = {k: v + 1 for v, k in enumerate(words)} # len(words) = 9486
word_map['<unk>'] = len(word_map) + 1 # 9487
word_map['<start>'] = len(word_map) + 1 # 9488
word_map['<end>'] = len(word_map) + 1 # 9489
word_map['<pad>'] = 0 # 0
# Create a base/root name for all output files
base_filename = 'fc' + '_' + str(captions_per_image) + '_cap_per_img_' + str(min_word_freq) + '_min_word_freq' # 'fc_5_cap_per_img_5_min_word_freq'
# Save word map to a JSON
with open(os.path.join(output_folder, 'DESC_WORDMAP_' + base_filename + '.json'), 'w') as j:
json.dump(word_map, j)
# Save word freq to a JSON
word_freq = dict(word_freq)
word_freq_sorted = {k: v for k, v in sorted(word_freq.items(), key=lambda item: item[1])}
with open(os.path.join(output_folder, 'DESC_WORDFREQ_' + base_filename + '.json'), 'w') as j:
json.dump(word_freq_sorted, j)
# Sample captions for each image, save images to HDF5 file, and captions and their lengths to JSON files
seed(123)
for impaths, imcaps, imattrs, imcate, split in [(train_image_paths, train_image_captions, train_image_attrs, train_image_cate, 'TRAIN'),
(val_image_paths, val_image_captions, val_image_attrs, val_image_cate, 'VAL'),
(test_image_paths, test_image_captions, test_image_attrs, test_image_cate, 'TEST')]:
with h5py.File(os.path.join(output_folder, split + '_DESC_IMAGES_' + base_filename + '.hdf5'), 'a') as h:
# Make a note of the number of captions we are sampling per image
h.attrs['captions_per_image'] = captions_per_image
# Create dataset inside HDF5 file to store images
images = h.create_dataset('images', (len(impaths), 3, 256, 256), dtype='uint8')
print("\nReading %s images and captions, storing to file...\n" % split)
enc_captions = []
enc_attrs = []
enc_cate = []
caplens = []
for i, img in enumerate(tqdm(impaths)):
# Read images
try:
img = imread(impaths[i])
# Sample captions
if len(imcaps[i]) < captions_per_image:
captions = imcaps[i] + [choice(imcaps[i]) for _ in range(
captions_per_image - len(imcaps[i]))] # choice(imcaps[i]): get one cap from imcaps[i]
attrs = imattrs[i] # choice(imattrs[i]): get one attr from imattrs[i]
else:
captions = sample(imcaps[i], k=captions_per_image) # if k = len(imcaps[i]), sample works like re-order
attrs = imattrs[i] # if k = len(imattrs[i]), sample works like re-order
enc_cate.append(imcate[i])
except:
img = imread(impaths[i-1])
# Sample captions
if len(imcaps[i-1]) < captions_per_image:
captions = imcaps[i-1] + [choice(imcaps[i-1]) for _ in range(
captions_per_image - len(imcaps[i-1]))] # choice(imcaps[i]): get one cap from imcaps[i]
attrs = imattrs[i-1] # choice(imattrs[i]): get one attr from imattrs[i]
else:
captions = sample(imcaps[i-1],
k=captions_per_image) # if k = len(imcaps[i]), sample works like re-order
attrs = imattrs[i-1] # if k = len(imattrs[i]), sample works like re-order
enc_cate.append([imcate[i-1]])
if len(img.shape) == 2:
img = img[:, :, np.newaxis]
img = np.concatenate([img, img, img], axis=2)
img = imresize(img, (256, 256))
img = img.transpose(2, 0, 1)
assert img.shape == (3, 256, 256)
assert np.max(img) <= 255
# Save image to HDF5 file
images[i] = img
# Sanity check
assert len(captions) == captions_per_image
for j, c in enumerate(captions):
# Encode captions
enc_c = [word_map['<start>']] + [word_map.get(word, word_map['<unk>']) for word in c] + [
word_map['<end>']] + [word_map['<pad>']] * (max_len - len(c))
c_len = len(c) + 2
enc_captions.append(enc_c)
caplens.append(c_len)
enc_attrs.append(attrs)
# Sanity check
assert images.shape[0] * captions_per_image == len(enc_captions) == len(caplens)
# Save encoded captions and their lengths to JSON files
with open(os.path.join(output_folder, split + '_DESC_CAPTIONS_' + base_filename + '.json'), 'w') as j:
json.dump(enc_captions, j)
with open(os.path.join(output_folder, split + '_DESC_CAPLENS_' + base_filename + '.json'), 'w') as j:
json.dump(caplens, j)
with open(os.path.join(output_folder, split + '_DESC_ATTRS_' + base_filename + '.json'), 'w') as j:
json.dump(enc_attrs, j)
with open(os.path.join(output_folder, split + '_DESC_CATES_' + base_filename + '.json'), 'w') as j:
json.dump(enc_cate, j)
def create_description_all_views_input_files(data_json_path, image_folder, captions_per_image, min_word_freq, output_folder,
max_len=50):
"""
Creates input files for training, validation, and test data.
:param data_json_path: path of JSON file with splits and captions
:param image_folder: folder with downloaded images
:param captions_per_image: number of captions to sample per image
:param min_word_freq: words occuring less frequently than this threshold are binned as <unk>s
:param output_folder: folder to save files
:param max_len: don't sample captions longer than this length
"""
# Read JSON
with open(data_json_path, 'r') as j:
data = json.load(j)
# Read image paths and captions for each image
train_image_paths = []
train_image_captions = []
train_image_attrs = []
train_image_cate = []
val_image_paths = []
val_image_captions = []
val_image_attrs = []
val_image_cate = []
test_image_paths = []
test_image_captions = []
test_image_attrs = []
test_image_cate = []
word_freq = Counter()
for ii, img in enumerate(data):
for ppp in img['images']:
for kkk in ppp.keys():
color_name = ppp['color'].replace('/', '').split()
if len(color_name) == 0:
continue
path = os.path.join(image_folder, str(img['id']), intersect_names(color_name), kkk + '.jpeg')
if not os.path.exists(path):
continue
captions = []
attrs = img['attrid']
tokens = img['description'].split()
tokens = [x.lower() for x in tokens]
word_freq.update(tokens)
if len(tokens) <= max_len:
captions.append(tokens)
if len(captions) == 0:
continue
if ii < len(data)/10*8:
train_image_paths.append(path)
train_image_captions.append(captions)
train_image_attrs.append(attrs)
train_image_cate.append(img['categoryid'])
elif ii > len(data)/10*9:
val_image_paths.append(path)
val_image_captions.append(captions)
val_image_attrs.append(attrs)
val_image_cate.append(img['categoryid'])
else:
test_image_paths.append(path)
test_image_captions.append(captions)
test_image_attrs.append(attrs)
test_image_cate.append(img['categoryid'])
# Sanity check
assert len(train_image_paths) == len(train_image_captions) == len(train_image_attrs) == len(train_image_cate)
assert len(val_image_paths) == len(val_image_captions) == len(val_image_attrs) == len(val_image_cate)
assert len(test_image_paths) == len(test_image_captions) == len(test_image_attrs) == len(test_image_cate)
print("# of training data: ", len(train_image_paths))
print("# of val data: ", len(val_image_paths))
print("# of test data: ", len(test_image_paths))
# Create word map
words = [w for w in word_freq.keys() if word_freq[w] > min_word_freq] # len(word_freq) = 27929
pdb.set_trace()
word_map = {k: v + 1 for v, k in enumerate(words)} # len(words) = 9486
word_map['<unk>'] = len(word_map) + 1 # 9487
word_map['<start>'] = len(word_map) + 1 # 9488
word_map['<end>'] = len(word_map) + 1 # 9489
word_map['<pad>'] = 0 # 0
# Create a base/root name for all output files
base_filename = 'fc' + '_' + str(captions_per_image) + '_cap_per_img_' + str(min_word_freq) + '_min_word_freq' # 'fc_5_cap_per_img_5_min_word_freq'
# Save word map to a JSON
with open(os.path.join(output_folder, 'DESC_WORDMAP_' + base_filename + '.json'), 'w') as j:
json.dump(word_map, j)
# Save word freq to a JSON
word_freq = dict(word_freq)
word_freq_sorted = {k: v for k, v in sorted(word_freq.items(), key=lambda item: item[1])}
with open(os.path.join(output_folder, 'DESC_WORDFREQ_' + base_filename + '.json'), 'w') as j:
json.dump(word_freq_sorted, j)
# Sample captions for each image, save images to HDF5 file, and captions and their lengths to JSON files
seed(123)
for impaths, imcaps, imattrs, imcate, split in [(train_image_paths, train_image_captions, train_image_attrs, train_image_cate, 'TRAIN'),
(val_image_paths, val_image_captions, val_image_attrs, val_image_cate, 'VAL'),
(test_image_paths, test_image_captions, test_image_attrs, test_image_cate, 'TEST')]:
with h5py.File(os.path.join(output_folder, split + '_DESC_IMAGES_' + base_filename + '.hdf5'), 'a') as h:
# Make a note of the number of captions we are sampling per image
h.attrs['captions_per_image'] = captions_per_image
# Create dataset inside HDF5 file to store images
images = h.create_dataset('images', (len(impaths), 3, 256, 256), dtype='uint8')
print("\nReading %s images and captions, storing to file...\n" % split)
enc_captions = []
enc_attrs = []
enc_cate = []
caplens = []
for i, img in enumerate(tqdm(impaths)):
# if i < 116730:
# continue
# Read images
try:
img = imread(impaths[i])
# Sample captions
if len(imcaps[i]) < captions_per_image:
captions = imcaps[i] + [choice(imcaps[i]) for _ in range(
captions_per_image - len(imcaps[i]))] # choice(imcaps[i]): get one cap from imcaps[i]
attrs = imattrs[i] # choice(imattrs[i]): get one attr from imattrs[i]
else:
captions = sample(imcaps[i], k=captions_per_image) # if k = len(imcaps[i]), sample works like re-order
attrs = imattrs[i] # if k = len(imattrs[i]), sample works like re-order
enc_cate.append(imcate[i])
except:
img, captions, attrs, cate = random_one(impaths, imcaps, imattrs, imcate)
enc_cate.append([cate])
if len(img.shape) == 2:
img = img[:, :, np.newaxis]
img = np.concatenate([img, img, img], axis=2)
img = imresize(img, (256, 256))
img = img.transpose(2, 0, 1)
assert img.shape == (3, 256, 256)
assert np.max(img) <= 255
# Save image to HDF5 file
images[i] = img
# Sanity check
assert len(captions) == captions_per_image
for j, c in enumerate(captions):
# Encode captions
enc_c = [word_map['<start>']] + [word_map.get(word, word_map['<unk>']) for word in c] + [
word_map['<end>']] + [word_map['<pad>']] * (max_len - len(c))
c_len = len(c) + 2
enc_captions.append(enc_c)
caplens.append(c_len)
enc_attrs.append(attrs)
# Sanity check
assert images.shape[0] * captions_per_image == len(enc_captions) == len(caplens)
# Save encoded captions and their lengths to JSON files
with open(os.path.join(output_folder, split + '_DESC_CAPTIONS_' + base_filename + '.json'), 'w') as j:
json.dump(enc_captions, j)
with open(os.path.join(output_folder, split + '_DESC_CAPLENS_' + base_filename + '.json'), 'w') as j:
json.dump(caplens, j)
with open(os.path.join(output_folder, split + '_DESC_ATTRS_' + base_filename + '.json'), 'w') as j:
json.dump(enc_attrs, j)
with open(os.path.join(output_folder, split + '_DESC_CATES_' + base_filename + '.json'), 'w') as j:
json.dump(enc_cate, j)
def init_embedding(embeddings):
"""
Fills embedding tensor with values from the uniform distribution.
:param embeddings: embedding tensor
"""
bias = np.sqrt(3.0 / embeddings.size(1))
torch.nn.init.uniform_(embeddings, -bias, bias)
def load_embeddings(emb_file, word_map):
"""
Creates an embedding tensor for the specified word map, for loading into the model.
:param emb_file: file containing embeddings (stored in GloVe format)
:param word_map: word map
:return: embeddings in the same order as the words in the word map, dimension of embeddings
"""
# Find embedding dimension
with open(emb_file, 'r') as f:
emb_dim = len(f.readline().split(' ')) - 1
vocab = set(word_map.keys())
# Create tensor to hold embeddings, initialize
embeddings = torch.FloatTensor(len(vocab), emb_dim)
init_embedding(embeddings)
# Read embedding file
print("\nLoading embeddings...")
for line in open(emb_file, 'r'):
line = line.split(' ')
emb_word = line[0]
embedding = list(map(lambda t: float(t), filter(lambda n: n and not n.isspace(), line[1:])))
# Ignore word if not in train_vocab
if emb_word not in vocab:
continue
embeddings[word_map[emb_word]] = torch.FloatTensor(embedding)
return embeddings, emb_dim
def clip_gradient(optimizer, grad_clip):
"""
Clips gradients computed during backpropagation to avoid explosion of gradients.
:param optimizer: optimizer with the gradients to be clipped
:param grad_clip: clip value
"""
for group in optimizer.param_groups:
for param in group['params']:
if param.grad is not None:
param.grad.data.clamp_(-grad_clip, grad_clip)
def save_checkpoint(model_folder, epoch, epochs_since_improvement, model, optimizer, cider, is_best):
"""
Saves model checkpoint.
:param epoch: epoch number
:param epochs_since_improvement: number of epochs since last improvement in cider score
:param model: model
:param optimizer: optimizer to update weights
:param cider: validation cider score for this epoch
:param is_best: is this checkpoint the best so far?
"""
if torch.cuda.device_count() > 1:
state = {'epoch': epoch,
'epochs_since_improvement': epochs_since_improvement,
'cider': cider,
'model': model.module.state_dict(), # save model.module for > 1 gpus
'optimizer': optimizer # or use .state_dict()?
}
else:
state = {'epoch': epoch,
'epochs_since_improvement': epochs_since_improvement,
'cider': cider,
'model': model.state_dict(),
'optimizer': optimizer
}
filename = 'checkpoint_' + str(epoch) + '.pth.tar'
torch.save(state, os.path.join(model_folder, filename))
# If this checkpoint is the best so far, store a copy so it doesn't get overwritten by a worse checkpoint
if is_best:
filename = 'checkpoint.pth.tar'
torch.save(state, os.path.join(model_folder, 'BEST_' + filename))
class AverageMeter(object):
"""
Keeps track of most recent, average, sum, and count of a metric.
"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def adjust_learning_rate(optimizer, shrink_factor):
"""
Shrinks learning rate by a specified factor.
:param optimizer: optimizer whose learning rate must be shrunk.
:param shrink_factor: factor in interval (0, 1) to multiply learning rate with.
"""
print("\nDECAYING learning rate.")
for param_group in optimizer.param_groups:
param_group['lr'] = param_group['lr'] * shrink_factor
print("The new learning rate is %f\n" % (optimizer.param_groups[0]['lr'],))
def accuracy(scores, targets, k):
"""
Computes top-k accuracy, from predicted and true labels.
:param scores: scores from the model
:param targets: true labels
:param k: k in top-k accuracy
:return: top-k accuracy
"""
batch_size = targets.batch_sizes.size(0)
_, ind = scores.data.topk(k, 1, True, True)
correct = ind.eq(targets.data.view(-1, 1).expand_as(ind))
correct_total = correct.view(-1).float().sum() # 0D tensor
return correct_total.item() * (100.0 / batch_size)
def break_down_description(desc):
"""
Break description into several lines to show them
:param desc: description
:return:
"""
words = desc.split()
len_s = len(words)
words_n = []
for i in range(len_s):
if i == int(len_s / 2.0):
words_n.append('\n')
words_n.append(words[i])
desc_n = " ".join(x for x in words_n)
return desc_n
def random_meta_data(file):
with open(file, 'r') as f:
data = json.load(f)
random.seed(30)
random.shuffle(data)
random.seed(50)
random.shuffle(data)
file_name = '/home/xuewyang/Xuewen/Research/data/FACAD/jsons/meta_random_130254.json'
with open(file_name, 'w') as f:
json.dump(data, fp=f, indent=4, ensure_ascii=False)
json_file = '/home/xuewyang/Xuewen/Research/data/FACAD/jsons/meta_130254.json'
random_meta_data(json_file)
def get_pos_combinations(tokens):
"""
tokens: [('Lounge', 'NN'), ('in', 'IN'), ('the', 'DT'), ('lap', 'NN'), ('of', 'IN'), ('luxury', 'NN'),
('with', 'IN'), ('this', 'DT'), ('short', 'JJ'), ('cashmere', 'NN'), ('robe', 'NN'), ('featuring', 'VBG'),
('large', 'JJ'), ('patch', 'NN'), ('pockets—so', 'VBD'), ('even', 'RB'), ('your', 'PRP$'), ('hands', 'NNS'),
('can', 'MD'), ('experience', 'VB'), ('superlative', 'JJ'), ('comfort', 'NN'), ('.', '.')]
return: [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0]
"""
pos_tags = nltk.pos_tag(tokens)
attr_tokens = set()
prev = None # previous pos
result = []
first = ['JJ', 'JJR', 'JJS', 'VBD', 'VBG', 'VBN', 'NN', 'NNP', 'NNPS', 'NNS']
second = ['NN', 'NNP', 'NNPS', 'NNS']
for i, pos in enumerate(pos_tags):
if prev in first and pos[1] in second:
if len(result) != 0:
result.pop()
result.append(1)
result.append(1)
attr_tokens.add(tokens[i-1])
attr_tokens.add(tokens[i])
else:
result.append(0)
prev = pos[1]
return result, attr_tokens
# text = word_tokenize("A plunge neck provides a dramatic update for this sleek and shimmery long-sleeve bodysuit.")
# print(get_pos_combinations(text))
def calculate_semantic_loss(scores, targets, pretrained, criterion_se):
values, indices = torch.max(scores, dim=-1)
output = pretrained(indices, 1)
semantic_loss = criterion_se(output, targets.reshape(indices.shape[0]))
# student = F.log_softmax(output1, 1)
# output2 = pretrained(targets, 1)
# teacher = F.softmax(output2, 1)
# semantic_loss = criterion_se(student, teacher)
return semantic_loss
# def calculate_semantic_loss(h, targets, pretrained, criterion_se):
# values, indices = torch.max(scores, dim=-1)
# output = pretrained(indices, 1)
# new_scores = F.softmax(output, 1)
# semantic_loss = criterion_se(new_scores, targets.reshape(indices.shape[0]))
# # student = F.log_softmax(output1, 1)
# # output2 = pretrained(targets, 1)
# # teacher = F.softmax(output2, 1)
# # semantic_loss = criterion_se(student, teacher)
# return semantic_loss
def encode_onehot(labels):
pdb.set_trace()
classes = set(labels)
classes_dict = {c: np.identity(len(classes))[i, :] for i, c in
enumerate(classes)}
labels_onehot = np.array(list(map(classes_dict.get, labels)),
dtype=np.int32)
return labels_onehot
def load_data(path):
"""Load citation network dataset (cora only for now)"""
pdb.set_trace()
idx_features_labels = np.genfromtxt("{}{}.content".format(path, dataset),
dtype=np.dtype(str))
features = sp.csr_matrix(idx_features_labels[:, 1:-1], dtype=np.float32)
labels = encode_onehot(idx_features_labels[:, -1])
# build graph
idx = np.array(idx_features_labels[:, 0], dtype=np.int32)
idx_map = {j: i for i, j in enumerate(idx)}
edges_unordered = np.genfromtxt("{}{}.cites".format(path, dataset),
dtype=np.int32)
edges = np.array(list(map(idx_map.get, edges_unordered.flatten())),
dtype=np.int32).reshape(edges_unordered.shape)
adj = sp.coo_matrix((np.ones(edges.shape[0]), (edges[:, 0], edges[:, 1])),
shape=(labels.shape[0], labels.shape[0]),
dtype=np.float32)
# build symmetric adjacency matrix
adj = adj + adj.T.multiply(adj.T > adj) - adj.multiply(adj.T > adj)
features = normalize(features)
adj = normalize(adj + sp.eye(adj.shape[0]))
idx_train = range(140)
idx_val = range(200, 500)
idx_test = range(500, 1500)
features = torch.FloatTensor(np.array(features.todense()))
labels = torch.LongTensor(np.where(labels)[1])
adj = sparse_mx_to_torch_sparse_tensor(adj)
idx_train = torch.LongTensor(idx_train)
idx_val = torch.LongTensor(idx_val)
idx_test = torch.LongTensor(idx_test)
return adj, features, labels, idx_train, idx_val, idx_test
def normalize(mx):
"""Row-normalize sparse matrix"""
rowsum = np.array(mx.sum(1))
r_inv = np.power(rowsum, -1).flatten()
r_inv[np.isinf(r_inv)] = 0.
r_mat_inv = sp.diags(r_inv)
mx = r_mat_inv.dot(mx)
return mx
# def accuracy(output, labels):
# preds = output.max(1)[1].type_as(labels)
# correct = preds.eq(labels).double()
# correct = correct.sum()
# return correct / len(labels)
def sparse_mx_to_torch_sparse_tensor(sparse_mx):
"""Convert a scipy sparse matrix to a torch sparse tensor."""
sparse_mx = sparse_mx.tocoo().astype(np.float32)
indices = torch.from_numpy(
np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64))
values = torch.from_numpy(sparse_mx.data)
shape = torch.Size(sparse_mx.shape)
return torch.sparse.FloatTensor(indices, values, shape)
def preprocess_file(data_json_path, new_json_file):
# Read JSON
with open(data_json_path, 'r') as j:
data = json.load(j)
new_data = []
for ii, img in enumerate(data):
if len(img['images']) == 0:
continue
else:
if img['detail_info'] is not None and len(img['detail_info']) != 0:
try: # \([^)]*\)
tokens = word_tokenize(re.sub(r'[^A-Za-z0-9]+', ' ', img['detail_info'].split('\n')[1]))
except IndexError:
continue
else:
continue
if len(img['description']) != 0:
tokens = word_tokenize(re.sub(r'[^A-Za-z0-9]+', ' ', img['description']))
tokens = [x.lower() for x in tokens]
tokens = [wordnet_lemmatizer.lemmatize(x, pos='n') for x in tokens]
tokens = [filter_titles(x) for x in tokens]
img['description'] = ' '.join(tokens)
title_tokens = word_tokenize(re.sub(r'[^A-Za-z0-9]+', ' ', img['title']))
title_tokens = [x.lower() for x in title_tokens]
title_tokens = [wordnet_lemmatizer.lemmatize(x, pos='n') for x in title_tokens]
title_tokens = [filter_titles(x) for x in title_tokens]
img['title'] = ' '.join(title_tokens)
new_data.append(img)
print(len(new_data))
with open(new_json_file, 'w') as f:
json.dump(new_data, fp=f, indent=4, ensure_ascii=False)
# new_json_file = '/home/xuewyang/Xuewen/Research/Fashion/Captioning/data/jsons/meta_random_94026_preprocess.json'
# data_json_path='/home/xuewyang/Xuewen/Research/Fashion/Captioning/data/jsons/meta_random_94026.json'
# preprocess_file(data_json_path, new_json_file)
def correct_file():
file = os.path.join('/home/xuewyang/Xuewen/Research/Fashion/Captioning/data/hdf5_all_view', 'VAL_DESC_CATES_fc_1_cap_per_img_0_min_word_freq' + '.json')
with open(file, 'r') as j:
cates = json.load(j)
new_cates = []
for cc in cates:
if type(cc) is list:
new_cates.append(cc[0])
else:
new_cates.append(cc)
new_file = os.path.join('/home/xuewyang/Xuewen/Research/Fashion/Captioning/data/hdf5_all_view', 'VAL_DESC_CATES_fc_1_cap_per_img_0_min_word_freq2' + '.json')
with open(new_file, 'w') as f:
json.dump(new_cates, f)
# correct_file()
def count_cate_attr():
# count categories and attributes for all files
cate_dict = {}
attr_dict = {}
file_c_train = '/home/xuewyang/Xuewen/Research/Fashion/Captioning/data/hdf5_all_view/TRAIN_DESC_CATES_fc_1_cap_per_img_0_min_word_freq.json'
file_a_train = '/home/xuewyang/Xuewen/Research/Fashion/Captioning/data/hdf5_all_view/TRAIN_DESC_ATTRS_fc_1_cap_per_img_0_min_word_freq.json'
file_c_test = '/home/xuewyang/Xuewen/Research/Fashion/Captioning/data/hdf5_all_view/TEST_DESC_CATES_fc_1_cap_per_img_0_min_word_freq.json'
file_a_test = '/home/xuewyang/Xuewen/Research/Fashion/Captioning/data/hdf5_all_view/TEST_DESC_ATTRS_fc_1_cap_per_img_0_min_word_freq.json'
file_c_val = '/home/xuewyang/Xuewen/Research/Fashion/Captioning/data/hdf5_all_view/VAL_DESC_CATES_fc_1_cap_per_img_0_min_word_freq.json'
file_a_val = '/home/xuewyang/Xuewen/Research/Fashion/Captioning/data/hdf5_all_view/VAL_DESC_ATTRS_fc_1_cap_per_img_0_min_word_freq.json'
with open(file_c_train, 'r') as f:
cate_train = json.load(f)
for cc in cate_train:
if cc in cate_dict.keys():
cate_dict[cc] += 1
else:
cate_dict[cc] = 0
with open(file_c_test, 'r') as f:
cate_test = json.load(f)
for cc in cate_test:
if cc in cate_dict.keys():
cate_dict[cc] += 1
else:
cate_dict[cc] = 0
with open(file_c_val, 'r') as f:
cate_val = json.load(f)
for cc in cate_val:
if cc in cate_dict.keys():
cate_dict[cc] += 1
else:
cate_dict[cc] = 0
with open(file_a_train, 'r') as f:
attr_train = json.load(f)
for aa in attr_train:
for cc in aa:
# pdb.set_trace()
if cc in attr_dict.keys():
attr_dict[cc] += 1