Skip to content

Commit 9d0097d

Browse files
committed
Updated Sampler
1 parent 7fb8384 commit 9d0097d

File tree

2 files changed

+26
-24
lines changed

2 files changed

+26
-24
lines changed

BioExp/clusters/concept.py

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,6 @@ def flow_based_identifier(self, concept_info,
170170
exp_features = layers.Conv2D(1,1, name='Expectation')(features)
171171
model = Model(inputs = self.model.input, outputs=exp_features)
172172

173-
174173
# newmodel = Sequential()
175174
# newmodel.add(model)
176175
# newmodel.add()
@@ -180,22 +179,21 @@ def flow_based_identifier(self, concept_info,
180179
# newmodel.layers[ii].set_weights(self.model.layers[ii].get_weights())
181180
model.layers[-1].set_weights((np.ones((1, 1, len(total_filters), 1)), np.ones(1)))
182181

183-
184182
grad = singlelayercam(model, test_img,
185183
nclasses = 1,
186184
name = concept_info['concept_name'],
187185
st_layer_idx = -1,
188-
end_layer_idx = 1,
186+
end_layer_idx = -3,
189187
threshold = 0.5)
190188

191189
if base_grad == True:
192190
print ("[INFO: BioExp Concept Identification] Base Concept in layer {}".format(layer_name))
193191
else:
194192
print ("[INFO: BioExp Concept Identification] Identified Concept {} in layer {}".format(concept_info['concept_name'], layer_name))
195193

196-
del model, newmodel
194+
del model
197195

198-
return grad[0]
196+
return grad
199197

200198
def flow_based_identifier_no_conv(self, concept_info, save_path, test_img, base_grad=False):
201199

@@ -226,7 +224,7 @@ def flow_based_identifier_no_conv(self, concept_info, save_path, test_img, base_
226224
save_path = save_path,
227225
name = concept_info['concept_name'],
228226
st_layer_idx = -1,
229-
end_layer_idx = -2,
227+
end_layer_idx = -3,
230228
threshold = 0.5)
231229
print ("[INFO: BioExp Concept Identification] Identified Concept {} in layer {}".format(concept_info['concept_name'], layer_name))
232230

@@ -237,12 +235,13 @@ def flow_based_identifier_no_conv(self, concept_info, save_path, test_img, base_
237235

238236
def _gaussian_sampler_(self, data, size, ax=-1):
239237
shape = np.mean(data, ax).shape + (size,)
240-
return lambda: np.std(data, -1)[..., None] * np.random.randn(*list(shape)) + np.mean(data, -1)[..., None] # np.random.normal(loc=np.mean(data, axis=ax), scale=np.std(data, axis=ax), size=size)
238+
return lambda: np.std(data, -1)[..., None] * np.random.randn(*list(shape)) + np.mean(data, -1)[..., None]
239+
# return lambda: np.random.normal(np.mean(data, -1)[..., None], np.std(data, -1)[..., None], size = size)
241240

242241
def _uniform_sampler_(self, data, size, ax=-1):
243242
shape = np.mean(data, ax).shape + (size,)
244-
print(np.quantile(data, 0.1, axis=-1)[..., None].shape)
245-
return lambda: np.random.uniform(np.quantile(data, 0, axis=-1)[..., None], np.quantile(data, 1, axis=-1)[..., None], size = size)
243+
return lambda: np.quantile(data, 0.1, axis=-1)[..., None] * np.random.rand(*list(shape)) + np.quantile(data, 0.9, axis=-1)[..., None]
244+
# return lambda: np.random.uniform(np.quantile(data, 0.1, axis=-1)[..., None], np.quantile(data, 0.9, axis=-1)[..., None], size = size)
246245

247246
def concept_distribution(self, concept_info):
248247
"""
@@ -329,25 +328,24 @@ def concept_robustness(self, concept_info,
329328
except: pass
330329

331330
self.model.layers[node_idx].set_weights(occluded_weights)
332-
model = Model(inputs = self.model.input, outputs=self.model.get_layer(concept_info['layer_name']).output)
333-
334-
newmodel = Sequential()
335-
newmodel.add(model)
336-
newmodel.add(layers.Conv2D(1,1))
331+
features = self.model.get_layer(concept_info['layer_name']).output
332+
exp_features = layers.Conv2D(1,1, name='Expectation')(features)
333+
model = Model(inputs = self.model.input, outputs=exp_features)
337334

338335
# for ii in range(len(self.model.layers)):
339336
# newmodel.layers[ii].set_weights(self.model.layers[ii].get_weights())
340-
newmodel.layers[-1].set_weights((np.ones((1, 1, len(total_filters), 1)), np.ones(1)))
337+
model.layers[-1].set_weights((np.ones((1, 1, len(total_filters), 1)), np.ones(1)))
341338

342-
nclass_grad = singlelayercam(newmodel, test_img,
339+
nclass_grad = singlelayercam(model, test_img,
343340
nclasses = 1,
344341
name = concept_info['concept_name'],
345342
st_layer_idx = -1,
346-
end_layer_idx = -2,
343+
end_layer_idx = -3,
347344
threshold = 0.5)
348-
gradlist.append(nclass_grad[0])
349345

350-
del model, newmodel
346+
gradlist.append(nclass_grad)
347+
348+
del model
351349

352350
# try:
353351
# del bias_sampler

BioExp/spatial/flow.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ def singlelayercam(model, img,
1818
nclasses = 2,
1919
save_path = None,
2020
name = None,
21+
filter_indices=[0],
2122
end_layer_idx = 3,
2223
st_layer_idx = -1,
2324
threshold = 0.5,
@@ -34,11 +35,11 @@ def singlelayercam(model, img,
3435
plt.figure(figsize=(10*nclasses, 10))
3536
gs = gridspec.GridSpec(1, nclasses)
3637
gs.update(wspace=0.025, hspace=0.05)
37-
38+
3839
nclass_grad = []
39-
for i in range(nclasses):
40+
for i in range(len(filter_indices)):
4041
grads_ = visualize_cam(model, st_layer_idx, filter_indices=i, penultimate_layer_idx = end_layer_idx,
41-
seed_input = img[None, ...], backprop_modifier = modifier)
42+
seed_input = img[None, ...], backprop_modifier = None)
4243
if save_path is not None:
4344
ax = plt.subplot(gs[i])
4445
im = ax.imshow(np.squeeze(img), vmin=0, vmax=1)
@@ -49,14 +50,17 @@ def singlelayercam(model, img,
4950
ax.tick_params(bottom='off', top='off', labelbottom='off' )
5051

5152
nclass_grad.append(grads_)
52-
53+
54+
if len(np.array(nclass_grad).shape) == 3:
55+
nclass_grad = np.mean(np.array(nclass_grad), axis=0)
56+
5357
if save_path is not None:
5458
divider = make_axes_locatable(ax)
5559
cax = divider.append_axes("right", size="5%", pad=0.2)
5660
# cb = plt.colorbar(im, ax=ax, cax=cax )
5761
os.makedirs(save_path, exist_ok = True)
5862
plt.savefig(os.path.join(save_path, name +'.png'), bbox_inches='tight')
59-
return np.array(nclass_grad)
63+
return np.squeeze(np.array(nclass_grad))
6064

6165

6266
def cam(model, img, gt=None,

0 commit comments

Comments
 (0)