ludusc commited on
Commit
1efb52e
1 Parent(s): 56df1ee

cumulative change

Browse files
backend/disentangle_concepts.py CHANGED
@@ -103,6 +103,10 @@ def regenerate_images(model, z, decision_boundary, min_epsilon=-3, max_epsilon=3
103
 
104
  return images, lambdas
105
 
 
 
 
 
106
  def generate_original_image(z, model, latent_space='Z'):
107
  """
108
  The generate_original_image function takes in a latent vector and the model,
 
103
 
104
  return images, lambdas
105
 
106
+ def generate_joint_effect(model, z, decision_boundaries, min_epsilon=-3, max_epsilon=3, count=5, latent_space='Z'):
107
+ decision_boundary_joint = np.sum(decision_boundaries, axis=1)
108
+ return regenerate_images(model, z, decision_boundary_joint, min_epsilon=min_epsilon, max_epsilon=max_epsilon, count=count, latent_space=latent_space)
109
+
110
  def generate_original_image(z, model, latent_space='Z'):
111
  """
112
  The generate_original_image function takes in a latent vector and the model,
pages/2_Concepts_comparison.py CHANGED
@@ -5,8 +5,8 @@ import pickle
5
  import pandas as pd
6
  import numpy as np
7
  from pyvis.network import Network
8
- import networkx as nx
9
 
 
10
  from sklearn.metrics.pairwise import cosine_similarity
11
 
12
  from matplotlib.backends.backend_agg import RendererAgg
@@ -94,8 +94,6 @@ smoothgrad_col_1, smoothgrad_col_2, smoothgrad_col_3, smoothgrad_col_4, smoothgr
94
  # ---------------------------- DISPLAY COL 1 ROW 1 ------------------------------
95
  with output_col_1:
96
  vectors, nodes_in_common, performances = get_concepts_vectors(concept_ids, annotations, ann_df, latent_space=space_id)
97
- # st.write(f'Class ID {input_id} - {input_label}: {pred_prob*100:.3f}% confidence')
98
- #st.write('Concept vector', separation_vector)
99
  header_col_1.write(f'Concepts {", ".join(concept_ids)} - Latent space {space_id} - Relevant nodes in common: {nodes_in_common} - Performance of the concept vectors: {performances}')# - Nodes {",".join(list(imp_nodes))}')
100
 
101
  edges = []
@@ -144,7 +142,7 @@ with output_col_1:
144
 
145
  with output_col_2:
146
  with open('data/CLIP_vecs.pkl', 'rb') as f:
147
- vectors = pickle.load(f)
148
 
149
  # st.write(f'Class ID {input_id} - {input_label}: {pred_prob*100:.3f}% confidence')
150
  #st.write('Concept vector', separation_vector)
@@ -155,7 +153,7 @@ with output_col_2:
155
  for c2 in concept_ids:
156
  if c1 != c2:
157
  print(f'Similarity between {c1} and {c2}')
158
- similarity = cosine_similarity(vectors[c1].reshape(1, -1), vectors[c2].reshape(1, -1))
159
  print(np.round(similarity[0][0], 3))
160
  edges_clip.append((c1, c2, float(np.round(similarity[0][0], 3))))
161
 
@@ -195,65 +193,69 @@ with output_col_2:
195
  components.html(HtmlFile.read(), height=435)
196
 
197
  # ----------------------------- INPUT column 2 & 3 ----------------------------
198
- # with input_col_2:
199
- # with st.form('image_form'):
200
 
201
- # # image_id = st.number_input('Image ID: ', format='%d', step=1)
202
- # st.write('**Choose or generate a random image to test the disentanglement**')
203
- # chosen_image_id_input = st.empty()
204
- # image_id = chosen_image_id_input.number_input('Image ID:', format='%d', step=1, value=st.session_state.image_id)
205
 
206
- # choose_image_button = st.form_submit_button('Choose the defined image')
207
- # random_id = st.form_submit_button('Generate a random image')
208
 
209
- # if random_id:
210
- # image_id = random.randint(0, 100000)
211
- # st.session_state.image_id = image_id
212
- # chosen_image_id_input.number_input('Image ID:', format='%d', step=1, value=st.session_state.image_id)
213
 
214
- # if choose_image_button:
215
- # image_id = int(image_id)
216
- # st.session_state.image_id = int(image_id)
217
- # # st.write(image_id, st.session_state.image_id)
218
-
219
- # with input_col_3:
220
- # with st.form('Variate along the disentangled concept'):
221
- # st.write('**Set range of change**')
222
- # chosen_epsilon_input = st.empty()
223
- # epsilon = chosen_epsilon_input.number_input('Epsilon:', min_value=1, step=1)
224
- # epsilon_button = st.form_submit_button('Choose the defined epsilon')
225
 
226
  # # ---------------------------- DISPLAY COL 2 ROW 1 ------------------------------
227
 
228
- # #model = torch.load('./data/model_files/pytorch_model.bin', map_location=torch.device('cpu'))
229
- # with dnnlib.util.open_url('./data/model_files/network-snapshot-010600.pkl') as f:
230
- # model = legacy.load_network_pkl(f)['G_ema'].to('cpu') # type: ignore
231
 
232
- # original_image_vec = annotations['z_vectors'][st.session_state.image_id]
233
- # img = generate_original_image(original_image_vec, model)
234
- # # input_image = original_image_dict['image']
235
- # # input_label = original_image_dict['label']
236
- # # input_id = original_image_dict['id']
 
 
 
 
 
 
 
237
 
238
- # with smoothgrad_col_3:
239
- # st.image(img)
240
- # smooth_head_3.write(f'Base image')
241
 
242
 
243
- # images, lambdas = regenerate_images(model, original_image_vec, separation_vector, min_epsilon=-(int(epsilon)), max_epsilon=int(epsilon))
244
 
245
- # with smoothgrad_col_1:
246
- # st.image(images[0])
247
- # smooth_head_1.write(f'Change of {np.round(lambdas[0], 2)}')
248
 
249
- # with smoothgrad_col_2:
250
- # st.image(images[1])
251
- # smooth_head_2.write(f'Change of {np.round(lambdas[1], 2)}')
252
 
253
- # with smoothgrad_col_4:
254
- # st.image(images[3])
255
- # smooth_head_4.write(f'Change of {np.round(lambdas[3], 2)}')
256
 
257
- # with smoothgrad_col_5:
258
- # st.image(images[4])
259
- # smooth_head_5.write(f'Change of {np.round(lambdas[4], 2)}')
 
5
  import pandas as pd
6
  import numpy as np
7
  from pyvis.network import Network
 
8
 
9
+ import random
10
  from sklearn.metrics.pairwise import cosine_similarity
11
 
12
  from matplotlib.backends.backend_agg import RendererAgg
 
94
  # ---------------------------- DISPLAY COL 1 ROW 1 ------------------------------
95
  with output_col_1:
96
  vectors, nodes_in_common, performances = get_concepts_vectors(concept_ids, annotations, ann_df, latent_space=space_id)
 
 
97
  header_col_1.write(f'Concepts {", ".join(concept_ids)} - Latent space {space_id} - Relevant nodes in common: {nodes_in_common} - Performance of the concept vectors: {performances}')# - Nodes {",".join(list(imp_nodes))}')
98
 
99
  edges = []
 
142
 
143
  with output_col_2:
144
  with open('data/CLIP_vecs.pkl', 'rb') as f:
145
+ vectors_CLIP = pickle.load(f)
146
 
147
  # st.write(f'Class ID {input_id} - {input_label}: {pred_prob*100:.3f}% confidence')
148
  #st.write('Concept vector', separation_vector)
 
153
  for c2 in concept_ids:
154
  if c1 != c2:
155
  print(f'Similarity between {c1} and {c2}')
156
+ similarity = cosine_similarity(vectors_CLIP[c1].reshape(1, -1), vectors_CLIP[c2].reshape(1, -1))
157
  print(np.round(similarity[0][0], 3))
158
  edges_clip.append((c1, c2, float(np.round(similarity[0][0], 3))))
159
 
 
193
  components.html(HtmlFile.read(), height=435)
194
 
195
  # ----------------------------- INPUT column 2 & 3 ----------------------------
196
+ with input_col_2:
197
+ with st.form('image_form'):
198
 
199
+ # image_id = st.number_input('Image ID: ', format='%d', step=1)
200
+ st.write('**Choose or generate a random image to test the disentanglement**')
201
+ chosen_image_id_input = st.empty()
202
+ image_id = chosen_image_id_input.number_input('Image ID:', format='%d', step=1, value=st.session_state.image_id)
203
 
204
+ choose_image_button = st.form_submit_button('Choose the defined image')
205
+ random_id = st.form_submit_button('Generate a random image')
206
 
207
+ if random_id:
208
+ image_id = random.randint(0, 50000)
209
+ st.session_state.image_id = image_id
210
+ chosen_image_id_input.number_input('Image ID:', format='%d', step=1, value=st.session_state.image_id)
211
 
212
+ if choose_image_button:
213
+ image_id = int(image_id)
214
+ st.session_state.image_id = int(image_id)
215
+ # st.write(image_id, st.session_state.image_id)
216
+
217
+ with input_col_3:
218
+ with st.form('Variate along the disentangled concepts'):
219
+ st.write('**Set range of change**')
220
+ chosen_epsilon_input = st.empty()
221
+ epsilon = chosen_epsilon_input.number_input('Epsilon:', min_value=1, step=1)
222
+ epsilon_button = st.form_submit_button('Choose the defined epsilon')
223
 
224
  # # ---------------------------- DISPLAY COL 2 ROW 1 ------------------------------
225
 
 
 
 
226
 
227
+ with dnnlib.util.open_url('./data/model_files/network-snapshot-010600.pkl') as f:
228
+ model = legacy.load_network_pkl(f)['G_ema'].to('cpu') # type: ignore
229
+
230
+ if st.session_state.space_id == 'Z':
231
+ original_image_vec = annotations['z_vectors'][st.session_state.image_id]
232
+ else:
233
+ original_image_vec = annotations['w_vectors'][st.session_state.image_id]
234
+
235
+ img = generate_original_image(original_image_vec, model, latent_space=st.session_state.space_id)
236
+ # input_image = original_image_dict['image']
237
+ # input_label = original_image_dict['label']
238
+ # input_id = original_image_dict['id']
239
 
240
+ with smoothgrad_col_3:
241
+ st.image(img)
242
+ smooth_head_3.write(f'Base image')
243
 
244
 
245
+ images, lambdas = generate_joint_effect(model, original_image_vec, vectors, min_epsilon=-(int(epsilon)), max_epsilon=int(epsilon), latent_space=st.session_state.space_id)
246
 
247
+ with smoothgrad_col_1:
248
+ st.image(images[0])
249
+ smooth_head_1.write(f'Change of {np.round(lambdas[0], 2)}')
250
 
251
+ with smoothgrad_col_2:
252
+ st.image(images[1])
253
+ smooth_head_2.write(f'Change of {np.round(lambdas[1], 2)}')
254
 
255
+ with smoothgrad_col_4:
256
+ st.image(images[3])
257
+ smooth_head_4.write(f'Change of {np.round(lambdas[3], 2)}')
258
 
259
+ with smoothgrad_col_5:
260
+ st.image(images[4])
261
+ smooth_head_5.write(f'Change of {np.round(lambdas[4], 2)}')