hkayabilisim commited on
Commit
888babf
·
1 Parent(s): 7bdbd39

Upload 10 files

Browse files
Files changed (10) hide show
  1. IMG_0154.jpg +0 -0
  2. IMG_0155.jpg +0 -0
  3. IMG_0156.jpg +0 -0
  4. IMG_0157.jpg +0 -0
  5. IMG_0158.jpg +0 -0
  6. IMG_0159.jpg +0 -0
  7. IMG_0160.jpg +0 -0
  8. app.py +283 -188
  9. jeep.png +0 -0
  10. requirements.txt +1 -4
IMG_0154.jpg ADDED
IMG_0155.jpg ADDED
IMG_0156.jpg ADDED
IMG_0157.jpg ADDED
IMG_0158.jpg ADDED
IMG_0159.jpg ADDED
IMG_0160.jpg ADDED
app.py CHANGED
@@ -1,25 +1,19 @@
1
- #%% TODO: Very important
2
- # Class-agnostic sensitivity measurement
3
- # instead of softmax, get the logits
4
- # make them unit-norm
5
- # This means that every model output is a point
6
- # in 1000-dimensional hyper-sphere. So it could be possible
7
- # to measure the sensitivity of the needle.
8
- #%% Libraries
9
- import cv2
10
- from segment_anything import SamAutomaticMaskGenerator, sam_model_registry
11
- import matplotlib.pyplot as plt
12
  import numpy as np
13
- from torchvision.io import read_image
14
- from torchvision.models import resnet50, ResNet50_Weights
15
  import torch
16
- from itertools import combinations
17
- import seaborn as sns
18
- import gradio as gr
19
- from PIL import Image
20
  import matplotlib
21
- matplotlib.use('agg')
 
 
 
22
  import wget
 
 
23
 
24
  # Vanilla Legendre between [0,1]
25
  def Pn(m, x):
@@ -29,205 +23,306 @@ def Pn(m, x):
29
  return x
30
  else:
31
  return (2*m-1)*x*Pn(m-1, x)/m - (m-1)*Pn(m-2, x)/m
 
32
  # Legendre between [a,b]
33
  def L(a,b,m,x):
34
  return np.sqrt((2*m+1)/(b-a))*Pn(m, 2*(x-b)/(b-a)+1)
35
 
36
- URL = "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth"
37
- response = wget.download(URL, "sam_vit_b_01ec64.pth")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- #%% show segments on the image
40
- def segment_heatmap_image(img, masks, mask_weights, alpha=0.4):
41
- w, h, c = img.shape
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  img_grad3d = np.dstack([img_gray, img_gray, img_gray])
45
  print(img.shape, img_gray.shape)
46
  segment_image = np.zeros((w,h)).astype(np.uint8)
47
- for mask, weight in zip(masks, mask_weights):
 
 
 
 
48
  segment_image[mask['segmentation'] == True] = int(255*weight)
49
- #blur = cv2.GaussianBlur(segment_image,(13,13), 11)
50
  heatmap_img = cv2.applyColorMap(segment_image, cv2.COLORMAP_JET)
51
- super_imposed_img = cv2.addWeighted(heatmap_img, alpha, img_grad3d, 1-alpha, 0)
52
- return super_imposed_img, segment_image
53
-
54
- def run(gui_input_image_WHC):
55
- print("hello----------",type(gui_input_image_WHC))
56
- print(gui_input_image_WHC.shape)
57
- input_image_torch_CWH = gui_input_image_WHC.transpose(2,0,1)
58
- print(input_image_torch_CWH.shape)
59
- input_image_torch = torch.from_numpy(input_image_torch_CWH)
60
-
61
-
62
- # %% Step A: we have an input image
63
- # torch version uses CWH format
64
- #input_image_torch = read_image(gui_input_image)
65
- #input_image_torch = input_image_torch[:3,:,:]
66
 
67
- # copy WHC format for SAM algorithm
68
- input_image = gui_input_image_WHC #input_image_torch.permute(1,2,0).numpy()
 
 
 
69
 
