-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathprogram33_GMs_STL10.py
4027 lines (2816 loc) · 124 KB
/
program33_GMs_STL10.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 print_function
from __future__ import absolute_import
import tensorflow as tf
print(tf.__version__)
import sys
import os, tarfile, errno
import numpy as np
import matplotlib.pyplot as plt
if sys.version_info >= (3, 0, 0):
import urllib.request as urllib # ugly but works
else:
import urllib
try:
from imageio import imsave
except:
from scipy.misc import imsave
# sys.version_info
print(sys.version_info)
# image shape
HEIGHT = 96
WIDTH = 96
DEPTH = 3
# size of a single image in bytes
SIZE = HEIGHT * WIDTH * DEPTH
# path to the directory with the data
DATA_DIR = './data'
# url of the binary data
DATA_URL = 'http://ai.stanford.edu/~acoates/stl10/stl10_binary.tar.gz'
# use: https://cs.stanford.edu/~acoates/stl10/
# path to the binary train file with image data
DATA_PATH = './data/stl10_binary/train_X.bin'
# path to the binary train file with labels
LABEL_PATH = './data/stl10_binary/train_y.bin'
def read_labels(path_to_labels):
"""
:param path_to_labels: path to the binary file containing labels from the STL-10 dataset
:return: an array containing the labels
"""
with open(path_to_labels, 'rb') as f:
labels = np.fromfile(f, dtype=np.uint8)
return labels
def read_all_images(path_to_data):
"""
:param path_to_data: the file containing the binary images from the STL-10 dataset
:return: an array containing all the images
"""
with open(path_to_data, 'rb') as f:
# read whole file in uint8 chunks
# read whole file in uint8 chunks
everything = np.fromfile(f, dtype=np.uint8)
# We force the data into 3x96x96 chunks, since the
# images are stored in "column-major order", meaning
# that "the first 96*96 values are the red channel,
# the next 96*96 are green, and the last are blue."
# The -1 is since the size of the pictures depends
# on the input file, and this way numpy determines
# the size on its own.
# We force the data into 3x96x96 chunks.
images = np.reshape(everything, (-1, 3, 96, 96))
# Now transpose the images into a standard image format
# readable by, for example, matplotlib.imshow
# You might want to comment this line or reverse the shuffle
# if you will use a learning algorithm like CNN, since they like
# their channels separated.
# Transpose the images
images = np.transpose(images, (0, 3, 2, 1))
return images
def read_single_image(image_file):
"""
CAREFUL! - this method uses a file as input instead of the path - so the
position of the reader will be remembered outside of context of this method.
:param image_file: the open file containing the images
:return: a single image
"""
# read a single image, count determines the number of uint8's to read
image = np.fromfile(image_file, dtype=np.uint8, count=SIZE)
# force into image matrix
image = np.reshape(image, (3, 96, 96))
# transpose to standard format
# You might want to comment this line or reverse the shuffle
# if you will use a learning algorithm like CNN, since they like
# their channels separated.
# transpose to standard format
image = np.transpose(image, (2, 1, 0))
return image
def plot_image(image):
"""
:param image: the image to be plotted in a 3-D matrix format
"""
plt.imshow(image)
plt.show()
def save_image(image, name):
imsave("%s.png" % name, image, format="png")
def download_and_extract():
"""
Download and extract the STL-10 dataset
"""
dest_directory = DATA_DIR
if not os.path.exists(dest_directory):
os.makedirs(dest_directory)
filename = DATA_URL.split('/')[-1]
filepath = os.path.join(dest_directory, filename)
if not os.path.exists(filepath):
def _progress(count, block_size, total_size):
sys.stdout.write('\rDownloading %s %.2f%%' % (filename,
float(count * block_size) / float(total_size) * 100.0))
sys.stdout.flush()
filepath, _ = urllib.urlretrieve(DATA_URL, filepath, reporthook=_progress)
print('Downloaded', filename)
tarfile.open(filepath, 'r:gz').extractall(dest_directory)
def save_images(images, labels):
#print("Saving images to disk")
#print("Saving images to disk")
print("Save images to disk")
i = 0
for image in images:
label = labels[i]
directory = './img/' + str(label) + '/'
try:
os.makedirs(directory, exist_ok=True)
except OSError as exc:
if exc.errno == errno.EEXIST:
pass
filename = directory + str(i)
print(filename)
save_image(image, filename)
i = i + 1
if __name__ == "__main__":
# download the data
# if needed, download the data
download_and_extract()
# test to check if the image is read correctly
with open(DATA_PATH) as f:
image = read_single_image(f)
plot_image(image)
# test to check if the whole dataset is read correctly
images = read_all_images(DATA_PATH)
print(images.shape)
labels = read_labels(LABEL_PATH)
print(labels.shape)
# save images to disk
#save_images(images, labels)
import os
import tempfile
import subprocess
import numpy as np
import matplotlib.pyplot as plt
#g1 = [[0.9040965370370371, 0.74461, 0.5155018796296296, 0.6067401574074074, 0.5356445370370371, 0.6033470277777778, 0.8600094629629629, 0.5770984814814815, 0.7734221574074074, 0.6068066759259259], [0.9612778981481482, 0.6687222777777778, 0.5260006481481482, 0.5885034444444445, 0.6129901111111111, 0.6673065462962963, 0.7511156203703704, 0.5420412592592593, 0.85680575, 0.6509693703703704], [0.9332610555555555, 0.7233965462962962, 0.48850834259259257, 0.5622162962962962, 0.6895320833333334, 0.6664632407407407, 0.5627155, 0.5813406481481481, 0.8163357314814814, 0.6714644166666667]]
#g2 = [[0.9621442407407408, 0.74461, 0.5344123518518518, 0.6354489166666666, 0.7596060092592593, 0.6634529444444445, 0.8600094629629629, 0.6152494722222223, 0.8769023425925926, 0.6864652407407408], [0.9612778981481482, 0.704607611111111, 0.5458616759259258, 0.6221637685185185, 0.8161331388888889, 0.6673065462962963, 0.7942182962962963, 0.6073334722222222, 0.8597013055555556, 0.6749123333333333], [0.962578675925926, 0.7233965462962962, 0.5377918888888888, 0.647348361111111, 0.7773921296296297, 0.69790375, 0.8423532499999999, 0.5882901481481482, 0.872712101851852, 0.6799068518518518]]
#g3 = [[3.69779109954834, 3.76554012298584, 3.775956630706787, 3.870365619659424, 3.716261386871338, 3.994929790496826, 3.925158977508545, 4.060425758361816, 3.703930377960205, 3.95566463470459], [3.7598299980163574, 3.8211655616760254, 3.7877893447875977, 3.7814974784851074, 3.9992785453796387, 3.978555202484131, 3.631882667541504, 4.439399242401123, 3.957340717315674, 3.800053596496582], [3.9581727981567383, 3.675556182861328, 4.179351329803467, 3.965294361114502, 3.7168478965759277, 3.8895392417907715, 4.040830135345459, 6.364235877990723, 4.151716232299805, 3.7189888954162598]]
#g1 = [[0.7889737216613737, 0.4376289340238787, 0.4409219517892701, 0.4595648499901688, 0.5545440423978997, 0.5206263764533741, 0.7586791255690835, 0.48162266355712213, 0.6732045322341802, 0.4389286757081857], [0.7660555562078939, 0.48029352444285156, 0.4568258605673837, 0.45700917501541244, 0.5736049690514815, 0.5269126901596681, 0.5820140071785596, 0.43289228383491585, 0.703710630924051, 0.449899486301065]]
#g2 = [[0.93355385566179, 0.5170235999151753, 0.4662169285927492, 0.5251649760532959, 0.6554190394805207, 0.6006760280963213, 0.8124006550390338, 0.48162266355712213, 0.7996720828527245, 0.5187196519454024], [0.775196439320086, 0.5117902979187909, 0.4857918543069639, 0.4945914277633235, 0.6793749127030748, 0.5535922006444878, 0.674084747530882, 0.4829471835856364, 0.781411717399264, 0.5201429516294148]]
#g3 = [[5.302708148956299, 6.873373985290527, 8.551833629608154, 4.790539741516113, 9.20945405960083, 7.877237796783447, 8.614120483398438, 8.584418296813965, 8.528287410736084, 8.6995530128479], [9.554312229156494, 4.544234275817871, 4.635648727416992, 4.945080280303955, 4.576082229614258, 5.378477573394775, 5.201163291931152, 4.78830099105835, 4.979913234710693, 4.77419376373291]]
#g1 = [[0.0321416857986225, 0.20104712041884817, 0.019455894476504535, 0.011900826446280993, 0.022086698533047632, 0.04468016714882674, 0.011269472986410341, 0.037815126050420166, 0.10298273155416014, 0.0], [0.04131424853610931, 0.1913848744212151, 0.00895819508958195, 0.017110891740704178, 0.022086698533047632, 0.09772798008092128, 0.007637390004980906, 0.07848484848484849, 0.1090909090909091, 0.0003318951211417192], [0.029223444426202592, 0.06714701824313966, 0.03366563163915673, 0.014151719598486094, 0.02045529528208512, 0.04526349822179115, 0.008959681433549029, 0.07848484848484849, 0.1090909090909091, 0.0003318951211417192]]
#g2 = [[0.13096904650801058, 0.35081374321880654, 0.06159246848571885, 0.30612722170252576, 0.03568505483712556, 0.33062812673707614, 0.04782820888238165, 0.27070457354758964, 0.35906172192373215, 0.23543457497612225], [0.12003722084367247, 0.30970504281636535, 0.055332153771915714, 0.13032440056417488, 0.033753891528756345, 0.2395806699053951, 0.0522642428177244, 0.3875333196637277, 0.2628873141586772, 0.18817852834740653], [0.28604802076573654, 0.3537072043688301, 0.11930355791067372, 0.2977812816758644, 0.03504175536269854, 0.4955348660459813, 0.05542051531356344, 0.3875333196637277, 0.2628873141586772, 0.18817852834740653]]
#g3 = [[7.766354084014893, 6.104092597961426, 8.336114883422852, 6.420071125030518, 6.815962791442871, 5.024633407592773, 6.99282169342041, 4.712412357330322, 7.170934677124023, 7.1436285972595215], [7.420742511749268, 5.551357269287109, 5.628402233123779, 6.542465686798096, 6.72459602355957, 6.300387382507324, 7.186479568481445, 6.405231952667236, 6.526792049407959, 4.3767595291137695], [5.363500118255615, 6.78480863571167, 6.5532684326171875, 7.049682140350342, 4.75616455078125, 6.0572052001953125, 6.733193397521973, 6.405231952667236, 6.526792049407959, 4.3767595291137695]]
#g1 = [[0.8322690647579725, 0.46508818965244675, 0.4554794384184438, 0.46258671669986035, 0.5596197878676594, 0.5196174763431345, 0.4960934597989699, 0.4145508814661052, 0.6760784715597402, 0.4410497488078411], [0.8079101918260816, 0.46472301049649256, 0.46522895678705267, 0.4806114442137722, 0.5461513184154637, 0.5166404570479255, 0.5893097072368136, 0.4432133749487719, 0.7390971882169581, 0.45779990708967033], [0.8869100692278536, 0.47937692396718956, 0.4679810410710097, 0.43955356472805, 0.5039657981286474, 0.5058497120286687, 0.555222209456331, 0.4432133749487719, 0.7390971882169581, 0.45779990708967033]]
#g2 = [[0.8994543282452314, 0.50110293822674, 0.47136620220671804, 0.5072057519442077, 0.729771268038981, 0.5376782378981044, 0.7162969839053682, 0.46568174567064347, 0.795980885425057, 0.502347495496864], [0.9247059927964847, 0.5554989020025276, 0.4742671741781292, 0.5158302646403715, 0.6092528939240605, 0.5507575431405519, 0.795656957149063, 0.48186382479469303, 0.7900468243678925, 0.514806566514857], [0.9454696185574382, 0.48467452815862666, 0.5146056300735227, 0.5381002639846892, 0.6532587673252515, 0.5587824122581884, 0.7986278014575245, 0.48186382479469303, 0.7900468243678925, 0.514806566514857]]
#g3 = [[7.816967964172363, 7.423698902130127, 4.944567680358887, 5.794970989227295, 6.627023220062256, 6.498100757598877, 6.7436909675598145, 6.511788368225098, 5.947117805480957, 7.172915935516357], [6.732392311096191, 6.878643035888672, 6.776483058929443, 4.586198329925537, 8.029012680053711, 6.286039352416992, 5.112016201019287, 7.594101428985596, 8.815820217132568, 6.8603515625], [6.7368292808532715, 7.183847427368164, 6.407506465911865, 8.1144118309021, 5.538482666015625, 7.131941318511963, 8.118283748626709, 7.594101428985596, 8.815820217132568, 6.8603515625]]
#g1 = np.mean(g1, axis=0)
#g2 = np.mean(g2, axis=0)
#g3 = np.mean(g3, axis=0)
# This is also for manualseed = None:
#g1 = [0.9271919444444445, 0.5885791851851851, 0.5393023240740741, 0.5128948611111112, 0.669631712962963, 0.6479999444444444, 0.6850078611111112, 0.5864626481481482, 0.8149177685185185, 0.643201712962963]
#g2 = [0.9590519166666667, 0.7176374351851852, 0.5483709814814816, 0.6214027777777777, 0.7848986296296296, 0.6873968611111112, 0.9012428240740741, 0.5987799074074074, 0.8671639166666667, 0.6892931388888888]
#g3 = [5.915262699127197, 4.76083517074585, 4.176671504974365, 6.598055362701416, 6.626327037811279, 4.304831027984619, 4.264116287231445, 6.072173118591309, 5.856869220733643, 4.278533458709717]
# This is for manualseed = None:
g1 = [0.09730586370839936, 0.14985835694050992, 0.020115416323165703, 0.018390804597701153, 0.025341451374033243, 0.029450261780104712, 0.013573911604039068, 0.09443354955498567, 0.17894581426251294, 0.0019766101136550816]
g2 = [0.15686274509803924, 0.36533775221756504, 0.11579892280071813, 0.22565922920892498, 0.03310932633994427, 0.43326133909287257, 0.04973183812774256, 0.28463530427276656, 0.230287859824781, 0.24048525214081828]
g3 = [6.9103169441223145, 4.698286056518555, 6.453959941864014, 6.823458671569824, 4.304108619689941, 6.651432514190674, 4.146397113800049, 6.246163845062256, 6.551299095153809, 4.729597568511963]
#print(g1.shape)
#print(g2.shape)
#print(g3.shape)
arrayLoop = ["plane", "car", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck"]
res21_total = g1
best_auc21_total = g2
res22_total = g3
plt.figure(1)
#plt.plot(np.array(arrayLoop), res21_total, 'b-o', arrayLoop, best_auc21_total, 'r-o')
#plt.xticks(range(len(arrayLoop)), arrayLoop)
#print(res21_total)
#res21_total = list(res21_total)
#best_auc21_total = list(best_auc21_total)
#res22_total = list(res22_total)
#res21_total.reverse()
#best_auc21_total.reverse()
#res22_total.reverse()
res21_total = np.array(res21_total)
best_auc21_total = np.array(best_auc21_total)
res22_total = np.array(res22_total)
plt.plot(range(len(arrayLoop)), res21_total, 'bo', range(len(arrayLoop)), best_auc21_total, 'rx')
plt.xticks(range(len(arrayLoop)), arrayLoop)
plt.plot(res21_total, 'b-o', best_auc21_total, 'r-x')
#plt.ylabel('AUC')
plt.xlabel('Anomaly Class')
#plt.ylabel('AUC')
plt.ylabel('F1 Score')
#plt.ylabel('F1 Score')
#plt.ylabel('AUPRC')
#plt.legend(['AUC', 'Best AUC'])
plt.legend(['F1 Score', 'Best F1 Score'])
#plt.legend(['F1 Score', 'Best F1 Score'])
#plt.legend(['AUPRC', 'Best AUPRC'])
plt.show()
plt.figure(2)
#plt.plot(np.array(arrayLoop), res22_total, 'b-o')
#plt.xticks(range(len(arrayLoop)), arrayLoop)
plt.plot(range(len(arrayLoop)), res22_total, 'bo')
plt.xticks(range(len(arrayLoop)), arrayLoop)
plt.plot(res22_total, 'b-o')
plt.ylabel('Avg Run Time (ms/batch)')
plt.xlabel('Anomaly Class')
plt.show()
import numpy as np
import sonnet as snt
import tarfile
import tensorflow as tf
from six.moves import cPickle
from six.moves import urllib
from six.moves import xrange
# CIFAR-10 Dataset
data_path = "https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz"
local_data_dir = tempfile.mkdtemp()
tf.gfile.MakeDirs(local_data_dir)
url = urllib.request.urlopen(data_path)
archive = tarfile.open(fileobj=url, mode='r|gz')
archive.extractall(local_data_dir)
url.close()
archive.close()
print('extracted data files to %s' % local_data_dir)
# https://github.com/deepmind/sonnet/blob/master/sonnet/examples/vqvae_example.ipynb
# we use: https://github.com/deepmind/sonnet/blob/master/sonnet/examples/vqvae_example.ipynb
def unpickle(filename):
with open(filename, 'rb') as fo:
return cPickle.load(fo, encoding='latin1')
def reshape_flattened_image_batch(flat_image_batch):
return flat_image_batch.reshape(-1, 3, 32, 32).transpose([0, 2, 3, 1]) # convert from NCHW to NHWC
def combine_batches(batch_list):
images = np.vstack([reshape_flattened_image_batch(batch['data'])
for batch in batch_list])
labels = np.vstack([np.array(batch['labels']) for batch in batch_list]).reshape(-1, 1)
return {'images': images, 'labels': labels}
train_data_dict = combine_batches([
unpickle(os.path.join(local_data_dir,
'cifar-10-batches-py/data_batch_%d' % i))
for i in range(1, 5)])
valid_data_dict = combine_batches([
unpickle(os.path.join(local_data_dir,
'cifar-10-batches-py/data_batch_5'))])
test_data_dict = combine_batches([
unpickle(os.path.join(local_data_dir, 'cifar-10-batches-py/test_batch'))])
def cast_and_normalise_images(data_dict):
"""Convert images to floating point with the range [0.5, 0.5]"""
images = data_dict['images']
data_dict['images'] = (tf.cast(images, tf.float32) / 255.0) - 0.5
return data_dict
data_variance = np.var(train_data_dict['images'] / 255.0)
def residual_stack(h, num_hiddens, num_residual_layers, num_residual_hiddens):
for i in range(num_residual_layers):
h_i = tf.nn.relu(h)
h_i = snt.Conv2D(
output_channels=num_residual_hiddens,
kernel_shape=(3, 3),
stride=(1, 1),
name="res3x3_%d" % i)(h_i)
h_i = tf.nn.relu(h_i)
h_i = snt.Conv2D(
output_channels=num_hiddens,
kernel_shape=(1, 1),
stride=(1, 1),
name="res1x1_%d" % i)(h_i)
h += h_i
return tf.nn.relu(h)
class Encoder(snt.AbstractModule):
def __init__(self, num_hiddens, num_residual_layers, num_residual_hiddens, name='encoder'):
super(Encoder, self).__init__(name=name)
self._num_hiddens = num_hiddens
self._num_residual_layers = num_residual_layers
self._num_residual_hiddens = num_residual_hiddens
def _build(self, x):
h = snt.Conv2D(
output_channels=self._num_hiddens / 2,
kernel_shape=(4, 4),
stride=(2, 2),
name="enc_1")(x)
h = tf.nn.relu(h)
h = snt.Conv2D(
output_channels=self._num_hiddens,
kernel_shape=(4, 4),
stride=(2, 2),
name="enc_2")(h)
h = tf.nn.relu(h)
h = snt.Conv2D(
output_channels=self._num_hiddens,
kernel_shape=(3, 3),
stride=(1, 1),
name="enc_3")(h)
h = residual_stack(
h,
self._num_hiddens,
self._num_residual_layers,
self._num_residual_hiddens)
return h
class Decoder(snt.AbstractModule):
def __init__(self, num_hiddens, num_residual_layers, num_residual_hiddens,
name='decoder'):
super(Decoder, self).__init__(name=name)
self._num_hiddens = num_hiddens
self._num_residual_layers = num_residual_layers
self._num_residual_hiddens = num_residual_hiddens
def _build(self, x):
h = snt.Conv2D(
output_channels=self._num_hiddens,
kernel_shape=(3, 3),
stride=(1, 1),
name="dec_1")(x)
h = residual_stack(
h,
self._num_hiddens,
self._num_residual_layers,
self._num_residual_hiddens)
h = snt.Conv2DTranspose(
output_channels=int(self._num_hiddens / 2),
output_shape=None,
kernel_shape=(4, 4),
stride=(2, 2),
name="dec_2")(h)
h = tf.nn.relu(h)
x_recon = snt.Conv2DTranspose(
output_channels=3,
output_shape=None,
kernel_shape=(4, 4),
stride=(2, 2),
name="dec_3")(h)
return x_recon
tf.reset_default_graph()
# VQ-VAE, DeepMind, Google AI
# https://github.com/deepmind/sonnet/blob/master/sonnet/examples/vqvae_example.ipynb
# Set hyper-parameters
batch_size = 32
image_size = 32
# 100k steps should take < 30 minutes on a modern (>= 2017) GPU
#num_training_updates = 50000
#num_training_updates = 50000
num_training_updates = 100
num_hiddens = 128
num_residual_hiddens = 32
num_residual_layers = 2
# These hyper-parameters define the size of the model (number of parameters and layers).
# The hyper-parameters in the paper were (For ImageNet):
# batch_size = 128
# image_size = 128
# num_hiddens = 128
# num_residual_hiddens = 32
# num_residual_layers = 2
# This value is not that important, usually 64 works.
# This will not change the capacity in the information-bottleneck.
embedding_dim = 64
# The higher this value, the higher the capacity in the information bottleneck.
num_embeddings = 512
# commitment_cost should be set appropriately. It's often useful to try a couple
# of values. It mostly depends on the scale of the reconstruction cost
# (log p(x|z)). So if the reconstruction cost is 100x higher, the
# commitment_cost should also be multiplied with the same amount.
commitment_cost = 0.25
# Use EMA updates for the codebook (instead of the Adam optimizer).
# This typically converges faster, and makes the model less dependent on choice
# of the optimizer. In the VQ-VAE paper EMA updates were not used (but was
# developed afterwards). See Appendix of the paper for more details.
vq_use_ema = False
decay = 0.99
learning_rate = 3e-4
# Data Loading
train_dataset_iterator = (
tf.data.Dataset.from_tensor_slices(train_data_dict)
.map(cast_and_normalise_images)
.shuffle(10000)
.repeat(-1) # repeat indefinitely
.batch(batch_size)).make_one_shot_iterator()
valid_dataset_iterator = (
tf.data.Dataset.from_tensor_slices(valid_data_dict)
.map(cast_and_normalise_images)
.repeat(1) # 1 epoch
.batch(batch_size)).make_initializable_iterator()
train_dataset_batch = train_dataset_iterator.get_next()
valid_dataset_batch = valid_dataset_iterator.get_next()
def get_images(sess, subset='train'):
if subset == 'train':
return sess.run(train_dataset_batch)['images']
elif subset == 'valid':
return sess.run(valid_dataset_batch)['images']
# Build the modules
encoder = Encoder(num_hiddens, num_residual_layers, num_residual_hiddens)
decoder = Decoder(num_hiddens, num_residual_layers, num_residual_hiddens)
pre_vq_conv1 = snt.Conv2D(output_channels=embedding_dim,
kernel_shape=(1, 1),
stride=(1, 1),
name="to_vq")
if vq_use_ema:
vq_vae = snt.nets.VectorQuantizerEMA(
embedding_dim=embedding_dim,
num_embeddings=num_embeddings,
commitment_cost=commitment_cost,
decay=decay)
else:
vq_vae = snt.nets.VectorQuantizer(
embedding_dim=embedding_dim,
num_embeddings=num_embeddings,
commitment_cost=commitment_cost)
# Process inputs with conv stack, finishing with 1x1 to get to correct size.
x = tf.placeholder(tf.float32, shape=(None, image_size, image_size, 3))
z = pre_vq_conv1(encoder(x))
# vq_output_train["quantize"] are the quantized outputs of the encoder.
# That is also what is used during training with the straight-through estimator.
# To get the one-hot coded assignments use vq_output_train["encodings"] instead.
# These encodings will not pass gradients into to encoder,
# but can be used to train a PixelCNN on top afterwards.
# For training
vq_output_train = vq_vae(z, is_training=True)
x_recon = decoder(vq_output_train["quantize"])
recon_error = tf.reduce_mean((x_recon - x) ** 2) / data_variance # Normalized MSE
loss = recon_error + vq_output_train["loss"]
# For evaluation, make sure is_training=False!
vq_output_eval = vq_vae(z, is_training=False)
x_recon_eval = decoder(vq_output_eval["quantize"])
# The following is a useful value to track during training.
# It indicates how many codes are 'active' on average.
perplexity = vq_output_train["perplexity"]
# Create optimizer and TF session.
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss)
sess = tf.train.SingularMonitoredSession()
# Train
train_res_recon_error = []
train_res_perplexity = []
for i in xrange(num_training_updates):
feed_dict = {x: get_images(sess)}
results = sess.run([train_op, recon_error, perplexity],
feed_dict=feed_dict)
train_res_recon_error.append(results[1])
train_res_perplexity.append(results[2])
if (i + 1) % 100 == 0:
print('%d iterations' % (i + 1))
print('recon_error: %.3f' % np.mean(train_res_recon_error[-100:]))
print('perplexity: %.3f' % np.mean(train_res_perplexity[-100:]))
print()
f = plt.figure(figsize=(16,8))
ax = f.add_subplot(1,2,1)
ax.plot(train_res_recon_error)
ax.set_yscale('log')
ax.set_title('NMSE.')
ax = f.add_subplot(1,2,2)
ax.plot(train_res_perplexity)
ax.set_title('Average codebook usage (perplexity).')
# Reconstructions
sess.run(valid_dataset_iterator.initializer)
train_originals = get_images(sess, subset='train')
train_reconstructions = sess.run(x_recon_eval, feed_dict={x: train_originals})
valid_originals = get_images(sess, subset='valid')
valid_reconstructions = sess.run(x_recon_eval, feed_dict={x: valid_originals})
def convert_batch_to_image_grid(image_batch):
reshaped = (image_batch.reshape(4, 8, 32, 32, 3)
.transpose(0, 2, 1, 3, 4)
.reshape(4 * 32, 8 * 32, 3))
return reshaped + 0.5
f = plt.figure(figsize=(16,8))
ax = f.add_subplot(2,2,1)
ax.imshow(convert_batch_to_image_grid(train_originals), interpolation='nearest')
ax.set_title('training data originals')
plt.axis('off')
ax = f.add_subplot(2,2,2)
ax.imshow(convert_batch_to_image_grid(train_reconstructions), interpolation='nearest')
ax.set_title('training data reconstructions')
plt.axis('off')
ax = f.add_subplot(2,2,3)
ax.imshow(convert_batch_to_image_grid(valid_originals), interpolation='nearest')
ax.set_title('validation data originals')
plt.axis('off')
ax = f.add_subplot(2,2,4)
ax.imshow(convert_batch_to_image_grid(valid_reconstructions), interpolation='nearest')
ax.set_title('validation data reconstructions')
plt.axis('off')
plt.pause(3)
import torch
import torch.nn as nn
input_dim = 5
hidden_dim = 10
n_layers = 1
lstm_layer = nn.LSTM(input_dim, hidden_dim, n_layers, batch_first=True)
# https://blog.floydhub.com/long-short-term-memory-from-zero-to-hero-with-pytorch/
# we use: https://blog.floydhub.com/long-short-term-memory-from-zero-to-hero-with-pytorch/
batch_size = 1
seq_len = 1
inp = torch.randn(batch_size, seq_len, input_dim)
hidden_state = torch.randn(n_layers, batch_size, hidden_dim)
cell_state = torch.randn(n_layers, batch_size, hidden_dim)
hidden = (hidden_state, cell_state)
out, hidden = lstm_layer(inp, hidden)
print("Output shape: ", out.shape)
print("Hidden: ", hidden)
seq_len = 3
inp = torch.randn(batch_size, seq_len, input_dim)
out, hidden = lstm_layer(inp, hidden)
print(out.shape)
# Obtaining the last output
out = out.squeeze()[-1, :]
print(out.shape)
# we now use: https://github.com/gabrielloye/LSTM_Sentiment-Analysis
# https://blog.floydhub.com/long-short-term-memory-from-zero-to-hero-with-pytorch/
#import bz2
#from collections import Counter
#import re
#import nltk
#import numpy as np
#nltk.download('punkt')
#train_file = bz2.BZ2File('../input/amazon_reviews/train.ft.txt.bz2')
#test_file = bz2.BZ2File('../input/amazon_reviews/test.ft.txt.bz2')
#train_file = train_file.readlines()
#test_file = test_file.readlines()
import bz2
from collections import Counter
import re
import nltk
import numpy as np
nltk.download('punkt')
train_file = bz2.BZ2File('../input/amazon_reviews/train.ft.txt.bz2')
test_file = bz2.BZ2File('../input/amazon_reviews/test.ft.txt.bz2')
train_file = train_file.readlines()
test_file = test_file.readlines()
num_train = 800000 # We're training on the first 800,000 reviews in the dataset
num_test = 200000 # Using 200,000 reviews from test set
train_file = [x.decode('utf-8') for x in train_file[:num_train]]
test_file = [x.decode('utf-8') for x in test_file[:num_test]]
# Extracting labels from sentences
train_labels = [0 if x.split(' ')[0] == '__label__1' else 1 for x in train_file]
train_sentences = [x.split(' ', 1)[1][:-1].lower() for x in train_file]
test_labels = [0 if x.split(' ')[0] == '__label__1' else 1 for x in test_file]
test_sentences = [x.split(' ', 1)[1][:-1].lower() for x in test_file]
# Some simple cleaning of data
for i in range(len(train_sentences)):
train_sentences[i] = re.sub('\d', '0', train_sentences[i])
for i in range(len(test_sentences)):
test_sentences[i] = re.sub('\d', '0', test_sentences[i])
# Modify URLs to <url>
for i in range(len(train_sentences)):
if 'www.' in train_sentences[i] or 'http:' in train_sentences[i] or 'https:' in train_sentences[i] or '.com' in \
train_sentences[i]:
train_sentences[i] = re.sub(r"([^ ]+(?<=\.[a-z]{3}))", "<url>", train_sentences[i])
for i in range(len(test_sentences)):
if 'www.' in test_sentences[i] or 'http:' in test_sentences[i] or 'https:' in test_sentences[i] or '.com' in \
test_sentences[i]:
test_sentences[i] = re.sub(r"([^ ]+(?<=\.[a-z]{3}))", "<url>", test_sentences[i])
words = Counter() # Dictionary that will map a word to the number of times it appeared in all the training sentences
for i, sentence in enumerate(train_sentences):
train_sentences[i] = []
for word in nltk.word_tokenize(sentence): # Tokenize the words
words.update([word.lower()]) # Convert all the words to lowercase
train_sentences[i].append(word)
if i%20000 == 0:
print(str((i*100)/num_train) + "% done")
print("OK. Done.")
# Removing the words that only appear once
words = {k:v for k,v in words.items() if v>1}
# Sorting the words according to the number of appearances, with the most common word being first
words = sorted(words, key=words.get, reverse=True)
# Adding padding and unknown to our vocabulary so that they will be assigned an index
words = ['_PAD','_UNK'] + words
# Dictionaries to store the word to index mappings and vice versa
word2idx = {o:i for i,o in enumerate(words)}
idx2word = {i:o for i,o in enumerate(words)}
for i, sentence in enumerate(train_sentences):
# Looking up the mapping dictionary and assigning the index to the respective words
train_sentences[i] = [word2idx[word] if word in word2idx else 0 for word in sentence]
for i, sentence in enumerate(test_sentences):
# For test sentences, we have to tokenize the sentences as well
test_sentences[i] = [word2idx[word.lower()] if word.lower() in word2idx else 0 for word in nltk.word_tokenize(sentence)]
# Defining a function that either shortens sentences or pads sentences with 0 to a fixed length
def pad_input(sentences, seq_len):
features = np.zeros((len(sentences), seq_len),dtype=int)
for ii, review in enumerate(sentences):
if len(review) != 0:
features[ii, -len(review):] = np.array(review)[:seq_len]
return features
seq_len = 200 # The length that the sentences will be padded/shortened to
train_sentences = pad_input(train_sentences, seq_len)
test_sentences = pad_input(test_sentences, seq_len)
# Converting our labels into numpy arrays
train_labels = np.array(train_labels)
test_labels = np.array(test_labels)
split_frac = 0.5 # 50% validation, 50% test
split_id = int(split_frac * len(test_sentences))
val_sentences, test_sentences = test_sentences[:split_id], test_sentences[split_id:]
val_labels, test_labels = test_labels[:split_id], test_labels[split_id:]
import torch
import torch.nn as nn
from torch.utils.data import TensorDataset, DataLoader
train_data = TensorDataset(torch.from_numpy(train_sentences), torch.from_numpy(train_labels))
val_data = TensorDataset(torch.from_numpy(val_sentences), torch.from_numpy(val_labels))
test_data = TensorDataset(torch.from_numpy(test_sentences), torch.from_numpy(test_labels))
batch_size = 400
train_loader = DataLoader(train_data, shuffle=True, batch_size=batch_size)
val_loader = DataLoader(val_data, shuffle=True, batch_size=batch_size)
test_loader = DataLoader(test_data, shuffle=True, batch_size=batch_size)
# torch.cuda.is_available() checks and returns a Boolean True if a GPU is available, else it'll return False
#is_cuda = torch.cuda.is_available()
# If we have a GPU available, we'll set our device to GPU. We'll use this device variable later in our code.
#if is_cuda:
# device = torch.device("cuda")
#else:
# device = torch.device("cpu")
class SentimentNet(nn.Module):
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5):
super(SentimentNet, self).__init__()
self.output_size = output_size
self.n_layers = n_layers
self.hidden_dim = hidden_dim
self.embedding = nn.Embedding(vocab_size, embedding_dim)
self.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers, dropout=drop_prob, batch_first=True)
self.dropout = nn.Dropout(drop_prob)
self.fc = nn.Linear(hidden_dim, output_size)
self.sigmoid = nn.Sigmoid()
def forward(self, x, hidden):
batch_size = x.size(0)
x = x.long()
embeds = self.embedding(x)
lstm_out, hidden = self.lstm(embeds, hidden)
lstm_out = lstm_out.contiguous().view(-1, self.hidden_dim)
out = self.dropout(lstm_out)
out = self.fc(out)
out = self.sigmoid(out)
out = out.view(batch_size, -1)
out = out[:, -1]
return out, hidden
def init_hidden(self, batch_size):
weight = next(self.parameters()).data
hidden = (weight.new(self.n_layers, batch_size, self.hidden_dim).zero_().to(device),
weight.new(self.n_layers, batch_size, self.hidden_dim).zero_().to(device))
return hidden
vocab_size = len(word2idx) + 1
output_size = 1
embedding_dim = 400
hidden_dim = 512
n_layers = 2
model = SentimentNet(vocab_size, output_size, embedding_dim, hidden_dim, n_layers)
model.to(device)
lr=0.005
criterion = nn.BCELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
epochs = 2
counter = 0
print_every = 1000
clip = 5
valid_loss_min = np.Inf
model.train()
for i in range(epochs):
h = model.init_hidden(batch_size)
for inputs, labels in train_loader:
counter += 1
h = tuple([e.data for e in h])
inputs, labels = inputs.to(device), labels.to(device)
model.zero_grad()
output, h = model(inputs, h)
loss = criterion(output.squeeze(), labels.float())
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), clip)
optimizer.step()
if counter % print_every == 0:
val_h = model.init_hidden(batch_size)
val_losses = []
model.eval()
for inp, lab in val_loader:
val_h = tuple([each.data for each in val_h])
inp, lab = inp.to(device), lab.to(device)
out, val_h = model(inp, val_h)
val_loss = criterion(out.squeeze(), lab.float())
val_losses.append(val_loss.item())
model.train()
print("Epoch: {}/{}...".format(i + 1, epochs),
"Step: {}...".format(counter),
"Loss: {:.6f}...".format(loss.item()),
"Val Loss: {:.6f}".format(np.mean(val_losses)))
if np.mean(val_losses) <= valid_loss_min:
torch.save(model.state_dict(), './state_dict.pt')
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(valid_loss_min,
np.mean(val_losses)))
valid_loss_min = np.mean(val_losses)
# Loading the best model
model.load_state_dict(torch.load('./state_dict.pt'))
num_correct = 0
test_losses = []
h = model.init_hidden(batch_size)
model.eval()
for inputs, labels in test_loader:
h = tuple([each.data for each in h])
inputs, labels = inputs.to(device), labels.to(device)
output, h = model(inputs, h)
test_loss = criterion(output.squeeze(), labels.float())
test_losses.append(test_loss.item())
pred = torch.round(output.squeeze()) # Rounds the output to 0/1
correct_tensor = pred.eq(labels.float().view_as(pred))
correct = np.squeeze(correct_tensor.cpu().numpy())
num_correct += np.sum(correct)
# use: https://blog.floydhub.com/long-short-term-memory-from-zero-to-hero-with-pytorch/
print("Test loss: {:.3f}".format(np.mean(test_losses)))
test_acc = num_correct/len(test_loader.dataset)
print("Test accuracy: {:.3f}%".format(test_acc*100))
import tensorflow
import matplotlib.pyplot as plt
import time
import numpy as np
import tensorflow as tf
from keras.datasets import mnist
from tensorflow.examples.tutorials.mnist import input_data
# https://machinelearningmastery.com/how-to-choose-loss-functions-when-training-deep-learning-neural-networks/
# https://towardsdatascience.com/introduction-to-multilayer-neural-networks-with-tensorflows-keras-api-abf4f813959
# use: https://towardsdatascience.com/introduction-to-multilayer-neural-networks-with-tensorflows-keras-api-abf4f813959
# MNIST: Four files are available on this site:
# train-images-idx3-ubyte.gz: training set images (9912422 bytes)
# train-labels-idx1-ubyte.gz: training set labels (28881 bytes)
# t10k-images-idx3-ubyte.gz: test set images (1648877 bytes)
# t10k-labels-idx1-ubyte.gz: test set labels (4542 bytes)
# From Terminal: (1) cd mnist/
# (2) gzip train-images-idx3-ubyte.gz -d
# (3) gzip train-labels-idx1-ubyte.gz -d
# (4) gzip t10k-images-idx3-ubyte.gz -d
# (5) gzip t10k-labels-idx1-ubyte.gz -d