forked from i-deal/MLR-2.0
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BPreconstruction.py
executable file
·298 lines (232 loc) · 12.7 KB
/
BPreconstruction.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
# -*- coding: utf-8 -*-
"""BWBP_ReconstructionfromLayer1.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1n4E2TgkeEQCevnGnrW3ZBN5qRsguer8L
"""
#MNIST VAE from http://
# Modified by Brad Wyble and Shekoo Hedayati
# 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
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
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
import config
from IPython.display import Image, display
import cv2
from PIL import ImageFilter
config.init()
from config import numcolors
global numcolors
from PIL import Image
from mVAE import *
from PIL import Image, ImageOps, ImageEnhance, __version__ as PILLOW_VERSION
#print('twoloss singlegrad 75')
for outs in range(1,2):
load_checkpoint('output{num}/checkpoint_threeloss_singlegrad200.pth'.format(num=outs))
zc=torch.randn(64,8).cuda()*1
zs=torch.randn(64,8).cuda()*1
with torch.no_grad():
sample = vae.decoder_noskip(zs,zc,0).cuda()
sample_c= vae.decoder_noskip(zs*0,zc,0).cuda()
sample_s = vae.decoder_noskip(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=outs))
save_image(sample_c[0:8], 'output{num}/sample_c.png'.format(num=outs))
save_image(sample_s[0:8], 'output{num}/sample_s.png'.format(num=outs))
print('Loading the classifiers')
#clf_shapeS=load('output{num}/ss{num}.joblib'.format(num=outs))
# clf_shapeC=load('output{num}/sc{num}.joblib'.format(num=outs))
# clf_colorC=load('output{num}/cc{num}.joblib'.format(num=outs))
# clf_colorS=load('output{num}/cs{num}.joblib'.format(num=outs))
print(' shape labels predicted by the classifier')
#classifier_shape_test('all', clf_shapeS, clf_shapeC)
# print(' shape labels predicted by the classifier')
# classifier_shape_test('all', clf_shapeS, clf_shapeC)
# print(' color labels predicted by the classifier')
#classifier_color_test('all', clf_colorC, clf_colorS)
'''**Show the model a stimulus, encode it into the binding pool, then retrieve it and classify the output**'''
### Testing the classifier on BP or the activation maps
numcolors = 0
colorlabels = np.random.randint(0, 10, 100000)
test_colorlabels = thecolorlabels(test_dataset)
bs_testing = 2000 # 10000 is the limit
layernum = 1 # either one or two or zero if we want to reconstruct familiar shapes
shape_coeff = 1
color_coeff = 1
bpsize =1000
numimg= 8 #number of images to display
#test_loader_smaller = torch.utils.data.DataLoader(dataset=test_dataset_MNIST, batch_size=bs_testing, shuffle=True, num_workers=nw)
# upload Bengali images
trns=0
novel=1 #if we want to test novel charachetrs
n_root=2
all_imgs = []
if novel:
layernum = 1
numimg = 6
for i in range (1,numimg+1):
img=Image.open('{each}_thick.png'.format(each=i))
img_new=Colorize_func(img)
trans2=transforms.ToTensor()
image=trans2(img_new)
all_imgs.append(image)
all_imgs=torch.stack(all_imgs)
imgs = all_imgs.view(-1, 3 * 28 * 28).cuda()
else:
ftest_dataset = datasets.FashionMNIST(root='./fashionmnist_data/', train=False,
transform=transforms.Compose([Colorize_func, transforms.ToTensor()]),
download=False)
test_dataset_MNIST = datasets.MNIST(root='./mnist_data/', train=False,
transform=transforms.Compose([Colorize_func, transforms.ToTensor()]),
download=False)
test_dataset = torch.utils.data.ConcatDataset((test_dataset_MNIST, ftest_dataset))
test_loader_smaller = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=bs, shuffle=True,
num_workers=nw)
images, labels = next(iter(test_loader_smaller))
imgs = images.view(-1, 3 * 28 * 28).cuda()
if trns:
print('generating encoder and latent activations')
l1_act, l2_act, shape_act, color_act = activations(imgs)
#l1_act = l1_act + 1
#l1_act=torch.log(l1_act)
#l1_act =torch.pow(l1_act,1/ n_root)
l1_act=l1_act*val
print('feeding all layers through the BP')
BP_in, shape_out_BP, color_out_BP, BP_layerI_out, BP_layer2_out = BP(bpsize,l1_act, l2_act, shape_act, color_act, shape_coeff, color_coeff )
#BP_layerI_out=torch.exp(BP_layerI_out)
#BP_layerI_out = BP_layerI_out - 1
BP_layerI_out=BP_layerI_out/val
#BP_layerI_out=torch.pow(BP_layerI_out, n_root)
else:
if layernum==1:
l1_act, l2_act, shape_act, color_act = activations(imgs)
l1_act_tr= l1_act.clone()
l1_act_tr=l1_act_tr+1
l1_act_tr=torch.log10(l1_act_tr)
#l1_act_tr[l1_act_tr == 0]= -4
BP_in, shape_out_BP, color_out_BP, BP_layerI_out, BP_layer2_out = BP(bpsize, l1_act_tr, l2_act, shape_act,color_act, shape_coeff, color_coeff)
#BP_layerI_out[BP_layerI_out < 0] = 0
BP_layerI_out = torch.pow(10, BP_layerI_out)-1
BP_layerI_out[BP_layerI_out <0]=0
else:
l1_act, l2_act, shape_act, color_act = activations(imgs)
BP_in, shape_out_BP, color_out_BP, BP_layerI_out, BP_layer2_out = BP(bpsize, l1_act, l2_act, shape_act,
color_act, shape_coeff, color_coeff)
# print(shape_out_BP)
#print(color_out_BP)
# BP_layerI_out=torch.pow(10,BP_layerI_out)
#BP_layerI_out = torch.exp(BP_layerI_out)
#BP_layerI_out=BP_layerI_out-1
#l1_act_zeros = l1_act == 0 #set corresponding activations to zero
l1_plt = l1_act.view(1, -1).cpu()
BP_layerI_out_plt = BP_layerI_out.view(1, -1).cpu()
l1_plt = torch.squeeze(l1_plt)
BP_layerI_out_plt = torch.squeeze(BP_layerI_out_plt)
plt.figure()
plt.subplot(221)
plt.plot(l1_plt, 'b')
plt.ylabel('L1 before BP')
plt.subplot(222)
# plt.hist(l1_plt, 100, facecolor='b')
plt.hist(l1_plt[l1_plt != 0], 100, facecolor='b')
plt.subplot(223)
plt.plot(BP_layerI_out_plt, 'r')
plt.ylabel('L1 after BP')
plt.subplot(224)
plt.hist(BP_layerI_out_plt[BP_layerI_out_plt != 0], 100, facecolor='r')
# plt.hist(BP_layerI_out_plt, 100, facecolor='r')
plt.show()
print('generating from the latents from layer{}'.format(layernum))
#shape_act_bp, color_act_bp = activation_fromBP(BP_layerI_out, BP_layer2_out, layernum)
"""Show a set of stimuli, then retrieve them from the BP"""
#### Reconstruction from the BP and VAE
# number of images to display
np.set_printoptions(threshold=1000) # not sure if this is necessary
print('saving images to folder')
# reconstruct activations from layer 1
sampleVAE = vae.decoder_noskip(shape_act, color_act, 0).cuda() # reconstruction directly from the latents
sampleBP = vae.decoder_noskip(shape_out_BP, color_out_BP, 0).cuda() # reconstruction of the image after BP memory retrieval
sampleBP_s = vae.decoder_noskip(shape_out_BP, color_out_BP * 0, 0).cuda()
sampleBP_c = vae.decoder_noskip(shape_out_BP * 0, color_out_BP, 0).cuda()
if layernum == 1:
recon_layer1_skip, mu_color, log_var_color, mu_shape, log_var_shape = vae.forward_layers(l1_act, l2_act,layernum, 'skip')
recon_layer1_noskip, mu_color, log_var_color, mu_shape, log_var_shape = vae.forward_layers(l1_act, l2_act, layernum, 'noskip')
reconBP_layer1_all, mu_color, log_var_color, mu_shape, log_var_shape = vae.forward_layers(BP_layerI_out, BP_layer2_out,layernum, 'all')
reconBP_layer1_skip, mu_color, log_var_color, mu_shape, log_var_shape = vae.forward_layers(BP_layerI_out,BP_layer2_out,layernum, 'skip')
reconBP_layer1_noskip, mu_color, log_var_color, mu_shape, log_var_shape = vae.forward_layers(BP_layerI_out,BP_layer2_out, layernum, 'noskip')
save_image(
torch.cat([imgs[0: numimg].view( numimg, 3, 28, 28), recon_layer1_skip[0: numimg].view( numimg, 3, 28, 28),
reconBP_layer1_skip[0: numimg].view( numimg, 3, 28, 28)], 0),
f'out_novel.png',
nrow=numimg,
normalize=False,
range=(-1, 1),
)
save_image(recon_layer1_skip[0: numimg].view( numimg, 3, 28, 28), 'output{num}/recon_layer1_skip{num}.png'.format(num=outs))
save_image(recon_layer1_noskip[0: numimg].view( numimg, 3, 28, 28),'output{num}/recon_layer1_noskip{num}.png'.format(num=outs))
save_image(reconBP_layer1_all[0: numimg].view( numimg, 3, 28, 28), 'output{num}/reconBP_layer1_all{num}.png'.format(num=outs))
save_image(reconBP_layer1_skip[0: numimg].view( numimg, 3, 28, 28), 'output{num}/reconBP_layer1_skip{num}.png'.format(num=outs))
save_image(reconBP_layer1_noskip[0: numimg].view( numimg, 3, 28, 28), 'output{num}/reconBP_layer1_noskip{num}.png'.format(num=outs))
save_image(
torch.cat([imgs[0: numimg].view(numimg, 3, 28, 28), sampleVAE[0: numimg].view(numimg, 3, 28, 28),
reconBP_layer1_noskip[0: numimg].view( numimg, 3, 28, 28)], 0),
f'out_l1.png',
nrow=numimg,
normalize=False,
range=(-1, 1),
)
elif layernum == 2:
sampleBP_layer2_all, mu_color, log_var_color, mu_shape, log_var_shape = vae.forward_layers(BP_layerI_out, BP_layer2_out, layernum, 'all')
sampleBP_layer2_skip, mu_color, log_var_color, mu_shape, log_var_shape = vae.forward_layers(BP_layerI_out,BP_layer2_out, layernum, 'skip')
sampleBP_layer2_noskip, mu_color, log_var_color, mu_shape, log_var_shape = vae.forward_layers(BP_layerI_out, BP_layer2_out,layernum,'noskip')
save_image(sampleBP_layer2_all[0: numimg].view(numimg, 3, 28, 28), 'output{num}/sampleBP_layer2_all{num}.png'.format(num=outs))
save_image(sampleBP_layer2_skip[0: numimg].view(numimg, 3, 28, 28), 'output{num}/sampleBP_layer2_skip{num}.png'.format(num=outs))
save_image(sampleBP_layer2_noskip[0: numimg].view(numimg, 3, 28, 28),'output{num}/sampleBP_layer2_noskip{num}.png'.format(num=outs))
save_image(
torch.cat([imgs[0: numimg].view(numimg, 3, 28, 28), sampleVAE[0: numimg].view(numimg, 3, 28, 28),
sampleBP_layer2_noskip[0: numimg].view(numimg, 3, 28, 28)], 0),
f'out_l2.png',
nrow=numimg,
normalize=False,
range=(-1, 1),
)
else:
save_image(
torch.cat([imgs[0: numimg].view(numimg, 3, 28, 28), sampleVAE[0: numimg].view(numimg, 3, 28, 28),sampleBP[0: numimg].view(numimg, 3, 28, 28), sampleBP_s[0: numimg].view(numimg, 3, 28, 28),sampleBP_c[0: numimg].view(numimg, 3, 28, 28)], 0),
f'out.png',
nrow=numimg,
normalize=False,
range=(-1, 1),
)
BP_layerI_out = BP_layerI_out.squeeze()
a = l1_act.view(1, -1).cpu().numpy()
b = BP_layerI_out.view(1, -1).cpu().numpy()
print('Correlation between the original Layer 1 activation values and after BP')
print(np.corrcoef(a, b))
save_image(imgs[0: numimg].view( numimg, 3, 28, 28), 'output{num}/foriginal{num}.png'.format(num=outs))
save_image(sampleVAE[0: numimg].view( numimg, 3, 28, 28), 'output{num}/fsampleVAE{num}.png'.format(num=outs))
save_image(sampleBP[0: numimg].view( numimg, 3, 28, 28), 'output{num}/fsampleBP{num}.png'.format(num=outs))
save_image(sampleBP_s[0: numimg].view( numimg, 3, 28, 28), 'output{num}/fsampleBP_s{num}.png'.format(num=outs))
save_image(sampleBP_c[0: numimg].view( numimg, 3, 28, 28), 'output{num}/fsampleBP_c{num}.png'.format(num=outs))
#defining the classifiers for the fashion MNIST