70
- # %% Step B: we load pre-trained model and classify input image
71
- weights = ResNet50_Weights.DEFAULT
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  preprocess = weights.transforms(antialias=True)
73
- model = resnet50(weights=weights)
74
- model.eval()
75
- # feed the model and get the logits
76
- batch = preprocess(input_image_torch).unsqueeze(0)
77
- # Unit normalize the logits
78
- logits = model(batch)
79
- logits = logits.detach().numpy()
80
- logits_length = np.linalg.norm(logits, ord=1, axis=1)
81
- logits_normalized = logits[0] / logits_length
82
 
83
- #%% Step C: Segmentation
84
- sam = sam_model_registry["vit_b"](checkpoint='sam_vit_b_01ec64.pth')
85
- mask_generator = SamAutomaticMaskGenerator(sam)
86
  masks = mask_generator.generate(input_image)
87
 
88
- # %% show segments on the image
89
- def segmented_image(img, masks, alpha=0.7):
90
- segment_image = img.copy()
91
- for mask in masks:
92
- segment_image[mask['segmentation'] == 1] = 255*np.random.random(3)
93
- cv2.addWeighted(segment_image, alpha, img, 1.0-alpha, 0, segment_image)
94
- return segment_image
95
 
96
- gui_sam = segmented_image(input_image, masks)
97
- #plt.imshow(gui_sam)
 
 
 
 
 
98
 
99
- #%% Step D: Perturbations
100
- N = 200 # number of perturbations
101
- n = len(masks) # number of masks
102
 
103
  x = np.random.rand(N, n)
104
- y = np.zeros(N)
105
 
 
106
  for sample in range(N):
107
- x_input = input_image_torch.clone().type(torch.float64)
108
-
109
  for i, mask in enumerate(masks):
110
  x_seg = mask['segmentation']
111
- x_input[:,x_seg == 1] = x_input[:,x_seg == 1] * np.power(x[sample,i],2)
112
 
113
- x_input = x_input.type(torch.uint8)
114
- batch_2 = preprocess(x_input).unsqueeze(0)
115
  # Unit normalize the logits
116
- logits_2 = model(batch_2)
117
- probs = logits_2.squeeze(0).softmax(0)
118
- logits_2 = logits_2.detach().numpy()
119
- logits_length_2 = np.linalg.norm(logits_2, ord=1, axis=1)
120
- logits_normalized_2 = logits_2[0] / logits_length_2
121
-
122
- # Calculate cosine distance between logits_normalized and logits_normalized_2
123
- # This is the cosine distance between the two models
124
- # The closer the distance is to 1, the more similar the models are
125
- cosine_distance = np.dot(logits_normalized, logits_normalized_2)
126
- eucledean_distance = np.linalg.norm(logits_normalized - logits_normalized_2)
127
- l1_norm = np.sum(np.abs(logits_normalized - logits_normalized_2))
128
-
129
  class_id = probs.argmax().item()
130
  score = probs[class_id].item()
131
  category_name = weights.meta["categories"][class_id]
