Spaces:
Sleeping
Sleeping
Commit
·
d850212
1
Parent(s):
3b7d632
update app
Browse files- README.md +10 -10
- app.py +53 -27
- models/custom_resnet.py → custom_resnet.py +0 -0
- models/__init__.py +0 -0
- utils/__init__.py +0 -1
- utils/misc.py +0 -19
README.md
CHANGED
@@ -15,21 +15,21 @@ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-
|
|
15 |
# CIFAR10 demo with GradCAM
|
16 |
## How to Use the App
|
17 |
1. The app has two tabs:
|
18 |
-
- **Examples**: In this tab, you can upload your own 32x32 pixel image or choose an example image provided to classify and visualize the class activation maps using GradCAM. You can adjust the number of top predicted classes, show/hide the GradCAM overlay, select
|
19 |
- **Misclassified Examples**: In this tab, the app displays a gallery of misclassified images from CIFAR10 test dataset. You can control the number of examples shown, show/hide the GradCAM overlay, select a target layer, and control the transparency of the overlay.
|
20 |
|
21 |
2. **Examples Tab**:
|
22 |
-
- **Input Image**: Upload your own 32x32 pixel image or select one of the example images from the
|
23 |
-
- **
|
24 |
-
- **
|
25 |
-
- **
|
26 |
-
- **Transparency**: Control the transparency of the GradCAM overlay. The default value is 0.
|
27 |
|
28 |
3. **Misclassified Examples Tab**:
|
29 |
-
- **No. of
|
30 |
-
- **
|
31 |
-
- **
|
32 |
-
- **Transparency**: Control the transparency of the GradCAM overlay. The default value is 0.
|
33 |
|
34 |
4. After adjusting the settings, click the "Submit" button to see the results.
|
35 |
|
|
|
15 |
# CIFAR10 demo with GradCAM
|
16 |
## How to Use the App
|
17 |
1. The app has two tabs:
|
18 |
+
- **Examples**: In this tab, you can upload your own 32x32 pixel image or choose an example image provided to classify and visualize the class activation maps using GradCAM. You can adjust the number of top predicted classes, show/hide the GradCAM overlay, select multiple target layers, and control the transparency of the overlay.
|
19 |
- **Misclassified Examples**: In this tab, the app displays a gallery of misclassified images from CIFAR10 test dataset. You can control the number of examples shown, show/hide the GradCAM overlay, select a target layer, and control the transparency of the overlay.
|
20 |
|
21 |
2. **Examples Tab**:
|
22 |
+
- **Input Image**: Upload your own 32x32 pixel image or select one of the example images from the given list.
|
23 |
+
- **Top Classes**: Choose the number of top predicted classes to display along with their respective confidence scores.
|
24 |
+
- **Enable GradCAM**: Check this box to display the GradCAM overlay on the input image. Uncheck it to view only the original image.
|
25 |
+
- **Network Layers**: Select the target layers for GradCAM visualization. The default values are -2 and -1.
|
26 |
+
- **Transparency**: Control the transparency of the GradCAM overlay. The default value is 0.5.
|
27 |
|
28 |
3. **Misclassified Examples Tab**:
|
29 |
+
- **No. of Examples**: Control the number of misclassified examples displayed in the gallery. The default value is 20.
|
30 |
+
- **Enable GradCAM**: Check this box to display the GradCAM overlay on the misclassified images. Uncheck it to view only the original images.
|
31 |
+
- **Network Layer**: Adjust the target layer for GradCAM visualization. The default value is -2.
|
32 |
+
- **Transparency**: Control the transparency of the GradCAM overlay. The default value is 0.5.
|
33 |
|
34 |
4. After adjusting the settings, click the "Submit" button to see the results.
|
35 |
|
app.py
CHANGED
@@ -10,8 +10,19 @@ from pytorch_grad_cam import GradCAM
|
|
10 |
from pytorch_grad_cam.utils.image import show_cam_on_image
|
11 |
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
|
12 |
|
13 |
-
from
|
14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
DEVICE = get_device()
|
17 |
|
@@ -42,8 +53,18 @@ transform = transforms.Compose([
|
|
42 |
|
43 |
inv_transform = transforms.Normalize(mean=[-2, -2, -2], std=[4, 4, 4])
|
44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
|
46 |
-
def image_classifier(input_image, top_classes=3, show_cam=True,
|
47 |
input_ = transform(input_image).unsqueeze(0)
|
48 |
|
49 |
output = model(input_)
|
@@ -52,43 +73,47 @@ def image_classifier(input_image, top_classes=3, show_cam=True, target_layer=-2,
|
|
52 |
confidences = [(classes[i], float(output[i])) for i in range(10)]
|
53 |
confidences.sort(key=lambda x: x[1], reverse=True)
|
54 |
confidences = OrderedDict(confidences[:top_classes])
|
55 |
-
|
56 |
label = torch.argmax(output).item()
|
57 |
-
target_layer = [model.network[4 + target_layer]]
|
58 |
-
grad_cam = GradCAM(model=model, target_layers=target_layer, use_cuda=(DEVICE == 'cuda'))
|
59 |
-
targets = [ClassifierOutputTarget(label)]
|
60 |
-
grayscale_cam = grad_cam(input_tensor=input_, targets=targets)
|
61 |
-
grayscale_cam = grayscale_cam[0, :]
|
62 |
-
output_image = show_cam_on_image(input_image / 255, grayscale_cam, use_rgb=True, image_weight=transparency)
|
63 |
|
64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
|
66 |
|
67 |
demo1 = gr.Interface(
|
68 |
fn=image_classifier,
|
69 |
inputs=[
|
70 |
gr.Image(shape=(32, 32), label="Input Image", value='examples/cat.jpg'),
|
71 |
-
gr.Slider(1, 10, value=3, step=1, label="
|
72 |
-
|
73 |
-
gr.
|
74 |
-
gr.
|
|
|
|
|
|
|
75 |
],
|
76 |
-
outputs=[gr.
|
77 |
-
gr.Label(label='Top Classes')],
|
78 |
examples=[[f'examples/{k}.jpg'] for k in classes.values()]
|
79 |
)
|
80 |
|
81 |
|
82 |
-
def show_incorrect(num_examples=20, show_cam=True, target_layer=-
|
83 |
result = list()
|
84 |
for index, row in missed_df.iterrows():
|
85 |
image = np.asarray(Image.open(f'missed_examples/{index}.jpg'))
|
86 |
-
|
87 |
-
|
88 |
truth = row['ground_truths']
|
89 |
-
predicted = list(
|
90 |
if truth != predicted:
|
91 |
-
result.append((
|
92 |
if len(result) >= num_examples:
|
93 |
break
|
94 |
return result
|
@@ -97,12 +122,13 @@ def show_incorrect(num_examples=20, show_cam=True, target_layer=-1, transparency
|
|
97 |
demo2 = gr.Interface(
|
98 |
fn=show_incorrect,
|
99 |
inputs=[
|
100 |
-
gr.Number(value=20, minimum=1, maximum=
|
101 |
-
|
102 |
-
gr.
|
103 |
-
gr.Slider(
|
|
|
104 |
],
|
105 |
-
outputs=[gr.Gallery(label="Missclassified Images (Truth / Predicted)", columns=
|
106 |
)
|
107 |
|
108 |
demo = gr.TabbedInterface([demo1, demo2], ["Examples", "Misclassified Examples"])
|
|
|
10 |
from pytorch_grad_cam.utils.image import show_cam_on_image
|
11 |
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
|
12 |
|
13 |
+
from custom_resnet import Model
|
14 |
+
|
15 |
+
|
16 |
+
def get_device():
|
17 |
+
if torch.cuda.is_available():
|
18 |
+
device = "cuda"
|
19 |
+
elif torch.backends.mps.is_available():
|
20 |
+
device = "mps"
|
21 |
+
else:
|
22 |
+
device = "cpu"
|
23 |
+
print("Device Selected:", device)
|
24 |
+
return device
|
25 |
+
|
26 |
|
27 |
DEVICE = get_device()
|
28 |
|
|
|
53 |
|
54 |
inv_transform = transforms.Normalize(mean=[-2, -2, -2], std=[4, 4, 4])
|
55 |
|
56 |
+
grad_cams = [GradCAM(model=model, target_layers=[model.network[i]], use_cuda=(DEVICE == 'cuda')) for i in range(4)]
|
57 |
+
|
58 |
+
|
59 |
+
def get_gradcam_image(input_tensor, label, target_layer):
|
60 |
+
grad_cam = grad_cams[target_layer]
|
61 |
+
targets = [ClassifierOutputTarget(label)]
|
62 |
+
grayscale_cam = grad_cam(input_tensor=input_tensor, targets=targets)
|
63 |
+
grayscale_cam = grayscale_cam[0, :]
|
64 |
+
return grayscale_cam
|
65 |
+
|
66 |
|
67 |
+
def image_classifier(input_image, top_classes=3, show_cam=True, target_layers=[2, 3], transparency=0.5):
|
68 |
input_ = transform(input_image).unsqueeze(0)
|
69 |
|
70 |
output = model(input_)
|
|
|
73 |
confidences = [(classes[i], float(output[i])) for i in range(10)]
|
74 |
confidences.sort(key=lambda x: x[1], reverse=True)
|
75 |
confidences = OrderedDict(confidences[:top_classes])
|
|
|
76 |
label = torch.argmax(output).item()
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
|
78 |
+
outputs = list()
|
79 |
+
if show_cam:
|
80 |
+
for layer in target_layers:
|
81 |
+
grayscale_cam = get_gradcam_image(input_, label, layer)
|
82 |
+
output_image = show_cam_on_image(input_image / 255, grayscale_cam, use_rgb=True, image_weight=transparency)
|
83 |
+
outputs.append((output_image, f"Layer {layer - 4}"))
|
84 |
+
else:
|
85 |
+
outputs.append((input_image, "Input"))
|
86 |
+
|
87 |
+
return outputs, confidences
|
88 |
|
89 |
|
90 |
demo1 = gr.Interface(
|
91 |
fn=image_classifier,
|
92 |
inputs=[
|
93 |
gr.Image(shape=(32, 32), label="Input Image", value='examples/cat.jpg'),
|
94 |
+
gr.Slider(1, 10, value=3, step=1, label="Top Classes",
|
95 |
+
info="How many top classes do you want to view?"),
|
96 |
+
gr.Checkbox(label="Enable GradCAM", value=True, info="Do you want to see Class Activation Maps?"),
|
97 |
+
gr.CheckboxGroup(["-4", "-3", "-2", "-1"], value=["-2", "-1"], label="Network Layers", type='index',
|
98 |
+
info="Which layer CAMs do you want to visualize?",),
|
99 |
+
gr.Slider(0, 1, value=0.5, label="Transparency", step=0.1,
|
100 |
+
info="Set Transparency of CAMs")
|
101 |
],
|
102 |
+
outputs=[gr.Gallery(label="Output Images", columns=2, rows=2), gr.Label(label='Top Classes')],
|
|
|
103 |
examples=[[f'examples/{k}.jpg'] for k in classes.values()]
|
104 |
)
|
105 |
|
106 |
|
107 |
+
def show_incorrect(num_examples=20, show_cam=True, target_layer=-2, transparency=0.5):
|
108 |
result = list()
|
109 |
for index, row in missed_df.iterrows():
|
110 |
image = np.asarray(Image.open(f'missed_examples/{index}.jpg'))
|
111 |
+
output_images, confidences = image_classifier(image, top_classes=1, show_cam=show_cam,
|
112 |
+
target_layers=[4 + target_layer], transparency=transparency)
|
113 |
truth = row['ground_truths']
|
114 |
+
predicted = list(confidences)[0]
|
115 |
if truth != predicted:
|
116 |
+
result.append((output_images[0][0], f"{row['ground_truths']} / {predicted}"))
|
117 |
if len(result) >= num_examples:
|
118 |
break
|
119 |
return result
|
|
|
122 |
demo2 = gr.Interface(
|
123 |
fn=show_incorrect,
|
124 |
inputs=[
|
125 |
+
gr.Number(value=20, minimum=1, maximum=100, label="No. of Examples", precision=0,
|
126 |
+
info="How many misclassified examples do you want to view? (1 - 100)"),
|
127 |
+
gr.Checkbox(label="Enable GradCAM", value=True, info="Do you want to see Class Activation Maps?"),
|
128 |
+
gr.Slider(-4, -1, value=-2, step=1, label="Network Layer", info="Which layer CAM do you want to visualize?"),
|
129 |
+
gr.Slider(0, 1, value=0.5, label="Transparency", step=0.1, info="Set Transparency of CAMs"),
|
130 |
],
|
131 |
+
outputs=[gr.Gallery(label="Missclassified Images (Truth / Predicted)", columns=5)]
|
132 |
)
|
133 |
|
134 |
demo = gr.TabbedInterface([demo1, demo2], ["Examples", "Misclassified Examples"])
|
models/custom_resnet.py → custom_resnet.py
RENAMED
File without changes
|
models/__init__.py
DELETED
File without changes
|
utils/__init__.py
DELETED
@@ -1 +0,0 @@
|
|
1 |
-
from .misc import *
|
|
|
|
utils/misc.py
DELETED
@@ -1,19 +0,0 @@
|
|
1 |
-
import torch
|
2 |
-
|
3 |
-
SEED = 42
|
4 |
-
DEVICE = None
|
5 |
-
|
6 |
-
|
7 |
-
def get_device():
|
8 |
-
global DEVICE
|
9 |
-
if DEVICE is not None:
|
10 |
-
return DEVICE
|
11 |
-
|
12 |
-
if torch.cuda.is_available():
|
13 |
-
DEVICE = "cuda"
|
14 |
-
elif torch.backends.mps.is_available():
|
15 |
-
DEVICE = "mps"
|
16 |
-
else:
|
17 |
-
DEVICE = "cpu"
|
18 |
-
print("Device Selected:", DEVICE)
|
19 |
-
return DEVICE
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|