BhumikaMak commited on
Commit
4365154
·
1 Parent(s): 140adbe

Update: add sample images selection

Browse files
Files changed (5) hide show
  1. app.py +9 -4
  2. data/xai/sample1.jpeg +0 -0
  3. data/xai/sample2.jpg +0 -0
  4. test.png +0 -0
  5. test.py +0 -58
app.py CHANGED
@@ -20,21 +20,26 @@ def process_image(image, yolo_versions=["yolov5"]):
20
  result_images.append((Image.fromarray(image), f"{yolo_version} not yet implemented."))
21
  return result_images
22
 
23
-
24
  interface = gr.Interface(
25
  fn=process_image,
26
  inputs=[
27
- gr.Image(type="pil", label="Upload an Image"),
28
  gr.CheckboxGroup(
29
  choices=["yolov5", "yolov8s"],
30
  value=["yolov5"], # Set default selection to YOLOv5
31
  label="Select Model(s)",
32
- )
33
  ],
34
  outputs=gr.Gallery(label="Results", elem_id="gallery", rows=2, height=500),
35
  title="Explainable AI for YOLO Models",
36
- description="Upload an image to visualize YOLO object detection with Grad-CAM."
 
 
 
 
 
37
  )
38
 
 
39
  if __name__ == "__main__":
40
  interface.launch()
 
20
  result_images.append((Image.fromarray(image), f"{yolo_version} not yet implemented."))
21
  return result_images
22
 
 
23
  interface = gr.Interface(
24
  fn=process_image,
25
  inputs=[
26
+ gr.Image(type="pil", label="Upload an Image", optional=True),
27
  gr.CheckboxGroup(
28
  choices=["yolov5", "yolov8s"],
29
  value=["yolov5"], # Set default selection to YOLOv5
30
  label="Select Model(s)",
31
+ ),
32
  ],
33
  outputs=gr.Gallery(label="Results", elem_id="gallery", rows=2, height=500),
34
  title="Explainable AI for YOLO Models",
35
+ description="Upload an image or select a sample to visualize YOLO object detection with Grad-CAM.",
36
+ examples=[
37
+ ["/data/xai/sample1.jpeg"],
38
+ ["/data/xai/sample2.jpeg"],
39
+ ],
40
+ live=True
41
  )
42
 
43
+
44
  if __name__ == "__main__":
45
  interface.launch()
data/xai/sample1.jpeg ADDED
data/xai/sample2.jpg ADDED
test.png DELETED
Binary file (35.8 kB)
 
test.py DELETED
@@ -1,58 +0,0 @@
1
- import torch
2
- from transformers import BertTokenizer, BertForMaskedLM
3
- import matplotlib.pyplot as plt
4
- from sklearn.manifold import TSNE
5
- import numpy as np
6
- from mpl_toolkits.mplot3d import Axes3D
7
-
8
- # Load a pre-trained model and tokenizer
9
- model_name = 'bert-base-uncased'
10
- tokenizer = BertTokenizer.from_pretrained(model_name)
11
- model = BertForMaskedLM.from_pretrained(model_name)
12
-
13
- # Example input text
14
- text = "The quick brown fox jumps over the lazy dog"
15
-
16
- # Tokenize the input text
17
- inputs = tokenizer(text, return_tensors="pt")
18
- input_ids = inputs['input_ids']
19
-
20
- # Get attention weights by running the model
21
- with torch.no_grad():
22
- outputs = model(input_ids, output_attentions=True)
23
-
24
- # Extract the attention weights (size: [num_layers, num_heads, seq_len, seq_len])
25
- attention_weights = outputs.attentions
26
-
27
- # Select a specific layer and attention head
28
- layer_idx = 0 # First layer
29
- head_idx = 0 # First attention head
30
-
31
- # Get the attention matrix for this layer and head
32
- attention_matrix = attention_weights[layer_idx][0][head_idx].cpu().numpy()
33
-
34
- # Use t-SNE to reduce the dimensionality of the attention matrix (embedding space)
35
- # Attention matrix shape: [seq_len, seq_len], so we reduce each row (which corresponds to a token's attention distribution)
36
- tsne = TSNE(n_components=3, random_state=42, perplexity=5) # Set a lower perplexity value
37
- reduced_attention = tsne.fit_transform(attention_matrix)
38
-
39
- # Plotting the reduced attention embeddings in 3D
40
- fig = plt.figure(figsize=(12, 10))
41
- ax = fig.add_subplot(111, projection='3d')
42
-
43
- # Plot the reduced attention in 3D
44
- ax.scatter(reduced_attention[:, 0], reduced_attention[:, 1], reduced_attention[:, 2])
45
-
46
- # Annotate the tokens in the scatter plot
47
- tokens = tokenizer.convert_ids_to_tokens(input_ids[0])
48
- for i, token in enumerate(tokens):
49
- ax.text(reduced_attention[i, 0], reduced_attention[i, 1], reduced_attention[i, 2],
50
- token, fontsize=12, ha='center')
51
-
52
- # Set plot labels
53
- ax.set_title(f"3D t-SNE Visualization of Attention - Layer {layer_idx+1}, Head {head_idx+1}")
54
- ax.set_xlabel("t-SNE Dimension 1")
55
- ax.set_ylabel("t-SNE Dimension 2")
56
- ax.set_zlabel("t-SNE Dimension 3")
57
-
58
- plt.show()