132
- print(f"sample:{sample:2d} l1norm: {l1_norm:.5f} cosine distance: {cosine_distance:.5f} eucledean distance: {eucledean_distance:.5f} {category_name}: {100 * score:.1f}%")
133
-
134
- # Store output in y
135
- y[sample] = l1_norm
136
-
137
- #fig, axes = plt.subplots(3,1)
138
- #axes[0].imshow(x_input.permute(1,2,0).numpy()/255)
139
- #axes[1].plot(logits_normalized_2)
140
- #axes[2].plot(probs.detach().numpy())
141
-
142
- m = 3
143
- f0 = np.mean(y)
144
- alpha = np.zeros((m, n))
145
-
146
- num_pairs = len(list(combinations(range(n), 2)))
147
- beta = np.zeros((m,num_pairs))
148
-
149
- for r in range(m): # for each input feature
150
- ct = 0
151
- for i in range(n): # for each Legendre polynomial up to order m
152
- alpha[r, i] = np.mean((y-f0) * L(0, 1, r+1, np.array(x[:, i])))
153
- for j in range(i+1,n):
154
- beta[r, ct] = np.mean((y-f0)*
155
- L(0, 1, r+1, np.array(x[:, i]))*
156
- L(0, 1, r+1, np.array(x[:, j])))
157
- ct += 1
158
-
159
- # Calculate Sobol indices
160
- global_D = np.mean(y ** 2) - np.mean(y) ** 2
161
- D_first_order = np.zeros((m,n))
162
- S_first_order = np.zeros((m,n))
163
- D_second_order = np.zeros((m,num_pairs))
164
- S_second_order = np.zeros((m,num_pairs))
165
- for degree in range(m):
166
- for k in range(n):
167
- D_first_order[degree,k] = sum(alpha[r,k] ** 2 for r in range(degree+1))
168
- S_first_order[degree,k] = D_first_order[degree,k]/global_D
169
-
170
-
171
- for deg in range(m):
172
- for pair in range(num_pairs):
173
- D_second_order[deg,pair] = sum(beta[r,pair] ** 2 for r in range(deg+1))
174
- S_second_order[deg,pair] = D_second_order[deg,pair]/global_D
175
-
176
- selection_degree = m
177
- calculated_sobol = np.diag(S_first_order[m-1,:])
178
-
179
- ct = 0
180
- for i in range(n):
181
- for j in range(i+1,n):
182
- calculated_sobol[i, j] = S_second_order[m-1, ct]
183
- ct += 1
184
-
185
- sum_calculated_sobol = np.sum(calculated_sobol)
186
- print("Sum of calculated sobol coefficients: ", sum_calculated_sobol)
187
-
188
- sns.heatmap(calculated_sobol, annot=False,cbar=False)
189
- sns.set(font_scale=2)
190
- plt.savefig('sensitivity.png')
191
-
192
- gui_sensitivity = calculated_sobol
193
-
194
- mask_weights = S_first_order[-1]/np.max(S_first_order[-1])
195
-
196
- # Segment heatmap
197
-
198
- hdmr_map_image, heatmap, = segment_heatmap_image(input_image, masks, mask_weights)
199
-
200
- #plt.imshow(input_image)
201
- #plt.show()
202
- #plt.imshow(hdmr_map_image)
203
- #plt.figure()
204
- #plt.imshow(heatmap)
205
- #
206
- #plt.show()
207
-
208
- gui_hdmr = hdmr_map_image
209
-
210
- gui_sensitivity3d = np.dstack((gui_sensitivity,gui_sensitivity,gui_sensitivity))
211
-
212
- gui_sensitivity3d = (gui_sensitivity3d * 255).astype(np.uint8)
213
-
214
- print('gui_hdmr',type(gui_hdmr),gui_hdmr.shape)
215
- print('gui_sensitivity',type(gui_sensitivity),gui_sensitivity.shape)
216
-
217
- return Image.open('sensitivity.png'), gui_sam, gui_hdmr, heatmap
218
-
219
- with gr.Blocks() as demo:
220
- gui_input_image = gr.Image(label="Yükleyin")
221
- submit_button = gr.Button(label="Yükle", value="Yükle")
222
- damage_score = gr.Textbox(label="Hasar Skoru")
223
- with gr.Row():
224
- gui_sam = gr.Image(label="SAM segments",
225
- shape=(256,256))
226
- gui_hdmr = gr.Image(label="HDMR map",
227
- shape=(256,256))
228
- heatmap = gr.Image(label="heatmap")
229
- gui_sensitivity = gr.Image(label="Sensitivity Scores")
230
- submit_button.click(fn=run, inputs=gui_input_image,
231
- outputs=[gui_sensitivity, gui_sam, gui_hdmr, heatmap])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
  if __name__ == "__main__":
233
  demo.launch()
 
 
1
+ import gradio as gd
 
 
 
 
 
 
 
 
 
 
2
  import numpy as np
3
+ import os
 
4
  import torch
5
+ import torchvision
6
+ import torchvision.models as models
7
+ from lime import lime_image
8
+ import matplotlib.pyplot as plt
9
  import matplotlib
10
+ import torch.nn.functional as F
11
+ from skimage.segmentation import mark_boundaries
12
+ from PIL import Image
13
+ from segment_anything import SamAutomaticMaskGenerator, sam_model_registry
14
  import wget
15
+ import cv2
16
+ matplotlib.use('agg')
17
 
18
  # Vanilla Legendre between [0,1]
19
  def Pn(m, x):
 
23
  return x
24
  else:
25
  return (2*m-1)*x*Pn(m-1, x)/m - (m-1)*Pn(m-2, x)/m
