forked from i-deal/MLR-2.0
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplots_novel.py
executable file
·1865 lines (1440 loc) · 95.7 KB
/
plots_novel.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
#MNIST VAE retreived from https://github.com/lyeoni/pytorch-mnist-VAE/blob/master/pytorch-mnist-VAE.ipynb
# Modifications:
#Colorize transform that changes the colors of a grayscale image
#colors are chosen from 10 options:
colornames = ["red", "blue","green","purple","yellow","cyan","orange","brown","pink","teal"]
#specified in "colorvals" variable below
#also there is a skip connection from the first layer to the last layer to enable reconstructions of new stimuli
#and the VAE bottleneck is split, having two different maps
#one is trained with a loss function for color only (eliminating all shape info, reserving only the brightest color)
#the other is trained with a loss function for shape only
# prerequisites
import torch
from dataset_builder import Dataset
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from torchvision import datasets, transforms
from torch.autograd import Variable
from torchvision.utils import save_image
from sklearn import svm
from sklearn.metrics import classification_report, confusion_matrix
from IPython.display import Image, display
import cv2
from PIL import ImageFilter
import imageio, time
import math
import sys
import BPFunctions
import pandas as pd
from torch.utils.data import DataLoader, Subset
#from config import numcolors
global numcolors, colorlabels
from PIL import Image
from mVAE import *
from tokens_capacity import *
import os
from PIL import Image, ImageOps, ImageEnhance, __version__ as PILLOW_VERSION
convert_tensor = transforms.ToTensor()
convert_image = transforms.ToPILImage()
if torch.cuda.is_available():
device = 'cuda'
print('CUDA')
else:
device = 'cpu'
modelNumber= 1 #which model should be run, this can be 1 through 10
folder_path = f'output{modelNumber}' # the output folder for the trained model versions
if not os.path.exists(folder_path):
os.mkdir(folder_path)
#load_checkpoint('output/checkpoint_threeloss_singlegrad200_smfc.pth'.format(modelNumber=modelNumber))
load_checkpoint('output_emnist_recurr/checkpoint_150.pth') # MLR2.0 trained on emnist letters, digits, and fashion mnist
#print('Loading the classifiers')
clf_shapeS=load('classifier_output/ss.joblib')
clf_shapeC=load('classifier_output/sc.joblib')
clf_colorC=load('classifier_output/cc.joblib')
clf_colorS=load('classifier_output/cs.joblib')
#write to a text file
outputFile = open('outputFile.txt'.format(modelNumber),'w')
bs_testing = 1000 # number of images for testing. 20000 is the limit
shape_coeff = 1 #cofficient of the shape map
color_coeff = 1 #coefficient of the color map
location_coeff = 0 #Coefficient of Location map
l1_coeff = 1 #coefficient of layer 1
l2_coeff = 1 #coefficient of layer 2
shapeLabel_coeff= 1 #coefficient of the shape label
colorLabel_coeff = 1 #coefficient of the color label
location_coeff = 0 #coefficient of the color label
bpsize = 2500 #size of the binding pool
token_overlap =0.25
bpPortion = int(token_overlap *bpsize) # number binding pool neurons used for each item
normalize_fact_familiar=1
normalize_fact_novel=1
imgsize = 28
all_imgs = []
#number of repetions for statistical inference
hugepermnum=10000
bigpermnum = 500
smallpermnum = 100
Fig2aFlag = 0 #binding pool reconstructions NOTWORKING
fig_new_loc = 0 # reconstruct retina images with digits in the location opposite of training
fig_loc_compare = 1 # compare retina images with digits in the same location as training and opposite location
Fig2bFlag = 1 #novel objects stored and retrieved from memory, one at a time
Fig2btFlag = 1 #novel objects stored and retrieved from memory, in tokens
Fig2cFlag = 1 #familiar objects stored and retrieved from memory, using tokens
sampleflag = 0 #generate random objects from latents (plot working, not behaving as expected)
Fig2nFlag = 0
bindingtestFlag = 0 #simulating binding shape-color of two items NOT WORKING
Tab1Flag_noencoding = 0 #classify reconstructions (no memory) NOT WORKINGy
Tab1Flag = 0 # #classify binding pool memoriesNOT WORKING
Tab1SuppFlag = 0 #memory of labels (this is table 1 + Figure 2 in supplemental which includes the data in Figure 3)
Tab2Flag =0 #NOT WORKING
TabTwoColorFlag = 0 #NOT WORKING
TabTwoColorFlag1 = 0 #Cross correlations for familiar vs novel #NOT WORKING
noveltyDetectionFlag=0 #detecting whether a stimulus is familiar or not #NOT WORKING
latents_crossFlag = 0 #Cross correlations for familiar vs novel for when infromation is stored from the shape/color maps vs. L1. versus straight reconstructions
#This Figure is not included in the paper #NOT WORKING
bs=100 # number of samples to extract from the dataset
#### generate some random samples (currently commented out due to cuda errors) #NOT WORKING
if (sampleflag):
zc=torch.randn(64,16).cuda()*1
zs=torch.randn(64,16).cuda()*1
with torch.no_grad():
sample = vae.decoder_cropped(zs,zc,0).cuda()
sample_c= vae.decoder_cropped(zs*0,zc,0).cuda()
sample_s = vae.decoder_cropped(zs, zc*0, 0).cuda()
sample=sample.view(64, 3, 28, 28)
sample_c=sample_c.view(64, 3, 28, 28)
sample_s=sample_s.view(64, 3, 28, 28)
save_image(sample[0:8], 'output{num}/sample.png'.format(num=modelNumber))
save_image(sample_c[0:8], 'output{num}/sample_color.png'.format(num=modelNumber))
save_image(sample_s[0:8], 'output{num}/sample_shape.png'.format(num=modelNumber))
test_dataset = torch.utils.data.ConcatDataset((test_dataset_MNIST, ftest_dataset))
test_loader_smaller = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=bs_testing, shuffle=True, num_workers=nw)
######################## Figure 2a #######################################################################################
#store items using both features, and separately color and shape (memory retrievals)
if Fig2aFlag==1:
print('generating figure 2a, reconstructions from the binding pool')
numimg= 6
bs=numimg #number of images to display in this figure
nw=2
bs_testing = numimg # 20000 is the limit
train_loader_noSkip = Dataset('mnist',{'colorize':True}).get_loader(bs)
test_loader_noSkip = Dataset('mnist',{'colorize':True},train=False).get_loader(bs)
test_loader_smaller = test_loader_noSkip
images, shapelabels = next(iter(test_loader_smaller))#peel off a large number of images
#orig_imgs = images.view(-1, 3 * 28 * 28).cuda()
imgs = images.clone().cuda()
#run them all through the encoder
l1_act, l2_act, shape_act, color_act, location_act = activations(imgs) #get activations from this small set of images
'''BPOut, Tokenbindings = BPTokens_storage(bpsize, bpPortion, l1_act[n,:].view(1,-1), l2_act[n,:].view(1,-1), shape_act[n,:].view(1,-1),color_act[n,:].view(1,-1),location_act[n,:].view(1,-1),0, 0,0,1,0,1,normalize_fact_novel)
shape_out_all, color_out_all, location_out_all, BP_layer2_out, BP_layerI_out = BPTokens_retrieveByToken( bpsize, bpPortion, BPOut, Tokenbindings,l1_act.view(numimg,-1), l2_act.view(numimg,-1), shape_act,color_act,location_act,1,normalize_fact_novel)
'''
'''def BPTokens_storage(bpsize, bpPortion,l1_act, l2_act, shape_act, color_act, location_act, shape_coeff, color_coeff, location_coeff, l1_coeff,l2_coeff, bs_testing, normalize_fact):
'''
BPOut_all, Tokenbindings_all = BPTokens_storage(bpsize, bpPortion, l1_act, l2_act, shape_act,color_act,location_act,shape_coeff, color_coeff, location_coeff, l1_coeff,l2_coeff,1,normalize_fact_novel)
shape_out_all, color_out_all, location_out_all, BP_layer2_out, BP_layerI_out = BPTokens_retrieveByToken( bpsize, bpPortion, BPOut_all, Tokenbindings_all,l1_act, l2_act, shape_act,color_act,location_act,1,normalize_fact_novel)
#memory retrievals from Bottleneck storage
bothRet = vae.decoder_cropped(shape_out_all, color_out_all,0, 0).cuda() # memory retrieval from the bottleneck
#shapeRet = vae.decoder_shape(shape_out_BP_shapeonly, color_out_BP_shapeonly , 0).cuda() #memory retrieval from the shape map
#colorRet = vae.decoder_color(shape_out_BP_coloronly, color_out_BP_coloronly, 0).cuda() #memory retrieval from the color map
shapeRet = bothRet
colorRet = bothRet
save_image(
torch.cat([imgs[0: numimg].view(numimg, 3, 28, 28), bothRet[0: numimg].view(numimg, 3, 28, 28),
shapeRet[0: numimg].view(numimg, 3, 28, 28), colorRet[0: numimg].view(numimg, 3, 28, 28)], 0),
'output{num}/figure2a_BP_bottleneck_.png'.format(num=modelNumber),
nrow=numimg,
normalize=False,
range=(-1, 1),
)
#memory retrievals when information was stored from L1 and L2
BP_layer1_noskip, mu_color, log_var_color, mu_shape, log_var_shape = vae.forward_layers(BP_layerI_out,BP_layer2_out, 1, 'noskip') #bp retrievals from layer 1
BP_layer2_noskip, mu_color, log_var_color, mu_shape, log_var_shape = vae.forward_layers(BP_layerI_out,BP_layer2_out, 2, 'noskip') #bp retrievals from layer 2
save_image(
torch.cat([
BP_layer2_noskip[0: numimg].view(numimg, 3, 28, 28), BP_layer1_noskip[0: numimg].view(numimg, 3, 28, 28)], 0),
'output{num}/figure2a_layer2_layer1.png'.format(num=modelNumber),
nrow=numimg,
normalize=False,
range=(-1, 1),
)
if fig_new_loc == 1:
#recreate images of digits, but on the opposite side of the retina that they had originally been trained on
#no working memory, just a reconstruction
bs = 100
retina_size = 100 #how wide is the retina
#make the data loader, but specifically we are creating stimuli on the opposite to how the model was trained
train_loader_noSkip, train_loader_skip, test_loader_noSkip, test_loader_skip = dataset_builder('mnist',bs,{},True,{'left':list(range(0,5)),'right':list(range(5,10))})
#Code showing the data loader for how the model was trained, empty dict in 3rd param is for any color:
'''train_loader_noSkip, train_loader_skip, test_loader_noSkip, test_loader_skip = dataset_builder('mnist',bs,
{},True,{'right':list(range(0,5)),'left':list(range(5,10))}) '''
dataiter_noSkip = iter(test_loader_noSkip)
data = dataiter_noSkip.next()
data = data[0] #.cuda()
sample_data = data
sample_size = 15
sample_data[0] = sample_data[0][:sample_size]
sample_data[1] = sample_data[1][:sample_size]
sample_data[2] = sample_data[2][:sample_size]
sample = sample_data
with torch.no_grad(): #generate reconstructions for these stimuli from different pathways through the model
reconl, mu_color, log_var_color, mu_shape, log_var_shape,mu_location, log_var_location = vae(sample, 'location') #location
reconb, mu_color, log_var_color, mu_shape, log_var_shape, mu_location, log_var_location = vae(sample, 'retinal') #retina
recond, mu_color, log_var_color, mu_shape, log_var_shape, mu_location, log_var_location = vae(sample, 'cropped') #digit
reconc, mu_color, log_var_color, mu_shape, log_var_shape, mu_location, log_var_location = vae(sample, 'color') #color
recons, mu_color, log_var_color, mu_shape, log_var_shape, mu_location, log_var_location = vae(sample, 'shape') #shape
empty_retina = torch.zeros((sample_size, 3, 28, 100))
#repackage the reconstructions for visualization
n_reconl = empty_retina.clone()
for i in range(len(reconl)):
n_reconl[i][0, :, 0:100] = reconl[i]
n_reconl[i][1, :, 0:100] = reconl[i]
n_reconl[i][2, :, 0:100] = reconl[i]
n_recond = empty_retina.clone()
for i in range(len(recond)):
n_recond[i][0, :, 0:imgsize] = recond[i][0]
n_recond[i][1, :, 0:imgsize] = recond[i][1]
n_recond[i][2, :, 0:imgsize] = recond[i][2]
n_reconc = empty_retina.clone()
for i in range(len(reconc)):
n_reconc[i][0, :, 0:28] = reconc[i][0]
n_reconc[i][1, :, 0:28] = reconc[i][1]
n_reconc[i][2, :, 0:28] = reconc[i][2]
n_recons = empty_retina.clone()
for i in range(len(recons)):
n_recons[i][0, :, 0:28] = recons[i][0]
n_recons[i][1, :, 0:28] = recons[i][1]
n_recons[i][2, :, 0:28] = recons[i][2]
line1 = torch.ones((1,2)) * 0.5
line1 = line1.view(1,1,1,2)
line1 = line1.expand(sample_size, 3, imgsize, 2)
n_reconc = torch.cat((n_reconc,line1),dim = 3).cuda()
n_recons = torch.cat((n_recons,line1),dim = 3).cuda()
n_reconl = torch.cat((n_reconl,line1),dim = 3).cuda()
n_recond = torch.cat((n_recond,line1),dim = 3).cuda()
shape_color_dim = retina_size + 2
sample = torch.cat((sample[0],line1),dim = 3).cuda()
reconb = torch.cat((reconb,line1.cuda()),dim = 3).cuda()
utils.save_image(
torch.cat([sample.view(sample_size, 3, imgsize, retina_size+2), reconb.view(sample_size, 3, imgsize, retina_size+2), n_recond.view(sample_size, 3, imgsize, retina_size+2),
n_reconl.view(sample_size, 3, imgsize, retina_size+2), n_reconc.view(sample_size, 3, imgsize, shape_color_dim), n_recons.view(sample_size, 3, imgsize, shape_color_dim)], 0),
'output{num}/figure_new_location.png'.format(num=modelNumber),
nrow=sample_size,
normalize=False,
range=(-1, 1),
)
if fig_loc_compare == 1:
bs = 15
train_transforms = {'retina':True, 'colorize':True, 'location_targets':{'left':list(range(0,5)),'right':list(range(5,10))}}
test_transforms = {'retina':True, 'colorize':True, 'location_targets':{'right':list(range(0,5)),'left':list(range(5,10))}}
train_loader_noSkip = Dataset('mnist',train_transforms).get_loader(bs)
test_loader_noSkip = Dataset('mnist',test_transforms, train=False).get_loader(bs)
imgsize = 28
numimg = 10
dataiter_noSkip_test = iter(test_loader_noSkip)
dataiter_noSkip_train = iter(train_loader_noSkip)
#skipd = iter(train_loader_skip)
#skip = skipd.next()
#print(skip[0].size())
print(type(dataiter_noSkip_test))
data_test = dataiter_noSkip_test.next()
data_train = dataiter_noSkip_train.next()
data = data_train[0].copy()
#print(data.size())
data[0] = torch.cat((data_test[0][0], data_train[0][0]),dim=0) #.cuda()
data[1] = torch.cat((data_test[0][1], data_train[0][1]),dim=0)
data[2] = torch.cat((data_test[0][2], data_train[0][2]),dim=0)
sample = data
sample_size = 15
print(sample[0].size(),sample[1].size(),sample[2].size())
with torch.no_grad():
reconl, mu_color, log_var_color, mu_shape, log_var_shape, mu_location, log_var_location = vae(sample, 'location') #location
reconb, mu_color, log_var_color, mu_shape, log_var_shape, mu_location, log_var_location = vae(sample, 'retinal') #retina
recond, mu_color, log_var_color, mu_shape, log_var_shape, mu_location, log_var_location = vae(sample, 'cropped') #digit
reconc, mu_color, log_var_color, mu_shape, log_var_shape, mu_location, log_var_location = vae(sample, 'color') #color
recons, mu_color, log_var_color, mu_shape, log_var_shape, mu_location, log_var_location = vae(sample, 'shape') #shape
empty_retina = torch.zeros((2*sample_size, 3, 28, 100))
n_reconl = empty_retina.clone()
for i in range(len(reconl)):
n_reconl[i][0, :, 0:100] = reconl[i]
n_reconl[i][1, :, 0:100] = reconl[i]
n_reconl[i][2, :, 0:100] = reconl[i]
n_recond = empty_retina.clone()
for i in range(len(recond)):
n_recond[i][0, :, 0:imgsize] = recond[i][0]
n_recond[i][1, :, 0:imgsize] = recond[i][1]
n_recond[i][2, :, 0:imgsize] = recond[i][2]
n_reconc = empty_retina.clone()
for i in range(len(reconc)):
n_reconc[i][0, :, 0:28] = reconc[i][0]
n_reconc[i][1, :, 0:28] = reconc[i][1]
n_reconc[i][2, :, 0:28] = reconc[i][2]
n_recons = empty_retina.clone()
for i in range(len(recons)):
n_recons[i][0, :, 0:28] = recons[i][0]
n_recons[i][1, :, 0:28] = recons[i][1]
n_recons[i][2, :, 0:28] = recons[i][2]
line1 = torch.ones((1,2)) * 0.5
line1 = line1.view(1,1,1,2)
line2 = line1.expand(sample_size, 3, imgsize, 2)
line1 = line1.expand(2*sample_size, 3, imgsize, 2)
n_reconc = torch.cat((n_reconc,line1),dim = 3).cuda()
n_recons = torch.cat((n_recons,line1),dim = 3).cuda()
n_reconl = torch.cat((n_reconl,line1),dim = 3).cuda()
n_recond = torch.cat((n_recond,line1),dim = 3).cuda()
shape_color_dim = retina_size + 2
sample_test = torch.cat((sample[0][:sample_size],line2),dim = 3).cuda()
sample_train = torch.cat((sample[0][sample_size:(2*sample_size)],line2),dim = 3).cuda()
reconb = torch.cat((reconb,line1.cuda()),dim = 3).cuda()
utils.save_image(
torch.cat((
torch.cat([sample_train.view(sample_size, 3, imgsize, retina_size+2), reconb[sample_size:(2*sample_size)].view(sample_size, 3, imgsize, retina_size+2), n_reconl[sample_size:(2*sample_size)].view(sample_size, 3, imgsize, retina_size+2),
n_recond[sample_size:(2*sample_size)].view(sample_size, 3, imgsize, retina_size+2), n_reconc[sample_size:(2*sample_size)].view(sample_size, 3, imgsize, shape_color_dim), n_recons[sample_size:(2*sample_size)].view(sample_size, 3, imgsize, shape_color_dim)], 0),
torch.cat([sample_test.view(sample_size, 3, imgsize, retina_size+2), reconb[:(sample_size)].view(sample_size, 3, imgsize, retina_size+2), n_reconl[:(sample_size)].view(sample_size, 3, imgsize, retina_size+2),
n_recond[:(sample_size)].view(sample_size, 3, imgsize, retina_size+2), n_reconc[:(sample_size)].view(sample_size, 3, imgsize, shape_color_dim), n_recons[:(sample_size)].view(sample_size, 3, imgsize, shape_color_dim)], 0)),0),
'output{num}/figure_new_location.png'.format(num=modelNumber),
nrow=sample_size,
normalize=False,
range=(-1, 1),
)
image_pil = Image.open('output{num}/figure_new_location.png'.format(num=modelNumber))
trained_label = "Trained Data"
untrained_label = "Untrained Data"
# Add trained and untrained labels to the image using PIL's Draw module
draw = ImageDraw.Draw(image_pil)
font = ImageFont.load_default() # You can choose a different font or size
# Trained data label at top left
trained_label_position = (10, 10) # Adjust the position of the text
draw.text(trained_label_position, trained_label, fill=(255, 255, 255), font=font)
# Untrained data label at bottom left
image_width, image_height = image_pil.size
untrained_label_position = (10, image_height//2) # Adjust the position of the text
draw.text(untrained_label_position, untrained_label, fill=(255, 255, 255), font=font)
# Save the modified image with labels
image_pil.save('output{num}/figure_new_location.png'.format(num=modelNumber))
print("Images with labels saved successfully.")
if Fig2nFlag==1:
print('bengali reconstructions')
all_imgs = []
imgsize = 28
numimg = 7
#load in some examples of Bengali Characters
for i in range (1,numimg+1):
img_new = convert_tensor(Image.open(f'current_bengali/{i}_thick.png'))[0:3,:,:]
#img_new = Colorize_func(img) # Currently broken, but would add a color to each
all_imgs.append(img_new)
all_imgs = torch.stack(all_imgs)
imgs = all_imgs.view(-1, 3, imgsize, imgsize).cuda()
output, mu_color, log_var_color, mu_shape, log_var_shape, mu_location, log_var_location = vae(all_imgs,whichdecode='skip_cropped')
z_img = vae.sampling(mu_shape,log_var_shape)
recon_sample = vae.decoder_shape(z_img, 0, 0)
out_img = torch.cat([imgs[0: numimg].view(numimg, 3, 28, imgsize),output,recon_sample],dim=0)
utils.save_image(out_img,f'output{modelNumber}/bengali_recon.png',numimg)
if Fig2bFlag==1:
all_imgs = []
print('generating Figure 2b, Novel characters retrieved from memory of L1 and Bottleneck')
retina_size = 100
imgsize = 28
numimg = 7
#load in some examples of Bengali Characters
for i in range (1,numimg+1):
img_new = convert_tensor(Image.open(f'current_bengali/{i}_thick.png'))[0:3,:,:]
#img_new = Colorize_func(img) # Currently broken, but would add a color to each
all_imgs.append(img_new)
all_imgs = torch.stack(all_imgs)
imgs = all_imgs.view(-1, 3 * imgsize * imgsize).cuda()
location = torch.zeros(imgs.size()[0], vae.l_dim).cuda()
location[0] = 1
#push the images through the encoder
l1_act, l2_act, shape_act, color_act, location_act = activations(imgs.view(-1,3,28,28), location)
imgmatrixL1skip = torch.empty((0,3,28,28)).cuda()
imgmatrixL1noskip = torch.empty((0,3,28,28)).cuda()
imgmatrixMap = torch.empty((0,3,28,28)).cuda()
#now run them through the binding pool!
#store the items and then retrive them, and do it separately for shape+color maps, then L1, then L2.
#first store and retrieve the shape, color and location maps
for n in range (0,numimg):
# reconstruct directly from activation
recon_layer1_skip, mu_color, log_var_color, mu_shape, log_var_shape = vae.forward_layers(l1_act.view(numimg,-1), l2_act, 3, 'skip_cropped')
#now store/retrieve from L1
BPOut, Tokenbindings = BPTokens_storage(bpsize, bpPortion, l1_act[n,:].view(1,-1), l2_act[n,:].view(1,-1), shape_act[n,:].view(1,-1),color_act[n,:].view(1,-1),location_act[n,:].view(1,-1),0, 0,0,1,0,1,normalize_fact_novel)
shape_out_all, color_out_all, location_out_all, BP_layer2_out, BP_layerI_out = BPTokens_retrieveByToken( bpsize, bpPortion, BPOut, Tokenbindings,l1_act.view(numimg,-1), l2_act.view(numimg,-1), shape_act,color_act,location_act,1,normalize_fact_novel)
# reconstruct from BP version of layer 1, run through the skip
BP_layer1_skip, mu_color, log_var_color, mu_shape, log_var_shape = vae.forward_layers(BP_layerI_out.view(1,-1),BP_layer2_out,3, 'skip_cropped')
# reconstruct from BP version of layer 1, run through the bottleneck
BP_layer1_noskip, mu_color, log_var_color, mu_shape, log_var_shape = vae.forward_layers(BP_layerI_out.view(1,-1),BP_layer2_out, 3, 'cropped')
BPOut, Tokenbindings = BPTokens_storage(bpsize, bpPortion, l1_act[n,:].view(1,-1), l2_act[n,:].view(1,-1), shape_act[n,:].view(1,-1),color_act[n,:].view(1,-1),location_act[n,:].view(1,-1),1, 1,0,0,0,1,normalize_fact_novel)
shape_out_BP, color_out_BP, location_out_all, l2_out_all, l1_out_all = BPTokens_retrieveByToken( bpsize, bpPortion, BPOut, Tokenbindings,l1_act.view(numimg,-1), l2_act.view(numimg,-1), shape_act,color_act,location_act,1,normalize_fact_novel)
#reconstruct from BP version of the shape and color maps
retrievals = vae.decoder_cropped(shape_out_BP, color_out_BP,0,0).cuda()
imgmatrixL1skip = torch.cat([imgmatrixL1skip,BP_layer1_skip])
imgmatrixL1noskip = torch.cat([imgmatrixL1noskip,BP_layer1_noskip])
imgmatrixMap= torch.cat([imgmatrixMap,retrievals])
#save an image showing: original images, reconstructions directly from L1, from L1 BP, from L1 BP through bottleneck, from maps BP
save_image(torch.cat([imgs[0: numimg].view(numimg, 3, 28, imgsize), imgmatrixL1skip, imgmatrixL1noskip, imgmatrixMap], 0),'output{num}/figure2b.png'.format(num=modelNumber),
nrow=numimg, normalize=False, range=(-1, 1),)
if Fig2btFlag==1:
all_imgs = []
recon = list()
print('generating Figure 2bt, Novel characters retrieved from memory of L1 and Bottleneck using Tokens')
retina_size = 100
imgsize = 28
numimg = 7 #how many objects will we use here?
#load in some examples of Bengali Characters
for i in range (1,numimg+1):
img_new = convert_tensor(Image.open(f'current_bengali/{i}_thick.png'))[0:3,:,:]
all_imgs.append(img_new)
#all_imgs is a list of length 3, each of which is a 3x28x28
all_imgs = torch.stack(all_imgs)
imgs = all_imgs.view(-1, 3 * imgsize * imgsize).cuda() #dimensions are R+G+B + # pixels
imgmatrix = imgs.view(numimg,3,28,28)
#push the images through the model
l1_act, l2_act, shape_act, color_act, location_act = activations(imgs.view(-1,3,28,28))
emptyshape = torch.empty((1,3,28,28)).cuda()
# store 1 -> numimg items
for n in range(1,numimg+1):
BPOut, Tokenbindings = BPTokens_storage(bpsize, bpPortion, l1_act.view(numimg,-1), l2_act.view(numimg,-1), shape_act,color_act,location_act,0, 0,0,1,0,n,normalize_fact_novel)
shape_out_all, color_out_all, location_out_all, l2_out_all, l1_out_all = BPTokens_retrieveByToken( bpsize, bpPortion, BPOut, Tokenbindings,l1_act.view(numimg,-1), l2_act.view(numimg,-1), shape_act,color_act,location_act,n,normalize_fact_novel)
recon_layer1_skip, mu_color, log_var_color, mu_shape, log_var_shape = vae.forward_layers(l1_out_all.view(n,-1), l2_act, 3, 'skip_cropped')
#recon_layer1_skip= vae.decoder_skip_cropped(0,0,0,l1_out_all)
imgmatrix= torch.cat([imgmatrix,recon_layer1_skip],0)
#now pad with empty images
for i in range(n,numimg):
imgmatrix= torch.cat([imgmatrix,emptyshape*0],0)
save_image(imgmatrix,'output{num}/figure2bt.png'.format(num=modelNumber), nrow=numimg, normalize=False, range=(-1, 1), )
if Fig2cFlag==1:
print('generating Figure 2c, Familiar characters retrieved from Bottleneck using Tokens')
retina_size = 100
reconMap = list()
reconL1 = list()
imgsize = 28
numimg = 7 #how many objects will we use here?
#make the data loader, but specifically we are creating stimuli on the opposite to how the model was trained
train_loader_noSkip= Dataset('mnist',{'colorize':True,'retina':True}, train=False).get_loader(numimg)
#Code showing the data loader for how the model was trained, empty dict in 3rd param is for any color:
'''train_loader_noSkip, train_loader_skip, test_loader_noSkip, test_loader_skip = dataset_builder('mnist',bs,
{},True,{'right':list(range(0,5)),'left':list(range(5,10))}) '''
dataiter_noSkip = iter(test_loader_noSkip)
data = dataiter_noSkip.next()
data = data[0] #.cuda()
sample_data = data
sample_size = numimg
sample_data[0] = sample_data[0][:sample_size]
sample_data[1] = sample_data[1][:sample_size]
sample = sample_data
#push the images through the model
l1_act, l2_act, shape_act, color_act, location_act = activations(sample[1].view(-1,3,28,28).cuda())
emptyshape = torch.empty((1,3,28,28)).cuda()
imgmatrixMap = sample[1].view(numimg,3,28,28).cuda()
imgmatrixL1 = sample[1].view(numimg,3,28,28).cuda()
# store 1 -> numimg items
for n in range(1,numimg+1):
#Store and retrieve the map versions
BPOut, Tokenbindings = BPTokens_storage(bpsize, bpPortion, l1_act.view(numimg,-1), l2_act.view(numimg,-1), shape_act,color_act,location_act,1, 1,0,0,0,n,normalize_fact_novel)
shape_out_all, color_out_all, location_out_all, l2_out_all, l1_out_all = BPTokens_retrieveByToken( bpsize, bpPortion, BPOut, Tokenbindings,l1_act.view(numimg,-1), l2_act.view(numimg,-1), shape_act,color_act,location_act,n,normalize_fact_novel)
retrievals = vae.decoder_cropped(shape_out_all, color_out_all,0,0).cuda()
#Store and retrieve the L1 version
BPOut, Tokenbindings = BPTokens_storage(bpsize, bpPortion, l1_act.view(numimg,-1), l2_act.view(numimg,-1), shape_act,color_act,location_act,0, 0,0,1,0,n,normalize_fact_novel)
shape_out_all, color_out_all, location_out_all, l2_out_all, l1_out_all = BPTokens_retrieveByToken( bpsize, bpPortion, BPOut, Tokenbindings,l1_act.view(numimg,-1), l2_act.view(numimg,-1), shape_act,color_act,location_act,n,normalize_fact_novel)
recon_layer1_skip, mu_color, log_var_color, mu_shape, log_var_shape = vae.forward_layers(l1_out_all.view(n,-1), l2_act, 3, 'skip_cropped')
imgmatrixMap= torch.cat([imgmatrixMap,retrievals],0)
imgmatrixL1= torch.cat([imgmatrixL1,recon_layer1_skip],0)
#now pad with empty images
for i in range(n,numimg):
imgmatrixMap= torch.cat([imgmatrixMap,emptyshape*0],0)
imgmatrixL1= torch.cat([imgmatrixL1,emptyshape*0],0)
save_image(imgmatrixL1, 'output{num}/figure2cL1.png'.format(num=modelNumber), nrow=numimg, normalize=False,range=(-1, 1))
save_image(imgmatrixMap, 'output{num}/figure2cMap.png'.format(num=modelNumber), nrow=numimg, normalize=False,range=(-1, 1))
###################Table 2##################################################
if Tab2Flag ==1:
numModels=10
print('Tab2 loss of quality of familiar vs novel items using correlation')
setSizes=[1,2,3,4] #number of tokens
familiar_corr_all=list()
familiar_corr_all_se=list()
novel_corr_all=list()
novel_corr_all_se=list()
familiar_skip_all=list()
familiar_skip_all_se=list()
novel_BN_all=list()
novel_BN_all_se = list()
perms = bigpermnum#number of times it repeats storing/retrieval
for numItems in setSizes:
familiar_corr_models = list()
novel_corr_models = list()
familiar_skip_models=list()
novel_BN_models=list()
print('SetSize {num}'.format(num=numItems))
for modelNumber in range(1, numModels + 1): # which model should be run, this can be 1 through 10
load_checkpoint(
'output{modelNumber}/checkpoint_threeloss_singlegrad50.pth'.format(modelNumber=modelNumber))
# reset the data set for each set size
test_loader_smaller = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=numItems, shuffle=True,
num_workers=nw)
# This function is in tokens_capacity.py
familiar_corrValues= storeretrieve_crosscorrelation_test(numItems, perms, bpsize, bpPortion, shape_coeff,
color_coeff,
normalize_fact_familiar,
normalize_fact_novel, modelNumber,
test_loader_smaller, 'fam', 0,1)
familiar_corrValues_skip = storeretrieve_crosscorrelation_test(numItems, perms, bpsize, bpPortion, shape_coeff,
color_coeff,
normalize_fact_familiar,
normalize_fact_novel, modelNumber,
test_loader_smaller, 'fam', 1, 1)
novel_corrValues = storeretrieve_crosscorrelation_test(numItems, perms, bpsize,
bpPortion, shape_coeff,
color_coeff,
normalize_fact_familiar,
normalize_fact_novel,
modelNumber,
test_loader_smaller, 'nov',
1,1)
novel_corrValues_BN = storeretrieve_crosscorrelation_test(numItems, perms, bpsize,
bpPortion, shape_coeff,
color_coeff,
normalize_fact_familiar,
normalize_fact_novel,
modelNumber,
test_loader_smaller, 'nov',
0, 1)
familiar_corr_models.append(familiar_corrValues)
familiar_skip_models.append(familiar_corrValues_skip)
novel_corr_models.append(novel_corrValues)
novel_BN_models.append(novel_corrValues_BN)
familiar_corr_models_all=np.array(familiar_corr_models).reshape(-1,1)
novel_corr_models_all = np.array(novel_corr_models).reshape(1, -1)
familiar_skip_models_all=np.array(familiar_skip_models).reshape(1,-1)
novel_BN_models_all=np.array(novel_BN_models).reshape(1,-1)
familiar_corr_all.append(np.mean(familiar_corr_models_all))
familiar_corr_all_se.append(np.std(familiar_corr_models_all)/math.sqrt(numModels))
novel_corr_all.append(np.mean( novel_corr_models_all))
novel_corr_all_se.append(np.std(novel_corr_models_all)/math.sqrt(numModels))
familiar_skip_all.append(np.mean(familiar_skip_models_all))
familiar_skip_all_se.append(np.std(familiar_skip_models_all)/math.sqrt(numModels))
novel_BN_all.append(np.mean(novel_BN_models_all))
novel_BN_all_se.append(np.std(novel_BN_models_all)/math.sqrt(numModels))
#the mean correlation value between input and recontructed images for familiar and novel stimuli
outputFile.write('Familiar correlation\n')
for i in range(len(setSizes)):
outputFile.write('SS {0} Corr {1:.3g} SE {2:.3g}\n'.format(setSizes[i],familiar_corr_all[i],familiar_corr_all_se[i]))
outputFile.write('\nfNovel correlation\n')
for i in range(len(setSizes)):
outputFile.write(
'SS {0} Corr {1:.3g} SE {2:.3g}\n'.format(setSizes[i], novel_corr_all[i], novel_corr_all_se[i]))
outputFile.write('\nfamiliar correlation vis skip \n')
for i in range(len(setSizes)):
outputFile.write(
'SS {0} Corr {1:.3g} SE {2:.3g}\n'.format(setSizes[i], familiar_skip_all[i], familiar_skip_all_se[i]))
outputFile.write('\nnovel correlation via BN \n')
for i in range(len(setSizes)):
outputFile.write(
'SS {0} Corr {1:.3g} SE {2:.3g}\n'.format(setSizes[i], novel_BN_all[i], novel_BN_all_se[i]))
#This part (not included in the paper) visualizes the cross correlation between novel shapes retrieved from the skip and familiar shapes retrived from the BN
plt.figure()
familiar_corr_all=np.array(familiar_corr_all)
novel_corr_all=np.array(novel_corr_all)
plt.errorbar(setSizes,familiar_corr_all,yerr=familiar_corr_all_se, fmt='o',markersize=3)
plt.errorbar(setSizes, novel_corr_all, yerr=novel_corr_all_se, fmt='o', markersize=3)
plt.axis([0,6, 0, 1])
plt.xticks(np.arange(0,6,1))
plt.show()
#############################################
if latents_crossFlag ==1:
numModels=10
print('cross correlations for familiar items when reconstructed and when retrived from BN or L1+skip ')
setSizes=[1,2,3,4] #number of tokens
noskip_recon_mean=list()
noskip_recon_se=list()
noskip_ret_mean=list()
noskip_ret_se=list()
skip_recon_mean=list()
skip_recon_se=list()
skip_ret_mean=list()
skip_ret_se=list()
perms = bigpermnum #number of times it repeats storing/retrieval
for numItems in setSizes:
noskip_Reconmodels=list()
noskip_Retmodels=list()
skip_Reconmodels=list()
skip_Retmodels=list()
print('SetSize {num}'.format(num=numItems))
for modelNumber in range(1, numModels + 1): # which model should be run, this can be 1 through 10
load_checkpoint(
'output{modelNumber}/checkpoint_threeloss_singlegrad200.pth'.format(modelNumber=modelNumber))
# reset the data set for each set size
test_loader_smaller = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=numItems, shuffle=True,
num_workers=nw)
# This function is in tokens_capacity.py
#familiar items reconstrcuted via BN with no memory
noskip_noMem= storeretrieve_crosscorrelation_test(numItems, perms, bpsize, bpPortion, shape_coeff,
color_coeff,
normalize_fact_familiar,
normalize_fact_novel, modelNumber,
test_loader_smaller, 'fam', 0, 0)
# familiar items retrieved via BN
noskip_Mem = storeretrieve_crosscorrelation_test(numItems, perms, bpsize, bpPortion, shape_coeff,
color_coeff,
normalize_fact_familiar,
normalize_fact_novel, modelNumber,
test_loader_smaller, 'fam', 0, 1)
#recon from L1
skip_noMem = storeretrieve_crosscorrelation_test(numItems, perms, bpsize, bpPortion, shape_coeff,
color_coeff,
normalize_fact_familiar,
normalize_fact_novel, modelNumber,
test_loader_smaller, 'fam', 1, 0)
#retrieve from L1 +skip
skip_Mem = storeretrieve_crosscorrelation_test(numItems, perms, bpsize, bpPortion, shape_coeff,
color_coeff,
normalize_fact_familiar,
normalize_fact_novel, modelNumber,
test_loader_smaller, 'fam', 1, 1)
noskip_Reconmodels.append(noskip_noMem)
noskip_Retmodels.append(noskip_Mem)
skip_Reconmodels.append(skip_noMem)
skip_Retmodels.append(skip_Mem)
noskip_Reconmodels_all=np.array(noskip_Reconmodels).reshape(-1,1)
noskip_Retmodels_all=np.array(noskip_Retmodels).reshape(-1,1)
skip_Reconmodels_all = np.array(skip_Reconmodels).reshape(1, -1)
skip_Retmodels_all=np.array(skip_Retmodels).reshape(1,-1)
noskip_recon_mean.append(np.mean(noskip_Reconmodels_all))
noskip_recon_se.append(np.std(noskip_Reconmodels_all)/math.sqrt(numModels))
noskip_ret_mean.append(np.mean(noskip_Retmodels_all))
noskip_ret_se.append(np.std(noskip_Retmodels_all) / math.sqrt(numModels))
skip_recon_mean.append(np.mean(skip_Reconmodels_all))
skip_recon_se.append(np.std(skip_Reconmodels_all) / math.sqrt(numModels))
skip_ret_mean.append(np.mean(skip_Retmodels_all))
skip_ret_se.append(np.std(skip_Retmodels_all) / math.sqrt(numModels))
#the mean correlation value between input and recontructed images for familiar and novel stimuli
outputFile.write('correlation for recons from BN\n')
for i in range(len(setSizes)):
outputFile.write('SS {0} Corr {1:.3g} SE {2:.3g}\n'.format(setSizes[i],noskip_recon_mean[i],noskip_recon_se[i]))
outputFile.write('\nCorrelation for retrievals from BN\n')
for i in range(len(setSizes)):
outputFile.write('SS {0} Corr {1:.3g} SE {2:.3g}\n'.format(setSizes[i],noskip_ret_mean[i],noskip_ret_se[i]))
outputFile.write('\ncorrelation for recons from skip\n')
for i in range(len(setSizes)):
outputFile.write(
'SS {0} Corr {1:.3g} SE {2:.3g}\n'.format(setSizes[i], skip_recon_mean[i], skip_recon_se[i]))
outputFile.write('\ncorrelation for retrievals from skip\n')
for i in range(len(setSizes)):
outputFile.write(
'SS {0} Corr {1:.3g} SE {2:.3g}\n'.format(setSizes[i], skip_ret_mean[i], skip_ret_se[i]))
plt.figure()
correlations=np.array([skip_recon_mean,noskip_recon_mean, skip_ret_mean,noskip_ret_mean]).squeeze()
corr_se=np.array([skip_recon_se,noskip_recon_se, skip_ret_se,noskip_ret_se]).squeeze()
fig, ax = plt.subplots()
pos=np.array([1,2,3,4])
ax.bar(pos, correlations, yerr=corr_se, width=.4, alpha=.6, ecolor='black', color=['blue', 'blue', 'red', 'red'])
plt.show()
######################## Ability to extract the correct token from a shape-only stimulus
if bindingtestFlag ==1:
numModels=10
perms = bigpermnum
correctToken=np.tile(0.0,numModels)
correctToken_diff=np.tile(0.0,numModels)
accuracyColor=np.tile(0.0,numModels)
accuracyColor_diff=np.tile(0.0,numModels)
accuracyShape=np.tile(0.0,numModels)
accuracyShape_diff=np.tile(0.0,numModels)
for modelNumber in range(1,numModels+1):
print('testing binding cue retrieval')
# grey shape cue binding accuracy for only two items when the items are the same (e.g. two 3's ).
bs_testing = 2
correctToken[modelNumber-1],accuracyColor[modelNumber-1],accuracyShape[modelNumber-1] = binding_cue(bs_testing, perms, bpsize, bpPortion, shape_coeff, color_coeff, 'same',
modelNumber)
# grey shape cue binding accuracy for only two items when the two items are different
correctToken_diff[modelNumber-1],accuracyColor_diff[modelNumber-1] ,accuracyShape_diff[modelNumber-1] = binding_cue(bs_testing, perms, bpsize, bpPortion, shape_coeff, color_coeff
, 'diff', modelNumber)
correctToekn_all= correctToken.mean()
SD=correctToken.std()
correctToekn_diff_all=correctToken_diff.mean()
SD_diff=correctToken_diff.std()
accuracyColor_all=accuracyColor.mean()
SD_color= accuracyColor.std()
accuracyColor_diff_all=accuracyColor_diff.mean()
SD_color_diff=accuracyColor_diff.std()
accuracyShape_all=accuracyShape.mean()
SD_shape= accuracyShape.std()
accuracyShape_diff_all=accuracyShape_diff.mean()
SD_shape_diff=accuracyShape_diff.std()
outputFile.write('the correct retrieved token for same shapes condition is: {num} and SD is {sd}'.format(num=correctToekn_all, sd=SD))
outputFile.write('\n the correct retrieved color for same shapes condition is: {num} and SD is {sd}'.format(num=accuracyColor_all, sd=SD_color))
outputFile.write('\n the correct retrieved shape for same shapes condition is: {num} and SD is {sd}'.format(num=accuracyShape_all, sd=SD_shape))
outputFile.write(
'\n the correct retrieved token for different shapes condition is: {num} and SD is {sd}'.format(num=correctToekn_diff_all, sd=SD_diff))
outputFile.write(
'\n the correct retrieved color for different shapes condition is: {num} and SD is {sd}'.format(num=accuracyColor_diff_all, sd=SD_color_diff))
outputFile.write(
'\n the correct retrieved shape for different shapes condition is: {num} and SD is {sd}'.format(num=accuracyShape_diff_all, sd=SD_shape_diff))
#############Table 1 for the no memmory condition#####################
numModels = 1
perms=100
if Tab1Flag_noencoding == 1:
print('Table 1 shape labels predicted by the classifier before encoded in memory')
SSreport = np.tile(0.0,[perms,numModels])
SCreport = np.tile(0.0,[perms,numModels])
CCreport = np.tile(0.0,[perms,numModels])
CSreport = np.tile(0.0,[perms,numModels])
for temp in range(1,numModels +1): # which model should be run, this can be 1 through 10
modelNumber = 5
load_checkpoint('output{modelNumber}/checkpoint_threeloss_singlegrad200.pth'.format(modelNumber=modelNumber))
print('doing model {0} for Table 1'.format(modelNumber))
clf_shapeS = load('output{num}/ss{num}.joblib'.format(num=modelNumber))
clf_shapeC = load('output{num}/sc{num}.joblib'.format(num=modelNumber))
clf_colorC = load('output{num}/cc{num}.joblib'.format(num=modelNumber))
clf_colorS = load('output{num}/cs{num}.joblib'.format(num=modelNumber))
for rep in range(0,perms):
pred_cc, pred_cs, CCreport[rep,modelNumber - 1], CSreport[rep,modelNumber - 1] = classifier_color_test('noskip',
clf_colorC,
clf_colorS)
pred_ss, pred_sc, SSreport[rep,modelNumber-1], SCreport[rep,modelNumber-1] = classifier_shape_test('noskip', clf_shapeS, clf_shapeC)
print(CCreport)
CCreport=CCreport.reshape(1,-1)
CSreport=CSreport.reshape(1,-1)
SSreport=SSreport.reshape(1,-1)
SCreport=SCreport.reshape(1,-1)
outputFile.write('Table 1, accuracy of SS {0:.4g} SE {1:.4g}, accuracy of SC {2:.4g} SE {3:.4g}\n'.format(SSreport.mean(),SSreport.std()/math.sqrt(numModels*perms), SCreport.mean(), SCreport.std()/math.sqrt(numModels) ))
outputFile.write('Table 1, accuracy of CC {0:.4g} SE {1:.4g}, accuracy of CS {2:.4g} SE {3:.4g}\n'.format(CCreport.mean(),CCreport.std()/math.sqrt(numModels*perms), CSreport.mean(), CSreport.std()/math.sqrt(numModels)))
########################## Table 1 for memory conditions ######################################################################
if Tab1Flag == 1:
numModels=1
perms=1
SSreport_both = np.tile(0.0, [perms,numModels])
SCreport_both = np.tile(0.0, [perms,numModels])
CCreport_both = np.tile(0.0, [perms,numModels])
CSreport_both = np.tile(0.0, [perms,numModels])
SSreport_shape = np.tile(0.0, [perms,numModels])
SCreport_shape = np.tile(0.0, [perms,numModels])
CCreport_shape = np.tile(0.0, [perms,numModels])
CSreport_shape = np.tile(0.0, [perms,numModels])
SSreport_color = np.tile(0.0, [perms,numModels])
SCreport_color = np.tile(0.0, [perms,numModels])
CCreport_color = np.tile(0.0, [perms,numModels])
CSreport_color = np.tile(0.0, [perms,numModels])
SSreport_l1 = np.tile(0.0, [perms,numModels])
SCreport_l1= np.tile(0.0, [perms,numModels])
CCreport_l1 = np.tile(0.0, [perms,numModels])
CSreport_l1 = np.tile(0.0, [perms,numModels])
SSreport_l2 = np.tile(0.0, [perms,numModels])
SCreport_l2 = np.tile(0.0, [perms,numModels])
CCreport_l2 = np.tile(0.0, [perms,numModels])
CSreport_l2 = np.tile(0.0, [perms,numModels])
for modelNumber in range(1, numModels + 1): # which model should be run, this can be 1 through 10
load_checkpoint(
'output{modelNumber}/checkpoint_threeloss_singlegrad200.pth'.format(modelNumber=modelNumber))
print('doing model {0} for Table 1'.format(modelNumber))
clf_shapeS = load('output{num}/ss{num}.joblib'.format(num=modelNumber))
clf_shapeC = load('output{num}/sc{num}.joblib'.format(num=modelNumber))
clf_colorC = load('output{num}/cc{num}.joblib'.format(num=modelNumber))
clf_colorS = load('output{num}/cs{num}.joblib'.format(num=modelNumber))
print('Doing Table 1')
for rep in range(0,perms):
numcolors = 0
colorlabels = thecolorlabels(test_dataset)
bs_testing = 1000 # 20000 is the limit
test_loader_smaller = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=bs_testing, shuffle=True,