26
+
27
  # Legendre between [a,b]
28
  def L(a,b,m,x):
29
  return np.sqrt((2*m+1)/(b-a))*Pn(m, 2*(x-b)/(b-a)+1)
30
 
31
+ def run_lime(input_image,
32
+ model_name: str,
33
+ top_labels: int,
34
+ num_samples: int,
35
+ num_features: int,
36
+ batch_size: int):
37
+ # input_image is a numpy array of shape (height, width, channels)
38
+ # range is [0, 255]
39
+ print('model_name', model_name)
40
+ print('top_labels', top_labels)
41
+ print('num_samples', num_samples)
42
+ print('num_features', num_features)
43
+ print('batch_size', batch_size)
44
+ print('input image', type(input_image), input_image.shape)
45
+
46
+ model, weights = fetch_model(model_name)
47
+ preprocess = weights.transforms(antialias=True)
48
 
49
+ input_image_processed = preprocess(torch.from_numpy(input_image.transpose(2,0,1))).unsqueeze(0)
50
+ logits = model(input_image_processed)
51
+ probs = F.softmax(logits, dim=1)
52
+ names = weights.meta['categories']
53
+
54
+ top_10_classes = []
55
+ print('probs', type(probs), probs.shape)
56
+ for x in probs.argsort(descending=True)[0][:10]:
57
+ print(x.item(), names[x], probs[0,x].item())
58
+ top_10_classes.append([x.item(), names[x], f'{probs[0,x].item():.4f}'])
59
+
60
+ def classifier_fn(images):
61
+ print('classifier_fn', type(images), images.shape)
62
+
63
+ zz = preprocess(torch.from_numpy(images[0].transpose(2,0,1)))
64
+ c, w, h = zz.shape
65
+ batch = torch.zeros(batch_size, c, w, h)
66
+ print('len(images)', len(images))
67
+ for i in range(batch_size):
68
+ batch[i] = preprocess(torch.from_numpy(images[i].transpose(2,0,1)))
69
+ print('batch', type(batch), batch.shape)
70
+
71
+ logits = model(batch)
72
+ probs = F.softmax(logits, dim=1)
73
+ print('probs', type(probs), probs.shape)
74
+ return probs.detach().cpu().numpy()
75
+
76
+ explainer = lime_image.LimeImageExplainer()
77
+ explanation = explainer.explain_instance(
78
+ input_image,
79
+ classifier_fn,
80
+ top_labels=top_labels,
81
+ hide_color=0,
82
+ num_samples=num_samples,
83
+ num_features=num_features,
84
+ batch_size=batch_size)
85
 
86
+ temp, mask = explanation.get_image_and_mask(
87
+ explanation.top_labels[0],
88
+ positive_only=False, num_features=num_features, hide_rest=False)
89
+ lime_output = mark_boundaries(temp/255.0, mask)
90
+ return lime_output, top_10_classes
91
+
92
+ def segmented_image(img, masks, alpha=0.7):
93
+ segment_image = img.copy()
94
+ for mask in masks:
95
+ segment_image[mask['segmentation'] == 1] = 255*np.random.random(3)
96
+ cv2.addWeighted(segment_image, alpha, img, 1.0-alpha, 0, segment_image)
97
+ return segment_image
98
+
99
+ def segment_heatmap_image(img, masks, mask_weights, num_features_hdmr):
100
+ w, h, c = img.shape
101
+ img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
102
+ # increase brightness of gray image
103
+ img_gray = cv2.convertScaleAbs(img_gray, alpha=10, beta=0)
104
+
105
  img_grad3d = np.dstack([img_gray, img_gray, img_gray])
106
  print(img.shape, img_gray.shape)
107
  segment_image = np.zeros((w,h)).astype(np.uint8)
108
+
109
+ important_segment_indices = mask_weights.argsort()[-num_features_hdmr:]
110
+ for i in important_segment_indices:
111
+ mask = masks[i]
112
+ weight = mask_weights[i]
113
  segment_image[mask['segmentation'] == True] = int(255*weight)
 
114
  heatmap_img = cv2.applyColorMap(segment_image, cv2.COLORMAP_JET)
115
+ super_imposed_img = cv2.addWeighted(heatmap_img, 1, img_grad3d, 0.6, 0)
116
+ return super_imposed_img, heatmap_img
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
+ def sobol(x, y, m):
119
+ print(x.shape, y.shape)
120
+ N, n = x.shape
121
+ f0 = np.mean(y)
122
+ alpha = np.zeros((m, n))
123
 
124
+ for r in range(m):
125
+ for i in range(n):
126
+ alpha[r, i] = np.mean((y-f0) * L(0, 1, r+1, np.array(x[:, i])))
127
+
128
+ global_D = np.mean(y ** 2) - np.mean(y) ** 2
129
+ D_first_order = np.zeros((n,m))
130
+ S_first_order = np.zeros((n,m))
131
+ for degree in range(m):
132
+ for k in range(n):
133
+ D_first_order[k,degree] = sum(alpha[r,k] ** 2 for r in range(degree+1))
134
+ S_first_order[k,degree] = D_first_order[k,degree]/global_D
135
+
136
+ return S_first_order
137
+
138
+ def run_hdmr(input_image,
139
+ model_name: str,
140
+ sam_model_name: str,
141
+ num_samples_hdmr: int,
142
+ num_legendre: int,
143
+ num_features_hdmr: int):
144
+ # input_image is a numpy array of shape (height, width, channels)
145
+ # range is [0, 255]
146
+ print('model_name', model_name)
147
+ print('sam_model_name', sam_model_name)
148
+ print('num_samples_hdmr', num_samples_hdmr)
149
+ print('num_features_hdmr', num_features_hdmr)
150
+ print('input image', type(input_image), input_image.shape)
151
+
152
+ model, weights = fetch_model(model_name)
153
  preprocess = weights.transforms(antialias=True)
 
 
 
 
 
 
 
 
 
154
 
155
+ sam_model = fetch_sam_model(sam_model_name)
156
+ mask_generator = SamAutomaticMaskGenerator(sam_model)
 
157
  masks = mask_generator.generate(input_image)
158
 
159
+ sam_segmented_image = segmented_image(input_image, masks, alpha=0.9)
 
 
 
 
 
 
160
 
161
+ batch = preprocess(torch.from_numpy(input_image.transpose(2,0,1))).unsqueeze(0)
162
+ # Unit normalize the logits
163
+ logits = model(batch)
164
+ logits = logits[0].detach().numpy()
165
+ logits_length = np.linalg.norm(logits)
166
+ logits_normalized = logits / logits_length
167
+ print('logits_normalized',logits_normalized.shape)
168
 
169
+ N = num_samples_hdmr
170
+ n = len(masks)
 
171
 
172
  x = np.random.rand(N, n)
173
+ y = np.zeros((3,N)) # cosine, l1, l2
174
 
175
+ # TODO: implement batch_size
176
  for sample in range(N):
177
+ x_input = input_image.copy()
 
178
  for i, mask in enumerate(masks):
179
  x_seg = mask['segmentation']
180
+ x_input[x_seg == 1] = x_input[x_seg == 1] * np.power(x[sample,i],2)
181
 
182
+ batch = preprocess(torch.from_numpy(x_input.transpose(2,0,1))).unsqueeze(0)
 
183
  # Unit normalize the logits
184
+ logits_sample = model(batch)
185
+ probs = logits_sample.squeeze(0).softmax(0)
186
+ logits_sample = logits_sample[0].detach().numpy()
187
+ logits_sample_length = np.linalg.norm(logits_sample)
188
+ logits_sample_normalized = logits_sample / logits_sample_length
189
+
190
+ cosine_distance = np.dot(logits_normalized, logits_sample_normalized)
191
+ l1_distance = np.sum(np.abs(logits_normalized - logits_sample_normalized))
192
+ l2_distance = np.linalg.norm(logits_normalized - logits_sample_normalized)
 
 
 
 
193
  class_id = probs.argmax().item()
194
  score = probs[class_id].item()
195
  category_name = weights.meta["categories"][class_id]
196
+ print(f"sample:{sample:2d} cosine: {cosine_distance:.5f} l1: {l1_distance:.5f} l2: {l2_distance:.5f} {category_name}: {100 * score:.1f}%")
197
+
198
+ y[:,sample] = [cosine_distance, l1_distance, l2_distance]
199
+
200
+ sobol_indices_cosine = sobol(x, y[0], num_legendre)
201
+ sobol_indices_l1 = sobol(x, y[1], num_legendre)
202
+ sobol_indices_l2 = sobol(x, y[2], num_legendre)
203
+
204
+ hdmr_indices_cosine_df = [[f'{b:.4f}' for b in a] for a in sobol_indices_cosine]
205
+ hdmr_indices_l1_df = [[f'{b:.4f}' for b in a] for a in sobol_indices_l1]
206
+ hdmr_indices_l2_df = [[f'{b:.4f}' for b in a] for a in sobol_indices_l2]
207
+
208
+ weight_cosine = sobol_indices_cosine[:,-1] / np.max(sobol_indices_cosine[:,-1])
209
+ weight_l1 = sobol_indices_l1[:,-1] / np.max(sobol_indices_l1[:,-1])
210
+ weight_l2 = sobol_indices_l2[:,-1] / np.max(sobol_indices_l2[:,-1])
211
+
212
+ print('weight_cosine',weight_cosine.shape)
213
+ _, hdmr_cosine = segment_heatmap_image(input_image, masks, weight_cosine,num_features_hdmr)
214
+ _, hdmr_l1 = segment_heatmap_image(input_image, masks, weight_l1,num_features_hdmr)
215
+ _, hdmr_l2, = segment_heatmap_image(input_image, masks, weight_l2,num_features_hdmr)
216
+
217
+ return hdmr_cosine, hdmr_l1, hdmr_l2, hdmr_indices_cosine_df, hdmr_indices_l1_df, hdmr_indices_l2_df,sam_segmented_image
218
+
219
+ def fetch_sam_model(sam_model_name_checkpoint):
220
+ sam_model_name, sam_checkpoint = sam_model_name_checkpoint.split(' ')
221
+ URL = f"https://dl.fbaipublicfiles.com/segment_anything/{sam_checkpoint}"
222
+ if not os.path.isfile(sam_checkpoint):
223
+ response = wget.download(URL, sam_checkpoint)
224
+ sam = sam_model_registry[sam_model_name](checkpoint=sam_checkpoint)
225
+ return sam
226
+
227
+ def fetch_model_names():
228
+ return models.list_models(module=torchvision.models)
229
+
230
+ def fetch_model(model_name):
231
+ print('Retrieving model ', model_name)
232
+ weights_enum = models.get_model_weights(model_name)
233
+ for w in weights_enum:
234
+ if "IMAGENET1K" in w.name:
235
+ weights = w
236
+ model = models.get_model(model_name, weights=weights)
237
+ print('Model weights loaded', w.name)
238
+ return model, weights
239
+ return None, None
240
+
241
+ with gd.Blocks() as demo:
242
+ with gd.Column():
243
+ gd.Markdown(value='''
244
+ # xAI with a Meta-Modelling Algorithm
245
+ And its comparison with LIME.
246
+ LIME implementation is based on:
247
+ * [LIME](https://github.com/marcotcr/lime)
248
+ * [LIME tutorial](https://github.com/marcotcr/lime/blob/master/tutorials/lime_image.ipynb)
249
+ ''')
250
+ with gd.Row():
251
+ with gd.Column():
252
+ input_image = gd.Image(label="Input Image. Please upload an image that you want LIME to explain")
253
+ model_name = gd.Dropdown(label="Model",
254
+ info='''
255
+ Select the image classification model to use for LIME.
256
+ The list is automatically populated by using torchvision library.
257
+ ''',
258
+ value='convnext_tiny',
259
+ choices=fetch_model_names())
260
+ sam_model_name = gd.Dropdown(label="SAM model",
261
+ info='Select the SAM model',
262
+ value='vit_b sam_vit_b_01ec64.pth',
263
+ choices=['vit_b sam_vit_b_01ec64.pth'])
264
+ with gd.Column():
265
+ top_labels = gd.Number(label='top_labels',info='''
266
+ use the first <top_labels> labels to create explanations.
267
+ For example, setting top_labels=5 will create explanations
268
+ for the top 5 most likely classes.''',
269
+ precision=0, value=5)
270
+ num_samples = gd.Number(label="num_samples",
271
+ info="How many samples to be created to build the linear model inside LIME",
272
+ precision=0, value=100)
273
+ num_features = gd.Number(label="num_features",
274
+ info='Among the most important superpixels (features), how many to be shown in the explanation image',
275
+ precision=0, value=2)
276
+ batch_size = gd.Number(label="batch_size",
277
+ info='how many images in the samples to be processed at once',
278
+ precision=0, value=20)
279
+ with gd.Column():
280
+ num_samples_hdmr = gd.Number(label="num_samples_hdmr",
281
+ info="How many samples in HDMR",
282
+ precision=0, value=10)
283
+ num_legendre = gd.Number(label="num_legendre",
284
+ info='Number of Legendre Bases for HDMR',
285
+ precision=0,value=3)
286
+ num_features_hdmr = gd.Number(label="num_features_hdmr",
287
+ info='Among the most important segments, how many to be shown in the explanation image',
288
+ precision=0, value=2)
289
+ run_button = gd.Button(label="Run")
290
+ with gd.Row():
291
+ top_10_classes = gd.DataFrame(label="Top 10 classes",
292
+ info="Top-10 classes for the input image calculated by using the selected model",
293
+ headers=["class_id","label","probability"],
294
+ datatype=["number","str","number"])
295
+ lime_output = gd.Image(label="Lime Explanation",
296
+ info="The explanation image for the input image calculated by LIME for the selected model")
297
+ sam_segmented_image = gd.Image(label="SAM Segmentation",
298
+ info="The segmentation image for the input image calculated by SAM")
299
+ with gd.Row():
300
+ hdmr_cosine = gd.Image(label="HDMR Explanation via Cosine Distance")
301
+ hdmr_l1 = gd.Image(label="HDMR Explanation via L1 Distance")
302
+ hdmr_l2 = gd.Image(label="HDMR Explanation via L2 Distance")
303
+ with gd.Row():
304
+ hdmr_cosine_indices = gd.DataFrame(label="HDMR Cosine Indices")
305
+ hdmr_l1_indices = gd.DataFrame(label="HDMR L1 Indices")
306
+ hdmr_l2_indices = gd.DataFrame(label="HDMR L2 Indices")
307
+ gd.Examples(
308
+ label="Some examples images and parameters",
309
+ examples=[["jeep.png","convnext_tiny",5,20,2,20],
310
+ ["IMG_0154.jpg","convnext_tiny",5,100,2,20],
311
+ ["IMG_0155.jpg","convnext_tiny",5,100,2,20],
312
+ ["IMG_0156.jpg","convnext_tiny",5,100,2,20],
313
+ ["IMG_0157.jpg","convnext_tiny",5,100,2,20],
314
+ ["IMG_0158.jpg","convnext_tiny",5,100,2,20],
315
+ ["IMG_0159.jpg","convnext_tiny",5,100,2,20],
316
+ ["IMG_0160.jpg","convnext_tiny",5,100,2,20]],
317
+ inputs=[input_image,model_name,top_labels,num_samples,num_features,batch_size])
318
+
319
+ run_button.click(fn=run_lime,inputs=[input_image, model_name, top_labels,num_samples,num_features,batch_size],
320
+ outputs=[lime_output,top_10_classes])
321
+ run_button.click(fn=run_hdmr,inputs=[input_image, model_name, sam_model_name, num_samples_hdmr, num_legendre, num_features_hdmr],
322
+ outputs=[hdmr_cosine, hdmr_l1, hdmr_l2,
323
+ hdmr_cosine_indices, hdmr_l1_indices, hdmr_l2_indices,
324
+ sam_segmented_image])
325
+
326
  if __name__ == "__main__":
327
  demo.launch()
328
+
jeep.png ADDED
requirements.txt CHANGED
@@ -1,7 +1,4 @@
1
  segment-anything==1.0
2
  torchvision==0.15.1
3
  opencv-python==4.7.0.72
4
- fastai==2.7.12
5
- seaborn==0.12.2
6
- opencv-python==4.7.0.72
7
- wget
 
1
  segment-anything==1.0
2
  torchvision==0.15.1
3
  opencv-python==4.7.0.72
4
+ fastai==2.7.12