Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- Chest_Xray_Report_Generator-V2.py +307 -0
- Mimic_test/config.json +184 -0
- Mimic_test/generation_config.json +5 -0
- Mimic_test/merges.txt +0 -0
- Mimic_test/model.safetensors +3 -0
- Mimic_test/preprocessor_config.json +22 -0
- Mimic_test/special_tokens_map.json +6 -0
- Mimic_test/tokenizer.json +0 -0
- Mimic_test/tokenizer_config.json +20 -0
- Mimic_test/training_args.bin +3 -0
- Mimic_test/vocab.json +0 -0
- README.md +3 -9
- pytorch_grad_cam/Readme.md +29 -0
- pytorch_grad_cam/__init__.py +20 -0
- pytorch_grad_cam/__pycache__/__init__.cpython-39.pyc +0 -0
- pytorch_grad_cam/__pycache__/ablation_cam.cpython-39.pyc +0 -0
- pytorch_grad_cam/__pycache__/ablation_layer.cpython-39.pyc +0 -0
- pytorch_grad_cam/__pycache__/activations_and_gradients.cpython-39.pyc +0 -0
- pytorch_grad_cam/__pycache__/base_cam.cpython-39.pyc +0 -0
- pytorch_grad_cam/__pycache__/eigen_cam.cpython-39.pyc +0 -0
- pytorch_grad_cam/__pycache__/eigen_grad_cam.cpython-39.pyc +0 -0
- pytorch_grad_cam/__pycache__/fullgrad_cam.cpython-39.pyc +0 -0
- pytorch_grad_cam/__pycache__/grad_cam.cpython-39.pyc +0 -0
- pytorch_grad_cam/__pycache__/grad_cam_elementwise.cpython-39.pyc +0 -0
- pytorch_grad_cam/__pycache__/grad_cam_plusplus.cpython-39.pyc +0 -0
- pytorch_grad_cam/__pycache__/guided_backprop.cpython-39.pyc +0 -0
- pytorch_grad_cam/__pycache__/hirescam.cpython-39.pyc +0 -0
- pytorch_grad_cam/__pycache__/layer_cam.cpython-39.pyc +0 -0
- pytorch_grad_cam/__pycache__/random_cam.cpython-39.pyc +0 -0
- pytorch_grad_cam/__pycache__/score_cam.cpython-39.pyc +0 -0
- pytorch_grad_cam/__pycache__/xgrad_cam.cpython-39.pyc +0 -0
- pytorch_grad_cam/ablation_cam.py +148 -0
- pytorch_grad_cam/ablation_cam_multilayer.py +136 -0
- pytorch_grad_cam/ablation_layer.py +155 -0
- pytorch_grad_cam/activations_and_gradients.py +46 -0
- pytorch_grad_cam/base_cam.py +205 -0
- pytorch_grad_cam/cam_mult_image.py +37 -0
- pytorch_grad_cam/eigen_cam.py +23 -0
- pytorch_grad_cam/eigen_grad_cam.py +21 -0
- pytorch_grad_cam/feature_factorization/__init__.py +0 -0
- pytorch_grad_cam/feature_factorization/__pycache__/__init__.cpython-39.pyc +0 -0
- pytorch_grad_cam/feature_factorization/__pycache__/deep_feature_factorization.cpython-39.pyc +0 -0
- pytorch_grad_cam/feature_factorization/deep_feature_factorization.py +131 -0
- pytorch_grad_cam/fullgrad_cam.py +95 -0
- pytorch_grad_cam/grad_cam.py +22 -0
- pytorch_grad_cam/grad_cam_elementwise.py +30 -0
- pytorch_grad_cam/grad_cam_plusplus.py +32 -0
- pytorch_grad_cam/guided_backprop.py +100 -0
- pytorch_grad_cam/hirescam.py +32 -0
- pytorch_grad_cam/layer_cam.py +36 -0
Chest_Xray_Report_Generator-V2.py
ADDED
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import transformers
|
3 |
+
from transformers import pipeline
|
4 |
+
import gradio as gr
|
5 |
+
import cv2
|
6 |
+
import numpy as np
|
7 |
+
import pydicom
|
8 |
+
|
9 |
+
##### Libraries For Grad-Cam-View
|
10 |
+
import os
|
11 |
+
import cv2
|
12 |
+
import numpy as np
|
13 |
+
import torch
|
14 |
+
from functools import partial
|
15 |
+
from torchvision import transforms
|
16 |
+
from pytorch_grad_cam import GradCAM, ScoreCAM, GradCAMPlusPlus, AblationCAM, XGradCAM, EigenCAM, EigenGradCAM, LayerCAM, FullGrad
|
17 |
+
from pytorch_grad_cam.utils.image import show_cam_on_image, preprocess_image
|
18 |
+
from pytorch_grad_cam.ablation_layer import AblationLayerVit
|
19 |
+
from transformers import VisionEncoderDecoderModel
|
20 |
+
|
21 |
+
def generate_gradcam(image_path, model_path, output_path, method='gradcam', use_cuda=True, aug_smooth=False, eigen_smooth=False):
|
22 |
+
methods = {
|
23 |
+
"gradcam": GradCAM,
|
24 |
+
"scorecam": ScoreCAM,
|
25 |
+
"gradcam++": GradCAMPlusPlus,
|
26 |
+
"ablationcam": AblationCAM,
|
27 |
+
"xgradcam": XGradCAM,
|
28 |
+
"eigencam": EigenCAM,
|
29 |
+
"eigengradcam": EigenGradCAM,
|
30 |
+
"layercam": LayerCAM,
|
31 |
+
"fullgrad": FullGrad
|
32 |
+
}
|
33 |
+
|
34 |
+
if method not in methods:
|
35 |
+
raise ValueError(f"Method should be one of {list(methods.keys())}")
|
36 |
+
|
37 |
+
model = VisionEncoderDecoderModel.from_pretrained(model_path)
|
38 |
+
model.encoder.eval()
|
39 |
+
|
40 |
+
if use_cuda and torch.cuda.is_available():
|
41 |
+
model.encoder = model.encoder.cuda()
|
42 |
+
else:
|
43 |
+
use_cuda = False
|
44 |
+
|
45 |
+
#target_layers = [model.blocks[-1].norm1] ## For ViT model
|
46 |
+
#target_layers = model.blocks[-1].norm1 ## For EfficientNet-B7 model
|
47 |
+
target_layers = [model.encoder.encoder.layer[-1].layernorm_before] ## For ViT-based VisionEncoderDecoder model
|
48 |
+
#target_layers = [model.encoder.encoder.layers[-1].blocks[-1].layernorm_before, model.encoder.encoder.layers[-1].blocks[0].layernorm_before] ## For Swin-based VisionEncoderDecoder mode
|
49 |
+
|
50 |
+
|
51 |
+
if method == "ablationcam":
|
52 |
+
cam = methods[method](model=model.encoder,
|
53 |
+
target_layers=target_layers,
|
54 |
+
use_cuda=use_cuda,
|
55 |
+
reshape_transform=reshape_transform,
|
56 |
+
ablation_layer=AblationLayerVit())
|
57 |
+
else:
|
58 |
+
cam = methods[method](model=model.encoder,
|
59 |
+
target_layers=target_layers,
|
60 |
+
use_cuda=use_cuda,
|
61 |
+
reshape_transform=reshape_transform)
|
62 |
+
|
63 |
+
rgb_img = cv2.imread(image_path, 1)[:, :, ::-1]
|
64 |
+
rgb_img = cv2.resize(rgb_img, (224, 224)) ## (224, 224)
|
65 |
+
rgb_img = np.float32(rgb_img) / 255
|
66 |
+
input_tensor = preprocess_image(rgb_img, mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
|
67 |
+
|
68 |
+
targets = None
|
69 |
+
cam.batch_size = 16
|
70 |
+
|
71 |
+
grayscale_cam = cam(input_tensor=input_tensor, targets=targets, eigen_smooth=eigen_smooth, aug_smooth=aug_smooth)
|
72 |
+
grayscale_cam = grayscale_cam[0, :]
|
73 |
+
|
74 |
+
cam_image = show_cam_on_image(rgb_img, grayscale_cam)
|
75 |
+
output_file = os.path.join(output_path, 'gradcam_result.png')
|
76 |
+
cv2.imwrite(output_file, cam_image)
|
77 |
+
|
78 |
+
|
79 |
+
def reshape_transform(tensor, height=14, width=14): ### height=14, width=14 for ViT-based Model
|
80 |
+
batch_size, token_number, embed_dim = tensor.size()
|
81 |
+
if token_number < height * width:
|
82 |
+
pad = torch.zeros(batch_size, height * width - token_number, embed_dim, device=tensor.device)
|
83 |
+
tensor = torch.cat([tensor, pad], dim=1)
|
84 |
+
elif token_number > height * width:
|
85 |
+
tensor = tensor[:, :height * width, :]
|
86 |
+
|
87 |
+
result = tensor.reshape(batch_size, height, width, embed_dim)
|
88 |
+
result = result.transpose(2, 3).transpose(1, 2)
|
89 |
+
return result
|
90 |
+
|
91 |
+
|
92 |
+
|
93 |
+
|
94 |
+
# Example usage:
|
95 |
+
#image_path = "/home/chayan/CGI_Net/images/images/CXR1353_IM-0230-1001.png"
|
96 |
+
model_path = "/home/chayan/ViT-GPT2/Mimic_test/"
|
97 |
+
output_path = "/home/chayan/ViT-GPT2/CAM-Result/"
|
98 |
+
|
99 |
+
|
100 |
+
|
101 |
+
def sentence_case(paragraph):
|
102 |
+
sentences = paragraph.split('. ')
|
103 |
+
formatted_sentences = [sentence.capitalize() for sentence in sentences if sentence]
|
104 |
+
formatted_paragraph = '. '.join(formatted_sentences)
|
105 |
+
return formatted_paragraph
|
106 |
+
|
107 |
+
def dicom_to_png(dicom_file, png_file):
|
108 |
+
# Load DICOM file
|
109 |
+
dicom_data = pydicom.dcmread(dicom_file)
|
110 |
+
dicom_data.PhotometricInterpretation = 'MONOCHROME1'
|
111 |
+
|
112 |
+
# Normalize pixel values to 0-255
|
113 |
+
img = dicom_data.pixel_array
|
114 |
+
img = img.astype(np.float32)
|
115 |
+
|
116 |
+
img = cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX)
|
117 |
+
img = img.astype(np.uint8)
|
118 |
+
|
119 |
+
# Save as PNG
|
120 |
+
cv2.imwrite(png_file, img)
|
121 |
+
return img
|
122 |
+
|
123 |
+
|
124 |
+
Image_Captioner = pipeline("image-to-text", model = "/home/chayan/ViT-GPT2/Mimic_test/")
|
125 |
+
|
126 |
+
data_dir = '/home/chayan/ViT-GPT2/'
|
127 |
+
|
128 |
+
def xray_report_generator(Image_file):
|
129 |
+
if Image_file[-4:] =='.dcm':
|
130 |
+
png_file = 'DCM2PNG.png'
|
131 |
+
dicom_to_png(Image_file, png_file)
|
132 |
+
Image_file = os.path.join(data_dir, png_file)
|
133 |
+
output = Image_Captioner(Image_file, max_new_tokens=512)
|
134 |
+
|
135 |
+
else:
|
136 |
+
output = Image_Captioner(Image_file, max_new_tokens=512)
|
137 |
+
|
138 |
+
result = output[0]['generated_text']
|
139 |
+
output_paragraph = sentence_case(result)
|
140 |
+
|
141 |
+
generate_gradcam(Image_file, model_path, output_path, method='gradcam', use_cuda=True)
|
142 |
+
|
143 |
+
grad_cam_image = output_path + 'gradcam_result.png'
|
144 |
+
|
145 |
+
return Image_file,grad_cam_image, output_paragraph
|
146 |
+
|
147 |
+
|
148 |
+
|
149 |
+
def save_feedback(feedback):
|
150 |
+
feedback_dir = "/home/chayan/ViT-GPT2/Feedback/" # Update this to your desired directory
|
151 |
+
if not os.path.exists(feedback_dir):
|
152 |
+
os.makedirs(feedback_dir)
|
153 |
+
feedback_file = os.path.join(feedback_dir, "feedback.txt")
|
154 |
+
with open(feedback_file, "a") as f:
|
155 |
+
f.write(feedback + "\n")
|
156 |
+
return "Feedback submitted successfully!"
|
157 |
+
|
158 |
+
|
159 |
+
|
160 |
+
|
161 |
+
# Custom CSS styles
|
162 |
+
custom_css = """
|
163 |
+
<style>
|
164 |
+
|
165 |
+
#title {
|
166 |
+
color: green;
|
167 |
+
font-size: 36px;
|
168 |
+
font-weight: bold;
|
169 |
+
}
|
170 |
+
#description {
|
171 |
+
color: green;
|
172 |
+
font-size: 22px;
|
173 |
+
}
|
174 |
+
|
175 |
+
|
176 |
+
#submit-btn {
|
177 |
+
background-color: #1E90FF; /* DodgerBlue */
|
178 |
+
color: green;
|
179 |
+
padding: 15px 32px;
|
180 |
+
text-align: center;
|
181 |
+
text-decoration: none;
|
182 |
+
display: inline-block;
|
183 |
+
font-size: 20px;
|
184 |
+
margin: 4px 2px;
|
185 |
+
cursor: pointer;
|
186 |
+
}
|
187 |
+
#submit-btn:hover {
|
188 |
+
background-color: #00FFFF;
|
189 |
+
}
|
190 |
+
|
191 |
+
.intext textarea {
|
192 |
+
color: green;
|
193 |
+
font-size: 20px;
|
194 |
+
font-weight: bold;
|
195 |
+
}
|
196 |
+
|
197 |
+
|
198 |
+
.small-button {
|
199 |
+
color: green;
|
200 |
+
padding: 5px 10px;
|
201 |
+
font-size: 20px;
|
202 |
+
}
|
203 |
+
|
204 |
+
</style>
|
205 |
+
"""
|
206 |
+
|
207 |
+
# Sample image paths
|
208 |
+
sample_images = [
|
209 |
+
"/mnt/data/chayan/MIMIC-CXR-JPG/2.0.0/files/p19565388/s54621108/a9510716-02da91b0-61532c26-a65b2efc-c9dfa6f1.jpg",
|
210 |
+
"/mnt/data/chayan/MIMIC-CXR-JPG/2.0.0/files/p19454978/s52312858/93681764-ec39480e-0518b12c-199850c2-f15118ab.jpg",
|
211 |
+
"/mnt/data/chayan/MIMIC-CXR-JPG/2.0.0/files/p17340686/s55469953/6ff741e9-6ea01eef-1bf10153-d1b6beba-590b6620.jpg"
|
212 |
+
#"sample4.png",
|
213 |
+
#"sample5.png"
|
214 |
+
]
|
215 |
+
|
216 |
+
def set_input_image(image_path):
|
217 |
+
return gr.update(value=image_path)
|
218 |
+
|
219 |
+
|
220 |
+
with gr.Blocks(css = custom_css) as demo:
|
221 |
+
|
222 |
+
#gr.HTML(custom_css) # Inject custom CSS
|
223 |
+
|
224 |
+
gr.Markdown(
|
225 |
+
"""
|
226 |
+
<h1 style="color:blue; font-size: 36px; font-weight: bold">Chest X-ray Report Generator</h1>
|
227 |
+
<p id="description">Upload an X-ray image and get its report with heat-map visualization.</p>
|
228 |
+
"""
|
229 |
+
)
|
230 |
+
|
231 |
+
with gr.Row():
|
232 |
+
inputs = gr.File(label="Upload Chest X-ray Image File", type="filepath")
|
233 |
+
|
234 |
+
with gr.Row():
|
235 |
+
with gr.Column(scale=1, min_width=300):
|
236 |
+
outputs1 = gr.Image(label="Image Viewer")
|
237 |
+
with gr.Column(scale=1, min_width=300):
|
238 |
+
outputs2 = gr.Image(label="Grad_CAM-Visualization")
|
239 |
+
with gr.Column(scale=1, min_width=300):
|
240 |
+
outputs3 = gr.Textbox(label="Generated Report", elem_classes = "intext")
|
241 |
+
|
242 |
+
|
243 |
+
submit_btn = gr.Button("Generate Report", elem_id="submit-btn")
|
244 |
+
submit_btn.click(
|
245 |
+
fn=xray_report_generator,
|
246 |
+
inputs=inputs,
|
247 |
+
outputs=[outputs1, outputs2, outputs3])
|
248 |
+
|
249 |
+
|
250 |
+
gr.Markdown(
|
251 |
+
"""
|
252 |
+
<h2 style="color:green; font-size: 24px;">Or choose a sample image:</h2>
|
253 |
+
"""
|
254 |
+
)
|
255 |
+
|
256 |
+
with gr.Row():
|
257 |
+
for idx, sample_image in enumerate(sample_images):
|
258 |
+
with gr.Column(scale=1):
|
259 |
+
#sample_image_component = gr.Image(value=sample_image, interactive=False)
|
260 |
+
select_button = gr.Button(f"Select Sample Image {idx+1}")
|
261 |
+
select_button.click(
|
262 |
+
fn=set_input_image,
|
263 |
+
inputs=gr.State(value=sample_image),
|
264 |
+
outputs=inputs
|
265 |
+
)
|
266 |
+
|
267 |
+
|
268 |
+
|
269 |
+
# Feedback section
|
270 |
+
gr.Markdown(
|
271 |
+
"""
|
272 |
+
<h2 style="color:green; font-size: 24px;">Provide Your Valuable Feedback:</h2>
|
273 |
+
"""
|
274 |
+
)
|
275 |
+
|
276 |
+
with gr.Row():
|
277 |
+
feedback_input = gr.Textbox(label="Your Feedback", lines=4, placeholder="Enter your feedback here...")
|
278 |
+
feedback_submit_btn = gr.Button("Submit Feedback", elem_classes="small-button")
|
279 |
+
feedback_output = gr.Textbox(label="Feedback Status", interactive=False)
|
280 |
+
|
281 |
+
feedback_submit_btn.click(
|
282 |
+
fn=save_feedback,
|
283 |
+
inputs=feedback_input,
|
284 |
+
outputs=feedback_output
|
285 |
+
)
|
286 |
+
|
287 |
+
|
288 |
+
|
289 |
+
demo.launch(share=True)
|
290 |
+
|
291 |
+
|
292 |
+
# inputs = gr.File(label="Upload Chest X-ray Image File", type="filepath")
|
293 |
+
# outputs1 =gr.Image(label="Image Viewer")
|
294 |
+
# outputs2 =gr.Image(label="Grad_CAM-Visualization")
|
295 |
+
# outputs3 = gr.Textbox(label="Generated Report")
|
296 |
+
|
297 |
+
|
298 |
+
# interface = gr.Interface(
|
299 |
+
# fn=xray_report_generator,
|
300 |
+
# inputs=inputs,
|
301 |
+
# outputs=[outputs1, outputs2, outputs3],
|
302 |
+
# title="Chest X-ray Report Generator",
|
303 |
+
# description="Upload an X-ray image and get its report.",
|
304 |
+
# )
|
305 |
+
|
306 |
+
|
307 |
+
# interface.launch(share=True)
|
Mimic_test/config.json
ADDED
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"VisionEncoderDecoderModel"
|
4 |
+
],
|
5 |
+
"decoder": {
|
6 |
+
"_name_or_path": "gpt2",
|
7 |
+
"activation_function": "gelu_new",
|
8 |
+
"add_cross_attention": true,
|
9 |
+
"architectures": [
|
10 |
+
"GPT2LMHeadModel"
|
11 |
+
],
|
12 |
+
"attn_pdrop": 0.1,
|
13 |
+
"bad_words_ids": null,
|
14 |
+
"begin_suppress_tokens": null,
|
15 |
+
"bos_token_id": 50256,
|
16 |
+
"chunk_size_feed_forward": 0,
|
17 |
+
"cross_attention_hidden_size": null,
|
18 |
+
"decoder_start_token_id": null,
|
19 |
+
"diversity_penalty": 0.0,
|
20 |
+
"do_sample": false,
|
21 |
+
"early_stopping": false,
|
22 |
+
"embd_pdrop": 0.1,
|
23 |
+
"encoder_no_repeat_ngram_size": 0,
|
24 |
+
"eos_token_id": 50256,
|
25 |
+
"exponential_decay_length_penalty": null,
|
26 |
+
"finetuning_task": null,
|
27 |
+
"forced_bos_token_id": null,
|
28 |
+
"forced_eos_token_id": null,
|
29 |
+
"id2label": {
|
30 |
+
"0": "LABEL_0",
|
31 |
+
"1": "LABEL_1"
|
32 |
+
},
|
33 |
+
"initializer_range": 0.02,
|
34 |
+
"is_decoder": true,
|
35 |
+
"is_encoder_decoder": false,
|
36 |
+
"label2id": {
|
37 |
+
"LABEL_0": 0,
|
38 |
+
"LABEL_1": 1
|
39 |
+
},
|
40 |
+
"layer_norm_epsilon": 1e-05,
|
41 |
+
"length_penalty": 1.0,
|
42 |
+
"max_length": 20,
|
43 |
+
"min_length": 0,
|
44 |
+
"model_type": "gpt2",
|
45 |
+
"n_ctx": 1024,
|
46 |
+
"n_embd": 768,
|
47 |
+
"n_head": 12,
|
48 |
+
"n_inner": null,
|
49 |
+
"n_layer": 12,
|
50 |
+
"n_positions": 1024,
|
51 |
+
"no_repeat_ngram_size": 0,
|
52 |
+
"num_beam_groups": 1,
|
53 |
+
"num_beams": 1,
|
54 |
+
"num_return_sequences": 1,
|
55 |
+
"output_attentions": false,
|
56 |
+
"output_hidden_states": false,
|
57 |
+
"output_scores": false,
|
58 |
+
"pad_token_id": null,
|
59 |
+
"prefix": null,
|
60 |
+
"problem_type": null,
|
61 |
+
"pruned_heads": {},
|
62 |
+
"remove_invalid_values": false,
|
63 |
+
"reorder_and_upcast_attn": false,
|
64 |
+
"repetition_penalty": 1.0,
|
65 |
+
"resid_pdrop": 0.1,
|
66 |
+
"return_dict": true,
|
67 |
+
"return_dict_in_generate": false,
|
68 |
+
"scale_attn_by_inverse_layer_idx": false,
|
69 |
+
"scale_attn_weights": true,
|
70 |
+
"sep_token_id": null,
|
71 |
+
"summary_activation": null,
|
72 |
+
"summary_first_dropout": 0.1,
|
73 |
+
"summary_proj_to_labels": true,
|
74 |
+
"summary_type": "cls_index",
|
75 |
+
"summary_use_proj": true,
|
76 |
+
"suppress_tokens": null,
|
77 |
+
"task_specific_params": {
|
78 |
+
"text-generation": {
|
79 |
+
"do_sample": true,
|
80 |
+
"max_length": 50
|
81 |
+
}
|
82 |
+
},
|
83 |
+
"temperature": 1.0,
|
84 |
+
"tf_legacy_loss": false,
|
85 |
+
"tie_encoder_decoder": false,
|
86 |
+
"tie_word_embeddings": true,
|
87 |
+
"tokenizer_class": null,
|
88 |
+
"top_k": 50,
|
89 |
+
"top_p": 1.0,
|
90 |
+
"torch_dtype": null,
|
91 |
+
"torchscript": false,
|
92 |
+
"typical_p": 1.0,
|
93 |
+
"use_bfloat16": false,
|
94 |
+
"use_cache": true,
|
95 |
+
"vocab_size": 50257
|
96 |
+
},
|
97 |
+
"decoder_start_token_id": 50256,
|
98 |
+
"encoder": {
|
99 |
+
"_name_or_path": "google/vit-base-patch16-224-in21k",
|
100 |
+
"add_cross_attention": false,
|
101 |
+
"architectures": [
|
102 |
+
"ViTModel"
|
103 |
+
],
|
104 |
+
"attention_probs_dropout_prob": 0.0,
|
105 |
+
"bad_words_ids": null,
|
106 |
+
"begin_suppress_tokens": null,
|
107 |
+
"bos_token_id": null,
|
108 |
+
"chunk_size_feed_forward": 0,
|
109 |
+
"cross_attention_hidden_size": null,
|
110 |
+
"decoder_start_token_id": null,
|
111 |
+
"diversity_penalty": 0.0,
|
112 |
+
"do_sample": false,
|
113 |
+
"early_stopping": false,
|
114 |
+
"encoder_no_repeat_ngram_size": 0,
|
115 |
+
"encoder_stride": 16,
|
116 |
+
"eos_token_id": null,
|
117 |
+
"exponential_decay_length_penalty": null,
|
118 |
+
"finetuning_task": null,
|
119 |
+
"forced_bos_token_id": null,
|
120 |
+
"forced_eos_token_id": null,
|
121 |
+
"hidden_act": "gelu",
|
122 |
+
"hidden_dropout_prob": 0.0,
|
123 |
+
"hidden_size": 768,
|
124 |
+
"id2label": {
|
125 |
+
"0": "LABEL_0",
|
126 |
+
"1": "LABEL_1"
|
127 |
+
},
|
128 |
+
"image_size": 224,
|
129 |
+
"initializer_range": 0.02,
|
130 |
+
"intermediate_size": 3072,
|
131 |
+
"is_decoder": false,
|
132 |
+
"is_encoder_decoder": false,
|
133 |
+
"label2id": {
|
134 |
+
"LABEL_0": 0,
|
135 |
+
"LABEL_1": 1
|
136 |
+
},
|
137 |
+
"layer_norm_eps": 1e-12,
|
138 |
+
"length_penalty": 1.0,
|
139 |
+
"max_length": 20,
|
140 |
+
"min_length": 0,
|
141 |
+
"model_type": "vit",
|
142 |
+
"no_repeat_ngram_size": 0,
|
143 |
+
"num_attention_heads": 12,
|
144 |
+
"num_beam_groups": 1,
|
145 |
+
"num_beams": 1,
|
146 |
+
"num_channels": 3,
|
147 |
+
"num_hidden_layers": 12,
|
148 |
+
"num_return_sequences": 1,
|
149 |
+
"output_attentions": false,
|
150 |
+
"output_hidden_states": false,
|
151 |
+
"output_scores": false,
|
152 |
+
"pad_token_id": null,
|
153 |
+
"patch_size": 16,
|
154 |
+
"prefix": null,
|
155 |
+
"problem_type": null,
|
156 |
+
"pruned_heads": {},
|
157 |
+
"qkv_bias": true,
|
158 |
+
"remove_invalid_values": false,
|
159 |
+
"repetition_penalty": 1.0,
|
160 |
+
"return_dict": true,
|
161 |
+
"return_dict_in_generate": false,
|
162 |
+
"sep_token_id": null,
|
163 |
+
"suppress_tokens": null,
|
164 |
+
"task_specific_params": null,
|
165 |
+
"temperature": 1.0,
|
166 |
+
"tf_legacy_loss": false,
|
167 |
+
"tie_encoder_decoder": false,
|
168 |
+
"tie_word_embeddings": true,
|
169 |
+
"tokenizer_class": null,
|
170 |
+
"top_k": 50,
|
171 |
+
"top_p": 1.0,
|
172 |
+
"torch_dtype": null,
|
173 |
+
"torchscript": false,
|
174 |
+
"typical_p": 1.0,
|
175 |
+
"use_bfloat16": false
|
176 |
+
},
|
177 |
+
"eos_token_id": 50256,
|
178 |
+
"is_encoder_decoder": true,
|
179 |
+
"model_type": "vision-encoder-decoder",
|
180 |
+
"pad_token_id": 50256,
|
181 |
+
"tie_word_embeddings": false,
|
182 |
+
"torch_dtype": "float32",
|
183 |
+
"transformers_version": "4.37.1"
|
184 |
+
}
|
Mimic_test/generation_config.json
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token_id": 50256,
|
3 |
+
"eos_token_id": 50256,
|
4 |
+
"transformers_version": "4.37.1"
|
5 |
+
}
|
Mimic_test/merges.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
Mimic_test/model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:eae9007ca4a208a6a3d523ec5f24ac54b6ae165263243c957a3afe18021483af
|
3 |
+
size 956835520
|
Mimic_test/preprocessor_config.json
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"do_normalize": true,
|
3 |
+
"do_rescale": true,
|
4 |
+
"do_resize": true,
|
5 |
+
"image_mean": [
|
6 |
+
0.5,
|
7 |
+
0.5,
|
8 |
+
0.5
|
9 |
+
],
|
10 |
+
"feature_extractor_type": "ViTFeatureExtractor",
|
11 |
+
"image_std": [
|
12 |
+
0.5,
|
13 |
+
0.5,
|
14 |
+
0.5
|
15 |
+
],
|
16 |
+
"resample": 2,
|
17 |
+
"rescale_factor": 0.00392156862745098,
|
18 |
+
"size": {
|
19 |
+
"height": 224,
|
20 |
+
"width": 224
|
21 |
+
}
|
22 |
+
}
|
Mimic_test/special_tokens_map.json
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": "<|endoftext|>",
|
3 |
+
"eos_token": "<|endoftext|>",
|
4 |
+
"pad_token": "<|endoftext|>",
|
5 |
+
"unk_token": "<|endoftext|>"
|
6 |
+
}
|
Mimic_test/tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
Mimic_test/tokenizer_config.json
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_prefix_space": false,
|
3 |
+
"added_tokens_decoder": {
|
4 |
+
"50256": {
|
5 |
+
"content": "<|endoftext|>",
|
6 |
+
"lstrip": false,
|
7 |
+
"normalized": true,
|
8 |
+
"rstrip": false,
|
9 |
+
"single_word": false,
|
10 |
+
"special": true
|
11 |
+
}
|
12 |
+
},
|
13 |
+
"bos_token": "<|endoftext|>",
|
14 |
+
"clean_up_tokenization_spaces": true,
|
15 |
+
"eos_token": "<|endoftext|>",
|
16 |
+
"model_max_length": 1024,
|
17 |
+
"pad_token": "<|endoftext|>",
|
18 |
+
"tokenizer_class": "GPT2Tokenizer",
|
19 |
+
"unk_token": "<|endoftext|>"
|
20 |
+
}
|
Mimic_test/training_args.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ed01b457b864b39f97e7f2f322bba0c3d52815e5520732e5dab1ea9e98840a8b
|
3 |
+
size 4411
|
Mimic_test/vocab.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
README.md
CHANGED
@@ -1,12 +1,6 @@
|
|
1 |
---
|
2 |
-
title:
|
3 |
-
|
4 |
-
colorFrom: red
|
5 |
-
colorTo: purple
|
6 |
sdk: gradio
|
7 |
-
sdk_version: 4.
|
8 |
-
app_file: app.py
|
9 |
-
pinned: false
|
10 |
---
|
11 |
-
|
12 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
1 |
---
|
2 |
+
title: Automatic_Chest_X-ray_Report_Generation_System
|
3 |
+
app_file: Chest_Xray_Report_Generator-V2.py
|
|
|
|
|
4 |
sdk: gradio
|
5 |
+
sdk_version: 4.32.2
|
|
|
|
|
6 |
---
|
|
|
|
pytorch_grad_cam/Readme.md
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#### Grad-CAM visualization of any VisionEncoderDecoder model
|
2 |
+
|
3 |
+
# Step 1: Open /pytorch_grad_cam folder and make sure that in init.py all the CAM version is imported as the class name not the python file. For example
|
4 |
+
from pytorch_grad_cam.grad_cam import GradCAM
|
5 |
+
because when in the main python code (Grad_CAM_Visualization.py) we want to import every Class directly.
|
6 |
+
|
7 |
+
# Step2: Open the main Grad-CAM code: Grad_CAM_Visualization.py and edit the following function according to your model.
|
8 |
+
# "def reshape_transform(tensor, height=14, width=14):
|
9 |
+
result = tensor[:, 1:, :].reshape(tensor.size(0),
|
10 |
+
height, width, tensor.size(2))
|
11 |
+
result = result.transpose(2, 3).transpose(1, 2)
|
12 |
+
# return result"
|
13 |
+
here as the resized image tensor was [150,528] which should be equivalent to the reshaped transform of [1,14,14,768]
|
14 |
+
## The error message should be like this if any mismatch:
|
15 |
+
RuntimeError: shape '[1, 16, 16, 768]' is invalid for input of size 150528
|
16 |
+
|
17 |
+
# Step 3: Choose your desired model from (DeIT_Base16_Pretrained with ImageNeT, Customized VisionTransformer, Dino_Base16_Pretrained with ImageNeT, My customized DeiT-CXR model, My customized EfficientNet model, and ##VisionEncoderDecoder Model)
|
18 |
+
|
19 |
+
# Step 4: Open base_cam.py file and go to the "forward" function of Class BaseCAM.
|
20 |
+
Write extra line "outputs = outputs.pooler_output" for ##VisionEncoderDecoder Model as we need to take the tensor of pooler_output of the model configuration. Follow the comment line as well.
|
21 |
+
|
22 |
+
# Step 5: Then follow the comments in the Grad_CAM_Visualization.py:
|
23 |
+
use model.encoder instead of model for ## VisionEncoderDecoder Model
|
24 |
+
use different target_layers for different model
|
25 |
+
target_layers = [model.encoder.encoder.layer[-1].layernorm_before] for ## VisionEncoderDecoder Model
|
26 |
+
|
27 |
+
# Step 6: Change the image_path and output_path accordingly
|
28 |
+
|
29 |
+
# Step 7: Run python Grad_CAM_Visualization.py --use-cuda --image-path "directory/image_path" --method "any grad-cam method defined in the code"
|
pytorch_grad_cam/__init__.py
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pytorch_grad_cam.grad_cam import GradCAM
|
2 |
+
from pytorch_grad_cam.hirescam import HiResCAM
|
3 |
+
from pytorch_grad_cam.grad_cam_elementwise import GradCAMElementWise
|
4 |
+
from pytorch_grad_cam.ablation_layer import AblationLayer, AblationLayerVit, AblationLayerFasterRCNN
|
5 |
+
from pytorch_grad_cam.ablation_cam import AblationCAM
|
6 |
+
from pytorch_grad_cam.xgrad_cam import XGradCAM
|
7 |
+
from pytorch_grad_cam.grad_cam_plusplus import GradCAMPlusPlus
|
8 |
+
from pytorch_grad_cam.score_cam import ScoreCAM
|
9 |
+
from pytorch_grad_cam.layer_cam import LayerCAM
|
10 |
+
from pytorch_grad_cam.eigen_cam import EigenCAM
|
11 |
+
from pytorch_grad_cam.eigen_grad_cam import EigenGradCAM
|
12 |
+
from pytorch_grad_cam.random_cam import RandomCAM
|
13 |
+
from pytorch_grad_cam.fullgrad_cam import FullGrad
|
14 |
+
from pytorch_grad_cam.guided_backprop import GuidedBackpropReLUModel
|
15 |
+
from pytorch_grad_cam.activations_and_gradients import ActivationsAndGradients
|
16 |
+
from pytorch_grad_cam.feature_factorization.deep_feature_factorization import DeepFeatureFactorization, run_dff_on_image
|
17 |
+
import pytorch_grad_cam.utils.model_targets
|
18 |
+
import pytorch_grad_cam.utils.reshape_transforms
|
19 |
+
import pytorch_grad_cam.metrics.cam_mult_image
|
20 |
+
import pytorch_grad_cam.metrics.road
|
pytorch_grad_cam/__pycache__/__init__.cpython-39.pyc
ADDED
Binary file (1.55 kB). View file
|
|
pytorch_grad_cam/__pycache__/ablation_cam.cpython-39.pyc
ADDED
Binary file (3.68 kB). View file
|
|
pytorch_grad_cam/__pycache__/ablation_layer.cpython-39.pyc
ADDED
Binary file (5.23 kB). View file
|
|
pytorch_grad_cam/__pycache__/activations_and_gradients.cpython-39.pyc
ADDED
Binary file (1.89 kB). View file
|
|
pytorch_grad_cam/__pycache__/base_cam.cpython-39.pyc
ADDED
Binary file (5.84 kB). View file
|
|
pytorch_grad_cam/__pycache__/eigen_cam.cpython-39.pyc
ADDED
Binary file (931 Bytes). View file
|
|
pytorch_grad_cam/__pycache__/eigen_grad_cam.cpython-39.pyc
ADDED
Binary file (925 Bytes). View file
|
|
pytorch_grad_cam/__pycache__/fullgrad_cam.cpython-39.pyc
ADDED
Binary file (3.18 kB). View file
|
|
pytorch_grad_cam/__pycache__/grad_cam.cpython-39.pyc
ADDED
Binary file (872 Bytes). View file
|
|
pytorch_grad_cam/__pycache__/grad_cam_elementwise.cpython-39.pyc
ADDED
Binary file (1.09 kB). View file
|
|
pytorch_grad_cam/__pycache__/grad_cam_plusplus.cpython-39.pyc
ADDED
Binary file (1.12 kB). View file
|
|
pytorch_grad_cam/__pycache__/guided_backprop.cpython-39.pyc
ADDED
Binary file (3.41 kB). View file
|
|
pytorch_grad_cam/__pycache__/hirescam.cpython-39.pyc
ADDED
Binary file (1.12 kB). View file
|
|
pytorch_grad_cam/__pycache__/layer_cam.cpython-39.pyc
ADDED
Binary file (1.06 kB). View file
|
|
pytorch_grad_cam/__pycache__/random_cam.cpython-39.pyc
ADDED
Binary file (921 Bytes). View file
|
|
pytorch_grad_cam/__pycache__/score_cam.cpython-39.pyc
ADDED
Binary file (1.96 kB). View file
|
|
pytorch_grad_cam/__pycache__/xgrad_cam.cpython-39.pyc
ADDED
Binary file (983 Bytes). View file
|
|
pytorch_grad_cam/ablation_cam.py
ADDED
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import torch
|
3 |
+
import tqdm
|
4 |
+
from typing import Callable, List
|
5 |
+
from pytorch_grad_cam.base_cam import BaseCAM
|
6 |
+
from pytorch_grad_cam.utils.find_layers import replace_layer_recursive
|
7 |
+
from pytorch_grad_cam.ablation_layer import AblationLayer
|
8 |
+
|
9 |
+
|
10 |
+
""" Implementation of AblationCAM
|
11 |
+
https://openaccess.thecvf.com/content_WACV_2020/papers/Desai_Ablation-CAM_Visual_Explanations_for_Deep_Convolutional_Network_via_Gradient-free_Localization_WACV_2020_paper.pdf
|
12 |
+
|
13 |
+
Ablate individual activations, and then measure the drop in the target score.
|
14 |
+
|
15 |
+
In the current implementation, the target layer activations is cached, so it won't be re-computed.
|
16 |
+
However layers before it, if any, will not be cached.
|
17 |
+
This means that if the target layer is a large block, for example model.featuers (in vgg), there will
|
18 |
+
be a large save in run time.
|
19 |
+
|
20 |
+
Since we have to go over many channels and ablate them, and every channel ablation requires a forward pass,
|
21 |
+
it would be nice if we could avoid doing that for channels that won't contribute anwyay, making it much faster.
|
22 |
+
The parameter ratio_channels_to_ablate controls how many channels should be ablated, using an experimental method
|
23 |
+
(to be improved). The default 1.0 value means that all channels will be ablated.
|
24 |
+
"""
|
25 |
+
|
26 |
+
|
27 |
+
class AblationCAM(BaseCAM):
|
28 |
+
def __init__(self,
|
29 |
+
model: torch.nn.Module,
|
30 |
+
target_layers: List[torch.nn.Module],
|
31 |
+
use_cuda: bool = False,
|
32 |
+
reshape_transform: Callable = None,
|
33 |
+
ablation_layer: torch.nn.Module = AblationLayer(),
|
34 |
+
batch_size: int = 32,
|
35 |
+
ratio_channels_to_ablate: float = 1.0) -> None:
|
36 |
+
|
37 |
+
super(AblationCAM, self).__init__(model,
|
38 |
+
target_layers,
|
39 |
+
use_cuda,
|
40 |
+
reshape_transform,
|
41 |
+
uses_gradients=False)
|
42 |
+
self.batch_size = batch_size
|
43 |
+
self.ablation_layer = ablation_layer
|
44 |
+
self.ratio_channels_to_ablate = ratio_channels_to_ablate
|
45 |
+
|
46 |
+
def save_activation(self, module, input, output) -> None:
|
47 |
+
""" Helper function to save the raw activations from the target layer """
|
48 |
+
self.activations = output
|
49 |
+
|
50 |
+
def assemble_ablation_scores(self,
|
51 |
+
new_scores: list,
|
52 |
+
original_score: float,
|
53 |
+
ablated_channels: np.ndarray,
|
54 |
+
number_of_channels: int) -> np.ndarray:
|
55 |
+
""" Take the value from the channels that were ablated,
|
56 |
+
and just set the original score for the channels that were skipped """
|
57 |
+
|
58 |
+
index = 0
|
59 |
+
result = []
|
60 |
+
sorted_indices = np.argsort(ablated_channels)
|
61 |
+
ablated_channels = ablated_channels[sorted_indices]
|
62 |
+
new_scores = np.float32(new_scores)[sorted_indices]
|
63 |
+
|
64 |
+
for i in range(number_of_channels):
|
65 |
+
if index < len(ablated_channels) and ablated_channels[index] == i:
|
66 |
+
weight = new_scores[index]
|
67 |
+
index = index + 1
|
68 |
+
else:
|
69 |
+
weight = original_score
|
70 |
+
result.append(weight)
|
71 |
+
|
72 |
+
return result
|
73 |
+
|
74 |
+
def get_cam_weights(self,
|
75 |
+
input_tensor: torch.Tensor,
|
76 |
+
target_layer: torch.nn.Module,
|
77 |
+
targets: List[Callable],
|
78 |
+
activations: torch.Tensor,
|
79 |
+
grads: torch.Tensor) -> np.ndarray:
|
80 |
+
|
81 |
+
# Do a forward pass, compute the target scores, and cache the
|
82 |
+
# activations
|
83 |
+
handle = target_layer.register_forward_hook(self.save_activation)
|
84 |
+
with torch.no_grad():
|
85 |
+
outputs = self.model(input_tensor)
|
86 |
+
handle.remove()
|
87 |
+
original_scores = np.float32(
|
88 |
+
[target(output).cpu().item() for target, output in zip(targets, outputs)])
|
89 |
+
|
90 |
+
# Replace the layer with the ablation layer.
|
91 |
+
# When we finish, we will replace it back, so the original model is
|
92 |
+
# unchanged.
|
93 |
+
ablation_layer = self.ablation_layer
|
94 |
+
replace_layer_recursive(self.model, target_layer, ablation_layer)
|
95 |
+
|
96 |
+
number_of_channels = activations.shape[1]
|
97 |
+
weights = []
|
98 |
+
# This is a "gradient free" method, so we don't need gradients here.
|
99 |
+
with torch.no_grad():
|
100 |
+
# Loop over each of the batch images and ablate activations for it.
|
101 |
+
for batch_index, (target, tensor) in enumerate(
|
102 |
+
zip(targets, input_tensor)):
|
103 |
+
new_scores = []
|
104 |
+
batch_tensor = tensor.repeat(self.batch_size, 1, 1, 1)
|
105 |
+
|
106 |
+
# Check which channels should be ablated. Normally this will be all channels,
|
107 |
+
# But we can also try to speed this up by using a low
|
108 |
+
# ratio_channels_to_ablate.
|
109 |
+
channels_to_ablate = ablation_layer.activations_to_be_ablated(
|
110 |
+
activations[batch_index, :], self.ratio_channels_to_ablate)
|
111 |
+
number_channels_to_ablate = len(channels_to_ablate)
|
112 |
+
|
113 |
+
for i in tqdm.tqdm(
|
114 |
+
range(
|
115 |
+
0,
|
116 |
+
number_channels_to_ablate,
|
117 |
+
self.batch_size)):
|
118 |
+
if i + self.batch_size > number_channels_to_ablate:
|
119 |
+
batch_tensor = batch_tensor[:(
|
120 |
+
number_channels_to_ablate - i)]
|
121 |
+
|
122 |
+
# Change the state of the ablation layer so it ablates the next channels.
|
123 |
+
# TBD: Move this into the ablation layer forward pass.
|
124 |
+
ablation_layer.set_next_batch(
|
125 |
+
input_batch_index=batch_index,
|
126 |
+
activations=self.activations,
|
127 |
+
num_channels_to_ablate=batch_tensor.size(0))
|
128 |
+
score = [target(o).cpu().item()
|
129 |
+
for o in self.model(batch_tensor)]
|
130 |
+
new_scores.extend(score)
|
131 |
+
ablation_layer.indices = ablation_layer.indices[batch_tensor.size(
|
132 |
+
0):]
|
133 |
+
|
134 |
+
new_scores = self.assemble_ablation_scores(
|
135 |
+
new_scores,
|
136 |
+
original_scores[batch_index],
|
137 |
+
channels_to_ablate,
|
138 |
+
number_of_channels)
|
139 |
+
weights.extend(new_scores)
|
140 |
+
|
141 |
+
weights = np.float32(weights)
|
142 |
+
weights = weights.reshape(activations.shape[:2])
|
143 |
+
original_scores = original_scores[:, None]
|
144 |
+
weights = (original_scores - weights) / original_scores
|
145 |
+
|
146 |
+
# Replace the model back to the original state
|
147 |
+
replace_layer_recursive(self.model, ablation_layer, target_layer)
|
148 |
+
return weights
|
pytorch_grad_cam/ablation_cam_multilayer.py
ADDED
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
import numpy as np
|
3 |
+
import torch
|
4 |
+
import tqdm
|
5 |
+
from pytorch_grad_cam.base_cam import BaseCAM
|
6 |
+
|
7 |
+
|
8 |
+
class AblationLayer(torch.nn.Module):
|
9 |
+
def __init__(self, layer, reshape_transform, indices):
|
10 |
+
super(AblationLayer, self).__init__()
|
11 |
+
|
12 |
+
self.layer = layer
|
13 |
+
self.reshape_transform = reshape_transform
|
14 |
+
# The channels to zero out:
|
15 |
+
self.indices = indices
|
16 |
+
|
17 |
+
def forward(self, x):
|
18 |
+
self.__call__(x)
|
19 |
+
|
20 |
+
def __call__(self, x):
|
21 |
+
output = self.layer(x)
|
22 |
+
|
23 |
+
# Hack to work with ViT,
|
24 |
+
# Since the activation channels are last and not first like in CNNs
|
25 |
+
# Probably should remove it?
|
26 |
+
if self.reshape_transform is not None:
|
27 |
+
output = output.transpose(1, 2)
|
28 |
+
|
29 |
+
for i in range(output.size(0)):
|
30 |
+
|
31 |
+
# Commonly the minimum activation will be 0,
|
32 |
+
# And then it makes sense to zero it out.
|
33 |
+
# However depending on the architecture,
|
34 |
+
# If the values can be negative, we use very negative values
|
35 |
+
# to perform the ablation, deviating from the paper.
|
36 |
+
if torch.min(output) == 0:
|
37 |
+
output[i, self.indices[i], :] = 0
|
38 |
+
else:
|
39 |
+
ABLATION_VALUE = 1e5
|
40 |
+
output[i, self.indices[i], :] = torch.min(
|
41 |
+
output) - ABLATION_VALUE
|
42 |
+
|
43 |
+
if self.reshape_transform is not None:
|
44 |
+
output = output.transpose(2, 1)
|
45 |
+
|
46 |
+
return output
|
47 |
+
|
48 |
+
|
49 |
+
def replace_layer_recursive(model, old_layer, new_layer):
|
50 |
+
for name, layer in model._modules.items():
|
51 |
+
if layer == old_layer:
|
52 |
+
model._modules[name] = new_layer
|
53 |
+
return True
|
54 |
+
elif replace_layer_recursive(layer, old_layer, new_layer):
|
55 |
+
return True
|
56 |
+
return False
|
57 |
+
|
58 |
+
|
59 |
+
class AblationCAM(BaseCAM):
|
60 |
+
def __init__(self, model, target_layers, use_cuda=False,
|
61 |
+
reshape_transform=None):
|
62 |
+
super(AblationCAM, self).__init__(model, target_layers, use_cuda,
|
63 |
+
reshape_transform)
|
64 |
+
|
65 |
+
if len(target_layers) > 1:
|
66 |
+
print(
|
67 |
+
"Warning. You are usign Ablation CAM with more than 1 layers. "
|
68 |
+
"This is supported only if all layers have the same output shape")
|
69 |
+
|
70 |
+
def set_ablation_layers(self):
|
71 |
+
self.ablation_layers = []
|
72 |
+
for target_layer in self.target_layers:
|
73 |
+
ablation_layer = AblationLayer(target_layer,
|
74 |
+
self.reshape_transform, indices=[])
|
75 |
+
self.ablation_layers.append(ablation_layer)
|
76 |
+
replace_layer_recursive(self.model, target_layer, ablation_layer)
|
77 |
+
|
78 |
+
def unset_ablation_layers(self):
|
79 |
+
# replace the model back to the original state
|
80 |
+
for ablation_layer, target_layer in zip(
|
81 |
+
self.ablation_layers, self.target_layers):
|
82 |
+
replace_layer_recursive(self.model, ablation_layer, target_layer)
|
83 |
+
|
84 |
+
def set_ablation_layer_batch_indices(self, indices):
|
85 |
+
for ablation_layer in self.ablation_layers:
|
86 |
+
ablation_layer.indices = indices
|
87 |
+
|
88 |
+
def trim_ablation_layer_batch_indices(self, keep):
|
89 |
+
for ablation_layer in self.ablation_layers:
|
90 |
+
ablation_layer.indices = ablation_layer.indices[:keep]
|
91 |
+
|
92 |
+
def get_cam_weights(self,
|
93 |
+
input_tensor,
|
94 |
+
target_category,
|
95 |
+
activations,
|
96 |
+
grads):
|
97 |
+
with torch.no_grad():
|
98 |
+
outputs = self.model(input_tensor).cpu().numpy()
|
99 |
+
original_scores = []
|
100 |
+
for i in range(input_tensor.size(0)):
|
101 |
+
original_scores.append(outputs[i, target_category[i]])
|
102 |
+
original_scores = np.float32(original_scores)
|
103 |
+
|
104 |
+
self.set_ablation_layers()
|
105 |
+
|
106 |
+
if hasattr(self, "batch_size"):
|
107 |
+
BATCH_SIZE = self.batch_size
|
108 |
+
else:
|
109 |
+
BATCH_SIZE = 32
|
110 |
+
|
111 |
+
number_of_channels = activations.shape[1]
|
112 |
+
weights = []
|
113 |
+
|
114 |
+
with torch.no_grad():
|
115 |
+
# Iterate over the input batch
|
116 |
+
for tensor, category in zip(input_tensor, target_category):
|
117 |
+
batch_tensor = tensor.repeat(BATCH_SIZE, 1, 1, 1)
|
118 |
+
for i in tqdm.tqdm(range(0, number_of_channels, BATCH_SIZE)):
|
119 |
+
self.set_ablation_layer_batch_indices(
|
120 |
+
list(range(i, i + BATCH_SIZE)))
|
121 |
+
|
122 |
+
if i + BATCH_SIZE > number_of_channels:
|
123 |
+
keep = number_of_channels - i
|
124 |
+
batch_tensor = batch_tensor[:keep]
|
125 |
+
self.trim_ablation_layer_batch_indices(self, keep)
|
126 |
+
score = self.model(batch_tensor)[:, category].cpu().numpy()
|
127 |
+
weights.extend(score)
|
128 |
+
|
129 |
+
weights = np.float32(weights)
|
130 |
+
weights = weights.reshape(activations.shape[:2])
|
131 |
+
original_scores = original_scores[:, None]
|
132 |
+
weights = (original_scores - weights) / original_scores
|
133 |
+
|
134 |
+
# replace the model back to the original state
|
135 |
+
self.unset_ablation_layers()
|
136 |
+
return weights
|
pytorch_grad_cam/ablation_layer.py
ADDED
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from collections import OrderedDict
|
3 |
+
import numpy as np
|
4 |
+
from pytorch_grad_cam.utils.svd_on_activations import get_2d_projection
|
5 |
+
|
6 |
+
|
7 |
+
class AblationLayer(torch.nn.Module):
|
8 |
+
def __init__(self):
|
9 |
+
super(AblationLayer, self).__init__()
|
10 |
+
|
11 |
+
def objectiveness_mask_from_svd(self, activations, threshold=0.01):
|
12 |
+
""" Experimental method to get a binary mask to compare if the activation is worth ablating.
|
13 |
+
The idea is to apply the EigenCAM method by doing PCA on the activations.
|
14 |
+
Then we create a binary mask by comparing to a low threshold.
|
15 |
+
Areas that are masked out, are probably not interesting anyway.
|
16 |
+
"""
|
17 |
+
|
18 |
+
projection = get_2d_projection(activations[None, :])[0, :]
|
19 |
+
projection = np.abs(projection)
|
20 |
+
projection = projection - projection.min()
|
21 |
+
projection = projection / projection.max()
|
22 |
+
projection = projection > threshold
|
23 |
+
return projection
|
24 |
+
|
25 |
+
def activations_to_be_ablated(
|
26 |
+
self,
|
27 |
+
activations,
|
28 |
+
ratio_channels_to_ablate=1.0):
|
29 |
+
""" Experimental method to get a binary mask to compare if the activation is worth ablating.
|
30 |
+
Create a binary CAM mask with objectiveness_mask_from_svd.
|
31 |
+
Score each Activation channel, by seeing how much of its values are inside the mask.
|
32 |
+
Then keep the top channels.
|
33 |
+
|
34 |
+
"""
|
35 |
+
if ratio_channels_to_ablate == 1.0:
|
36 |
+
self.indices = np.int32(range(activations.shape[0]))
|
37 |
+
return self.indices
|
38 |
+
|
39 |
+
projection = self.objectiveness_mask_from_svd(activations)
|
40 |
+
|
41 |
+
scores = []
|
42 |
+
for channel in activations:
|
43 |
+
normalized = np.abs(channel)
|
44 |
+
normalized = normalized - normalized.min()
|
45 |
+
normalized = normalized / np.max(normalized)
|
46 |
+
score = (projection * normalized).sum() / normalized.sum()
|
47 |
+
scores.append(score)
|
48 |
+
scores = np.float32(scores)
|
49 |
+
|
50 |
+
indices = list(np.argsort(scores))
|
51 |
+
high_score_indices = indices[::-
|
52 |
+
1][: int(len(indices) *
|
53 |
+
ratio_channels_to_ablate)]
|
54 |
+
low_score_indices = indices[: int(
|
55 |
+
len(indices) * ratio_channels_to_ablate)]
|
56 |
+
self.indices = np.int32(high_score_indices + low_score_indices)
|
57 |
+
return self.indices
|
58 |
+
|
59 |
+
def set_next_batch(
|
60 |
+
self,
|
61 |
+
input_batch_index,
|
62 |
+
activations,
|
63 |
+
num_channels_to_ablate):
|
64 |
+
""" This creates the next batch of activations from the layer.
|
65 |
+
Just take corresponding batch member from activations, and repeat it num_channels_to_ablate times.
|
66 |
+
"""
|
67 |
+
self.activations = activations[input_batch_index, :, :, :].clone(
|
68 |
+
).unsqueeze(0).repeat(num_channels_to_ablate, 1, 1, 1)
|
69 |
+
|
70 |
+
def __call__(self, x):
|
71 |
+
output = self.activations
|
72 |
+
for i in range(output.size(0)):
|
73 |
+
# Commonly the minimum activation will be 0,
|
74 |
+
# And then it makes sense to zero it out.
|
75 |
+
# However depending on the architecture,
|
76 |
+
# If the values can be negative, we use very negative values
|
77 |
+
# to perform the ablation, deviating from the paper.
|
78 |
+
if torch.min(output) == 0:
|
79 |
+
output[i, self.indices[i], :] = 0
|
80 |
+
else:
|
81 |
+
ABLATION_VALUE = 1e7
|
82 |
+
output[i, self.indices[i], :] = torch.min(
|
83 |
+
output) - ABLATION_VALUE
|
84 |
+
|
85 |
+
return output
|
86 |
+
|
87 |
+
|
88 |
+
class AblationLayerVit(AblationLayer):
|
89 |
+
def __init__(self):
|
90 |
+
super(AblationLayerVit, self).__init__()
|
91 |
+
|
92 |
+
def __call__(self, x):
|
93 |
+
output = self.activations
|
94 |
+
output = output.transpose(1, len(output.shape) - 1)
|
95 |
+
for i in range(output.size(0)):
|
96 |
+
|
97 |
+
# Commonly the minimum activation will be 0,
|
98 |
+
# And then it makes sense to zero it out.
|
99 |
+
# However depending on the architecture,
|
100 |
+
# If the values can be negative, we use very negative values
|
101 |
+
# to perform the ablation, deviating from the paper.
|
102 |
+
if torch.min(output) == 0:
|
103 |
+
output[i, self.indices[i], :] = 0
|
104 |
+
else:
|
105 |
+
ABLATION_VALUE = 1e7
|
106 |
+
output[i, self.indices[i], :] = torch.min(
|
107 |
+
output) - ABLATION_VALUE
|
108 |
+
|
109 |
+
output = output.transpose(len(output.shape) - 1, 1)
|
110 |
+
|
111 |
+
return output
|
112 |
+
|
113 |
+
def set_next_batch(
|
114 |
+
self,
|
115 |
+
input_batch_index,
|
116 |
+
activations,
|
117 |
+
num_channels_to_ablate):
|
118 |
+
""" This creates the next batch of activations from the layer.
|
119 |
+
Just take corresponding batch member from activations, and repeat it num_channels_to_ablate times.
|
120 |
+
"""
|
121 |
+
repeat_params = [num_channels_to_ablate] + \
|
122 |
+
len(activations.shape[:-1]) * [1]
|
123 |
+
self.activations = activations[input_batch_index, :, :].clone(
|
124 |
+
).unsqueeze(0).repeat(*repeat_params)
|
125 |
+
|
126 |
+
|
127 |
+
class AblationLayerFasterRCNN(AblationLayer):
|
128 |
+
def __init__(self):
|
129 |
+
super(AblationLayerFasterRCNN, self).__init__()
|
130 |
+
|
131 |
+
def set_next_batch(
|
132 |
+
self,
|
133 |
+
input_batch_index,
|
134 |
+
activations,
|
135 |
+
num_channels_to_ablate):
|
136 |
+
""" Extract the next batch member from activations,
|
137 |
+
and repeat it num_channels_to_ablate times.
|
138 |
+
"""
|
139 |
+
self.activations = OrderedDict()
|
140 |
+
for key, value in activations.items():
|
141 |
+
fpn_activation = value[input_batch_index,
|
142 |
+
:, :, :].clone().unsqueeze(0)
|
143 |
+
self.activations[key] = fpn_activation.repeat(
|
144 |
+
num_channels_to_ablate, 1, 1, 1)
|
145 |
+
|
146 |
+
def __call__(self, x):
|
147 |
+
result = self.activations
|
148 |
+
layers = {0: '0', 1: '1', 2: '2', 3: '3', 4: 'pool'}
|
149 |
+
num_channels_to_ablate = result['pool'].size(0)
|
150 |
+
for i in range(num_channels_to_ablate):
|
151 |
+
pyramid_layer = int(self.indices[i] / 256)
|
152 |
+
index_in_pyramid_layer = int(self.indices[i] % 256)
|
153 |
+
result[layers[pyramid_layer]][i,
|
154 |
+
index_in_pyramid_layer, :, :] = -1000
|
155 |
+
return result
|
pytorch_grad_cam/activations_and_gradients.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
class ActivationsAndGradients:
|
2 |
+
""" Class for extracting activations and
|
3 |
+
registering gradients from targetted intermediate layers """
|
4 |
+
|
5 |
+
def __init__(self, model, target_layers, reshape_transform):
|
6 |
+
self.model = model
|
7 |
+
self.gradients = []
|
8 |
+
self.activations = []
|
9 |
+
self.reshape_transform = reshape_transform
|
10 |
+
self.handles = []
|
11 |
+
for target_layer in target_layers:
|
12 |
+
self.handles.append(
|
13 |
+
target_layer.register_forward_hook(self.save_activation))
|
14 |
+
# Because of https://github.com/pytorch/pytorch/issues/61519,
|
15 |
+
# we don't use backward hook to record gradients.
|
16 |
+
self.handles.append(
|
17 |
+
target_layer.register_forward_hook(self.save_gradient))
|
18 |
+
|
19 |
+
def save_activation(self, module, input, output):
|
20 |
+
activation = output
|
21 |
+
|
22 |
+
if self.reshape_transform is not None:
|
23 |
+
activation = self.reshape_transform(activation)
|
24 |
+
self.activations.append(activation.cpu().detach())
|
25 |
+
|
26 |
+
def save_gradient(self, module, input, output):
|
27 |
+
if not hasattr(output, "requires_grad") or not output.requires_grad:
|
28 |
+
# You can only register hooks on tensor requires grad.
|
29 |
+
return
|
30 |
+
|
31 |
+
# Gradients are computed in reverse order
|
32 |
+
def _store_grad(grad):
|
33 |
+
if self.reshape_transform is not None:
|
34 |
+
grad = self.reshape_transform(grad)
|
35 |
+
self.gradients = [grad.cpu().detach()] + self.gradients
|
36 |
+
|
37 |
+
output.register_hook(_store_grad)
|
38 |
+
|
39 |
+
def __call__(self, x):
|
40 |
+
self.gradients = []
|
41 |
+
self.activations = []
|
42 |
+
return self.model(x)
|
43 |
+
|
44 |
+
def release(self):
|
45 |
+
for handle in self.handles:
|
46 |
+
handle.remove()
|
pytorch_grad_cam/base_cam.py
ADDED
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import torch
|
3 |
+
import ttach as tta
|
4 |
+
from typing import Callable, List, Tuple
|
5 |
+
from pytorch_grad_cam.activations_and_gradients import ActivationsAndGradients
|
6 |
+
from pytorch_grad_cam.utils.svd_on_activations import get_2d_projection
|
7 |
+
from pytorch_grad_cam.utils.image import scale_cam_image
|
8 |
+
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
|
9 |
+
|
10 |
+
|
11 |
+
class BaseCAM:
|
12 |
+
def __init__(self,
|
13 |
+
model: torch.nn.Module,
|
14 |
+
target_layers: List[torch.nn.Module],
|
15 |
+
use_cuda: bool = False,
|
16 |
+
reshape_transform: Callable = None,
|
17 |
+
compute_input_gradient: bool = False,
|
18 |
+
uses_gradients: bool = True) -> None:
|
19 |
+
self.model = model.eval()
|
20 |
+
self.target_layers = target_layers
|
21 |
+
self.cuda = use_cuda
|
22 |
+
if self.cuda:
|
23 |
+
self.model = model.cuda()
|
24 |
+
self.reshape_transform = reshape_transform
|
25 |
+
self.compute_input_gradient = compute_input_gradient
|
26 |
+
self.uses_gradients = uses_gradients
|
27 |
+
self.activations_and_grads = ActivationsAndGradients(
|
28 |
+
self.model, target_layers, reshape_transform)
|
29 |
+
|
30 |
+
""" Get a vector of weights for every channel in the target layer.
|
31 |
+
Methods that return weights channels,
|
32 |
+
will typically need to only implement this function. """
|
33 |
+
|
34 |
+
def get_cam_weights(self,
|
35 |
+
input_tensor: torch.Tensor,
|
36 |
+
target_layers: List[torch.nn.Module],
|
37 |
+
targets: List[torch.nn.Module],
|
38 |
+
activations: torch.Tensor,
|
39 |
+
grads: torch.Tensor) -> np.ndarray:
|
40 |
+
raise Exception("Not Implemented")
|
41 |
+
|
42 |
+
def get_cam_image(self,
|
43 |
+
input_tensor: torch.Tensor,
|
44 |
+
target_layer: torch.nn.Module,
|
45 |
+
targets: List[torch.nn.Module],
|
46 |
+
activations: torch.Tensor,
|
47 |
+
grads: torch.Tensor,
|
48 |
+
eigen_smooth: bool = False) -> np.ndarray:
|
49 |
+
|
50 |
+
weights = self.get_cam_weights(input_tensor,
|
51 |
+
target_layer,
|
52 |
+
targets,
|
53 |
+
activations,
|
54 |
+
grads)
|
55 |
+
weighted_activations = weights[:, :, None, None] * activations
|
56 |
+
if eigen_smooth:
|
57 |
+
cam = get_2d_projection(weighted_activations)
|
58 |
+
else:
|
59 |
+
cam = weighted_activations.sum(axis=1)
|
60 |
+
return cam
|
61 |
+
|
62 |
+
def forward(self,
|
63 |
+
input_tensor: torch.Tensor,
|
64 |
+
targets: List[torch.nn.Module],
|
65 |
+
eigen_smooth: bool = False) -> np.ndarray:
|
66 |
+
|
67 |
+
if self.cuda:
|
68 |
+
input_tensor = input_tensor.cuda()
|
69 |
+
|
70 |
+
if self.compute_input_gradient:
|
71 |
+
input_tensor = torch.autograd.Variable(input_tensor,
|
72 |
+
requires_grad=True)
|
73 |
+
|
74 |
+
outputs = self.activations_and_grads(input_tensor)
|
75 |
+
outputs = outputs.pooler_output # Only for ViT-GPT2 or any other VisionEncoderDecoder model
|
76 |
+
print(outputs)
|
77 |
+
if targets is None:
|
78 |
+
target_categories = np.argmax(outputs.cpu().data.numpy(), axis=-1) #np.argmax(outputs.cpu().data.numpy(), axis=-1)
|
79 |
+
targets = [ClassifierOutputTarget(
|
80 |
+
category) for category in target_categories]
|
81 |
+
|
82 |
+
if self.uses_gradients:
|
83 |
+
self.model.zero_grad()
|
84 |
+
loss = sum([target(output)
|
85 |
+
for target, output in zip(targets, outputs)])
|
86 |
+
loss.backward(retain_graph=True)
|
87 |
+
|
88 |
+
# In most of the saliency attribution papers, the saliency is
|
89 |
+
# computed with a single target layer.
|
90 |
+
# Commonly it is the last convolutional layer.
|
91 |
+
# Here we support passing a list with multiple target layers.
|
92 |
+
# It will compute the saliency image for every image,
|
93 |
+
# and then aggregate them (with a default mean aggregation).
|
94 |
+
# This gives you more flexibility in case you just want to
|
95 |
+
# use all conv layers for example, all Batchnorm layers,
|
96 |
+
# or something else.
|
97 |
+
cam_per_layer = self.compute_cam_per_layer(input_tensor,
|
98 |
+
targets,
|
99 |
+
eigen_smooth)
|
100 |
+
return self.aggregate_multi_layers(cam_per_layer)
|
101 |
+
|
102 |
+
def get_target_width_height(self,
|
103 |
+
input_tensor: torch.Tensor) -> Tuple[int, int]:
|
104 |
+
width, height = input_tensor.size(-1), input_tensor.size(-2)
|
105 |
+
return width, height
|
106 |
+
|
107 |
+
def compute_cam_per_layer(
|
108 |
+
self,
|
109 |
+
input_tensor: torch.Tensor,
|
110 |
+
targets: List[torch.nn.Module],
|
111 |
+
eigen_smooth: bool) -> np.ndarray:
|
112 |
+
activations_list = [a.cpu().data.numpy()
|
113 |
+
for a in self.activations_and_grads.activations]
|
114 |
+
grads_list = [g.cpu().data.numpy()
|
115 |
+
for g in self.activations_and_grads.gradients]
|
116 |
+
target_size = self.get_target_width_height(input_tensor)
|
117 |
+
|
118 |
+
cam_per_target_layer = []
|
119 |
+
# Loop over the saliency image from every layer
|
120 |
+
for i in range(len(self.target_layers)):
|
121 |
+
target_layer = self.target_layers[i]
|
122 |
+
layer_activations = None
|
123 |
+
layer_grads = None
|
124 |
+
if i < len(activations_list):
|
125 |
+
layer_activations = activations_list[i]
|
126 |
+
if i < len(grads_list):
|
127 |
+
layer_grads = grads_list[i]
|
128 |
+
|
129 |
+
cam = self.get_cam_image(input_tensor,
|
130 |
+
target_layer,
|
131 |
+
targets,
|
132 |
+
layer_activations,
|
133 |
+
layer_grads,
|
134 |
+
eigen_smooth)
|
135 |
+
cam = np.maximum(cam, 0)
|
136 |
+
scaled = scale_cam_image(cam, target_size)
|
137 |
+
cam_per_target_layer.append(scaled[:, None, :])
|
138 |
+
|
139 |
+
return cam_per_target_layer
|
140 |
+
|
141 |
+
def aggregate_multi_layers(
|
142 |
+
self,
|
143 |
+
cam_per_target_layer: np.ndarray) -> np.ndarray:
|
144 |
+
cam_per_target_layer = np.concatenate(cam_per_target_layer, axis=1)
|
145 |
+
cam_per_target_layer = np.maximum(cam_per_target_layer, 0)
|
146 |
+
result = np.mean(cam_per_target_layer, axis=1)
|
147 |
+
return scale_cam_image(result)
|
148 |
+
|
149 |
+
def forward_augmentation_smoothing(self,
|
150 |
+
input_tensor: torch.Tensor,
|
151 |
+
targets: List[torch.nn.Module],
|
152 |
+
eigen_smooth: bool = False) -> np.ndarray:
|
153 |
+
transforms = tta.Compose(
|
154 |
+
[
|
155 |
+
tta.HorizontalFlip(),
|
156 |
+
tta.Multiply(factors=[0.9, 1, 1.1]),
|
157 |
+
]
|
158 |
+
)
|
159 |
+
cams = []
|
160 |
+
for transform in transforms:
|
161 |
+
augmented_tensor = transform.augment_image(input_tensor)
|
162 |
+
cam = self.forward(augmented_tensor,
|
163 |
+
targets,
|
164 |
+
eigen_smooth)
|
165 |
+
|
166 |
+
# The ttach library expects a tensor of size BxCxHxW
|
167 |
+
cam = cam[:, None, :, :]
|
168 |
+
cam = torch.from_numpy(cam)
|
169 |
+
cam = transform.deaugment_mask(cam)
|
170 |
+
|
171 |
+
# Back to numpy float32, HxW
|
172 |
+
cam = cam.numpy()
|
173 |
+
cam = cam[:, 0, :, :]
|
174 |
+
cams.append(cam)
|
175 |
+
|
176 |
+
cam = np.mean(np.float32(cams), axis=0)
|
177 |
+
return cam
|
178 |
+
|
179 |
+
def __call__(self,
|
180 |
+
input_tensor: torch.Tensor,
|
181 |
+
targets: List[torch.nn.Module] = None,
|
182 |
+
aug_smooth: bool = False,
|
183 |
+
eigen_smooth: bool = False) -> np.ndarray:
|
184 |
+
|
185 |
+
# Smooth the CAM result with test time augmentation
|
186 |
+
if aug_smooth is True:
|
187 |
+
return self.forward_augmentation_smoothing(
|
188 |
+
input_tensor, targets, eigen_smooth)
|
189 |
+
|
190 |
+
return self.forward(input_tensor,
|
191 |
+
targets, eigen_smooth)
|
192 |
+
|
193 |
+
def __del__(self):
|
194 |
+
self.activations_and_grads.release()
|
195 |
+
|
196 |
+
def __enter__(self):
|
197 |
+
return self
|
198 |
+
|
199 |
+
def __exit__(self, exc_type, exc_value, exc_tb):
|
200 |
+
self.activations_and_grads.release()
|
201 |
+
if isinstance(exc_value, IndexError):
|
202 |
+
# Handle IndexError here...
|
203 |
+
print(
|
204 |
+
f"An exception occurred in CAM with block: {exc_type}. Message: {exc_value}")
|
205 |
+
return True
|
pytorch_grad_cam/cam_mult_image.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import numpy as np
|
3 |
+
from typing import List, Callable
|
4 |
+
from pytorch_grad_cam.metrics.perturbation_confidence import PerturbationConfidenceMetric
|
5 |
+
|
6 |
+
|
7 |
+
def multiply_tensor_with_cam(input_tensor: torch.Tensor,
|
8 |
+
cam: torch.Tensor):
|
9 |
+
""" Multiply an input tensor (after normalization)
|
10 |
+
with a pixel attribution map
|
11 |
+
"""
|
12 |
+
return input_tensor * cam
|
13 |
+
|
14 |
+
|
15 |
+
class CamMultImageConfidenceChange(PerturbationConfidenceMetric):
|
16 |
+
def __init__(self):
|
17 |
+
super(CamMultImageConfidenceChange,
|
18 |
+
self).__init__(multiply_tensor_with_cam)
|
19 |
+
|
20 |
+
|
21 |
+
class DropInConfidence(CamMultImageConfidenceChange):
|
22 |
+
def __init__(self):
|
23 |
+
super(DropInConfidence, self).__init__()
|
24 |
+
|
25 |
+
def __call__(self, *args, **kwargs):
|
26 |
+
scores = super(DropInConfidence, self).__call__(*args, **kwargs)
|
27 |
+
scores = -scores
|
28 |
+
return np.maximum(scores, 0)
|
29 |
+
|
30 |
+
|
31 |
+
class IncreaseInConfidence(CamMultImageConfidenceChange):
|
32 |
+
def __init__(self):
|
33 |
+
super(IncreaseInConfidence, self).__init__()
|
34 |
+
|
35 |
+
def __call__(self, *args, **kwargs):
|
36 |
+
scores = super(IncreaseInConfidence, self).__call__(*args, **kwargs)
|
37 |
+
return np.float32(scores > 0)
|
pytorch_grad_cam/eigen_cam.py
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pytorch_grad_cam.base_cam import BaseCAM
|
2 |
+
from pytorch_grad_cam.utils.svd_on_activations import get_2d_projection
|
3 |
+
|
4 |
+
# https://arxiv.org/abs/2008.00299
|
5 |
+
|
6 |
+
|
7 |
+
class EigenCAM(BaseCAM):
|
8 |
+
def __init__(self, model, target_layers, use_cuda=False,
|
9 |
+
reshape_transform=None):
|
10 |
+
super(EigenCAM, self).__init__(model,
|
11 |
+
target_layers,
|
12 |
+
use_cuda,
|
13 |
+
reshape_transform,
|
14 |
+
uses_gradients=False)
|
15 |
+
|
16 |
+
def get_cam_image(self,
|
17 |
+
input_tensor,
|
18 |
+
target_layer,
|
19 |
+
target_category,
|
20 |
+
activations,
|
21 |
+
grads,
|
22 |
+
eigen_smooth):
|
23 |
+
return get_2d_projection(activations)
|
pytorch_grad_cam/eigen_grad_cam.py
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pytorch_grad_cam.base_cam import BaseCAM
|
2 |
+
from pytorch_grad_cam.utils.svd_on_activations import get_2d_projection
|
3 |
+
|
4 |
+
# Like Eigen CAM: https://arxiv.org/abs/2008.00299
|
5 |
+
# But multiply the activations x gradients
|
6 |
+
|
7 |
+
|
8 |
+
class EigenGradCAM(BaseCAM):
|
9 |
+
def __init__(self, model, target_layers, use_cuda=False,
|
10 |
+
reshape_transform=None):
|
11 |
+
super(EigenGradCAM, self).__init__(model, target_layers, use_cuda,
|
12 |
+
reshape_transform)
|
13 |
+
|
14 |
+
def get_cam_image(self,
|
15 |
+
input_tensor,
|
16 |
+
target_layer,
|
17 |
+
target_category,
|
18 |
+
activations,
|
19 |
+
grads,
|
20 |
+
eigen_smooth):
|
21 |
+
return get_2d_projection(grads * activations)
|
pytorch_grad_cam/feature_factorization/__init__.py
ADDED
File without changes
|
pytorch_grad_cam/feature_factorization/__pycache__/__init__.cpython-39.pyc
ADDED
Binary file (163 Bytes). View file
|
|
pytorch_grad_cam/feature_factorization/__pycache__/deep_feature_factorization.cpython-39.pyc
ADDED
Binary file (4.73 kB). View file
|
|
pytorch_grad_cam/feature_factorization/deep_feature_factorization.py
ADDED
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from PIL import Image
|
3 |
+
import torch
|
4 |
+
from typing import Callable, List, Tuple, Optional
|
5 |
+
from sklearn.decomposition import NMF
|
6 |
+
from pytorch_grad_cam.activations_and_gradients import ActivationsAndGradients
|
7 |
+
from pytorch_grad_cam.utils.image import scale_cam_image, create_labels_legend, show_factorization_on_image
|
8 |
+
|
9 |
+
|
10 |
+
def dff(activations: np.ndarray, n_components: int = 5):
|
11 |
+
""" Compute Deep Feature Factorization on a 2d Activations tensor.
|
12 |
+
|
13 |
+
:param activations: A numpy array of shape batch x channels x height x width
|
14 |
+
:param n_components: The number of components for the non negative matrix factorization
|
15 |
+
:returns: A tuple of the concepts (a numpy array with shape channels x components),
|
16 |
+
and the explanation heatmaps (a numpy arary with shape batch x height x width)
|
17 |
+
"""
|
18 |
+
|
19 |
+
batch_size, channels, h, w = activations.shape
|
20 |
+
reshaped_activations = activations.transpose((1, 0, 2, 3))
|
21 |
+
reshaped_activations[np.isnan(reshaped_activations)] = 0
|
22 |
+
reshaped_activations = reshaped_activations.reshape(
|
23 |
+
reshaped_activations.shape[0], -1)
|
24 |
+
offset = reshaped_activations.min(axis=-1)
|
25 |
+
reshaped_activations = reshaped_activations - offset[:, None]
|
26 |
+
|
27 |
+
model = NMF(n_components=n_components, init='random', random_state=0)
|
28 |
+
W = model.fit_transform(reshaped_activations)
|
29 |
+
H = model.components_
|
30 |
+
concepts = W + offset[:, None]
|
31 |
+
explanations = H.reshape(n_components, batch_size, h, w)
|
32 |
+
explanations = explanations.transpose((1, 0, 2, 3))
|
33 |
+
return concepts, explanations
|
34 |
+
|
35 |
+
|
36 |
+
class DeepFeatureFactorization:
|
37 |
+
""" Deep Feature Factorization: https://arxiv.org/abs/1806.10206
|
38 |
+
This gets a model andcomputes the 2D activations for a target layer,
|
39 |
+
and computes Non Negative Matrix Factorization on the activations.
|
40 |
+
|
41 |
+
Optionally it runs a computation on the concept embeddings,
|
42 |
+
like running a classifier on them.
|
43 |
+
|
44 |
+
The explanation heatmaps are scalled to the range [0, 1]
|
45 |
+
and to the input tensor width and height.
|
46 |
+
"""
|
47 |
+
|
48 |
+
def __init__(self,
|
49 |
+
model: torch.nn.Module,
|
50 |
+
target_layer: torch.nn.Module,
|
51 |
+
reshape_transform: Callable = None,
|
52 |
+
computation_on_concepts=None
|
53 |
+
):
|
54 |
+
self.model = model
|
55 |
+
self.computation_on_concepts = computation_on_concepts
|
56 |
+
self.activations_and_grads = ActivationsAndGradients(
|
57 |
+
self.model, [target_layer], reshape_transform)
|
58 |
+
|
59 |
+
def __call__(self,
|
60 |
+
input_tensor: torch.Tensor,
|
61 |
+
n_components: int = 16):
|
62 |
+
batch_size, channels, h, w = input_tensor.size()
|
63 |
+
_ = self.activations_and_grads(input_tensor)
|
64 |
+
|
65 |
+
with torch.no_grad():
|
66 |
+
activations = self.activations_and_grads.activations[0].cpu(
|
67 |
+
).numpy()
|
68 |
+
|
69 |
+
concepts, explanations = dff(activations, n_components=n_components)
|
70 |
+
|
71 |
+
processed_explanations = []
|
72 |
+
|
73 |
+
for batch in explanations:
|
74 |
+
processed_explanations.append(scale_cam_image(batch, (w, h)))
|
75 |
+
|
76 |
+
if self.computation_on_concepts:
|
77 |
+
with torch.no_grad():
|
78 |
+
concept_tensors = torch.from_numpy(
|
79 |
+
np.float32(concepts).transpose((1, 0)))
|
80 |
+
concept_outputs = self.computation_on_concepts(
|
81 |
+
concept_tensors).cpu().numpy()
|
82 |
+
return concepts, processed_explanations, concept_outputs
|
83 |
+
else:
|
84 |
+
return concepts, processed_explanations
|
85 |
+
|
86 |
+
def __del__(self):
|
87 |
+
self.activations_and_grads.release()
|
88 |
+
|
89 |
+
def __exit__(self, exc_type, exc_value, exc_tb):
|
90 |
+
self.activations_and_grads.release()
|
91 |
+
if isinstance(exc_value, IndexError):
|
92 |
+
# Handle IndexError here...
|
93 |
+
print(
|
94 |
+
f"An exception occurred in ActivationSummary with block: {exc_type}. Message: {exc_value}")
|
95 |
+
return True
|
96 |
+
|
97 |
+
|
98 |
+
def run_dff_on_image(model: torch.nn.Module,
|
99 |
+
target_layer: torch.nn.Module,
|
100 |
+
classifier: torch.nn.Module,
|
101 |
+
img_pil: Image,
|
102 |
+
img_tensor: torch.Tensor,
|
103 |
+
reshape_transform=Optional[Callable],
|
104 |
+
n_components: int = 5,
|
105 |
+
top_k: int = 2) -> np.ndarray:
|
106 |
+
""" Helper function to create a Deep Feature Factorization visualization for a single image.
|
107 |
+
TBD: Run this on a batch with several images.
|
108 |
+
"""
|
109 |
+
rgb_img_float = np.array(img_pil) / 255
|
110 |
+
dff = DeepFeatureFactorization(model=model,
|
111 |
+
reshape_transform=reshape_transform,
|
112 |
+
target_layer=target_layer,
|
113 |
+
computation_on_concepts=classifier)
|
114 |
+
|
115 |
+
concepts, batch_explanations, concept_outputs = dff(
|
116 |
+
img_tensor[None, :], n_components)
|
117 |
+
|
118 |
+
concept_outputs = torch.softmax(
|
119 |
+
torch.from_numpy(concept_outputs),
|
120 |
+
axis=-1).numpy()
|
121 |
+
concept_label_strings = create_labels_legend(concept_outputs,
|
122 |
+
labels=model.config.id2label,
|
123 |
+
top_k=top_k)
|
124 |
+
visualization = show_factorization_on_image(
|
125 |
+
rgb_img_float,
|
126 |
+
batch_explanations[0],
|
127 |
+
image_weight=0.3,
|
128 |
+
concept_labels=concept_label_strings)
|
129 |
+
|
130 |
+
result = np.hstack((np.array(img_pil), visualization))
|
131 |
+
return result
|
pytorch_grad_cam/fullgrad_cam.py
ADDED
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import torch
|
3 |
+
from pytorch_grad_cam.base_cam import BaseCAM
|
4 |
+
from pytorch_grad_cam.utils.find_layers import find_layer_predicate_recursive
|
5 |
+
from pytorch_grad_cam.utils.svd_on_activations import get_2d_projection
|
6 |
+
from pytorch_grad_cam.utils.image import scale_accross_batch_and_channels, scale_cam_image
|
7 |
+
|
8 |
+
# https://arxiv.org/abs/1905.00780
|
9 |
+
|
10 |
+
|
11 |
+
class FullGrad(BaseCAM):
|
12 |
+
def __init__(self, model, target_layers, use_cuda=False,
|
13 |
+
reshape_transform=None):
|
14 |
+
if len(target_layers) > 0:
|
15 |
+
print(
|
16 |
+
"Warning: target_layers is ignored in FullGrad. All bias layers will be used instead")
|
17 |
+
|
18 |
+
def layer_with_2D_bias(layer):
|
19 |
+
bias_target_layers = [torch.nn.Conv2d, torch.nn.BatchNorm2d]
|
20 |
+
if type(layer) in bias_target_layers and layer.bias is not None:
|
21 |
+
return True
|
22 |
+
return False
|
23 |
+
target_layers = find_layer_predicate_recursive(
|
24 |
+
model, layer_with_2D_bias)
|
25 |
+
super(
|
26 |
+
FullGrad,
|
27 |
+
self).__init__(
|
28 |
+
model,
|
29 |
+
target_layers,
|
30 |
+
use_cuda,
|
31 |
+
reshape_transform,
|
32 |
+
compute_input_gradient=True)
|
33 |
+
self.bias_data = [self.get_bias_data(
|
34 |
+
layer).cpu().numpy() for layer in target_layers]
|
35 |
+
|
36 |
+
def get_bias_data(self, layer):
|
37 |
+
# Borrowed from official paper impl:
|
38 |
+
# https://github.com/idiap/fullgrad-saliency/blob/master/saliency/tensor_extractor.py#L47
|
39 |
+
if isinstance(layer, torch.nn.BatchNorm2d):
|
40 |
+
bias = - (layer.running_mean * layer.weight
|
41 |
+
/ torch.sqrt(layer.running_var + layer.eps)) + layer.bias
|
42 |
+
return bias.data
|
43 |
+
else:
|
44 |
+
return layer.bias.data
|
45 |
+
|
46 |
+
def compute_cam_per_layer(
|
47 |
+
self,
|
48 |
+
input_tensor,
|
49 |
+
target_category,
|
50 |
+
eigen_smooth):
|
51 |
+
input_grad = input_tensor.grad.data.cpu().numpy()
|
52 |
+
grads_list = [g.cpu().data.numpy() for g in
|
53 |
+
self.activations_and_grads.gradients]
|
54 |
+
cam_per_target_layer = []
|
55 |
+
target_size = self.get_target_width_height(input_tensor)
|
56 |
+
|
57 |
+
gradient_multiplied_input = input_grad * input_tensor.data.cpu().numpy()
|
58 |
+
gradient_multiplied_input = np.abs(gradient_multiplied_input)
|
59 |
+
gradient_multiplied_input = scale_accross_batch_and_channels(
|
60 |
+
gradient_multiplied_input,
|
61 |
+
target_size)
|
62 |
+
cam_per_target_layer.append(gradient_multiplied_input)
|
63 |
+
|
64 |
+
# Loop over the saliency image from every layer
|
65 |
+
assert(len(self.bias_data) == len(grads_list))
|
66 |
+
for bias, grads in zip(self.bias_data, grads_list):
|
67 |
+
bias = bias[None, :, None, None]
|
68 |
+
# In the paper they take the absolute value,
|
69 |
+
# but possibily taking only the positive gradients will work
|
70 |
+
# better.
|
71 |
+
bias_grad = np.abs(bias * grads)
|
72 |
+
result = scale_accross_batch_and_channels(
|
73 |
+
bias_grad, target_size)
|
74 |
+
result = np.sum(result, axis=1)
|
75 |
+
cam_per_target_layer.append(result[:, None, :])
|
76 |
+
cam_per_target_layer = np.concatenate(cam_per_target_layer, axis=1)
|
77 |
+
if eigen_smooth:
|
78 |
+
# Resize to a smaller image, since this method typically has a very large number of channels,
|
79 |
+
# and then consumes a lot of memory
|
80 |
+
cam_per_target_layer = scale_accross_batch_and_channels(
|
81 |
+
cam_per_target_layer, (target_size[0] // 8, target_size[1] // 8))
|
82 |
+
cam_per_target_layer = get_2d_projection(cam_per_target_layer)
|
83 |
+
cam_per_target_layer = cam_per_target_layer[:, None, :, :]
|
84 |
+
cam_per_target_layer = scale_accross_batch_and_channels(
|
85 |
+
cam_per_target_layer,
|
86 |
+
target_size)
|
87 |
+
else:
|
88 |
+
cam_per_target_layer = np.sum(
|
89 |
+
cam_per_target_layer, axis=1)[:, None, :]
|
90 |
+
|
91 |
+
return cam_per_target_layer
|
92 |
+
|
93 |
+
def aggregate_multi_layers(self, cam_per_target_layer):
|
94 |
+
result = np.sum(cam_per_target_layer, axis=1)
|
95 |
+
return scale_cam_image(result)
|
pytorch_grad_cam/grad_cam.py
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from pytorch_grad_cam.base_cam import BaseCAM
|
3 |
+
|
4 |
+
|
5 |
+
class GradCAM(BaseCAM):
|
6 |
+
def __init__(self, model, target_layers, use_cuda=False,
|
7 |
+
reshape_transform=None):
|
8 |
+
super(
|
9 |
+
GradCAM,
|
10 |
+
self).__init__(
|
11 |
+
model,
|
12 |
+
target_layers,
|
13 |
+
use_cuda,
|
14 |
+
reshape_transform)
|
15 |
+
|
16 |
+
def get_cam_weights(self,
|
17 |
+
input_tensor,
|
18 |
+
target_layer,
|
19 |
+
target_category,
|
20 |
+
activations,
|
21 |
+
grads):
|
22 |
+
return np.mean(grads, axis=(2, 3))
|
pytorch_grad_cam/grad_cam_elementwise.py
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from pytorch_grad_cam.base_cam import BaseCAM
|
3 |
+
from pytorch_grad_cam.utils.svd_on_activations import get_2d_projection
|
4 |
+
|
5 |
+
|
6 |
+
class GradCAMElementWise(BaseCAM):
|
7 |
+
def __init__(self, model, target_layers, use_cuda=False,
|
8 |
+
reshape_transform=None):
|
9 |
+
super(
|
10 |
+
GradCAMElementWise,
|
11 |
+
self).__init__(
|
12 |
+
model,
|
13 |
+
target_layers,
|
14 |
+
use_cuda,
|
15 |
+
reshape_transform)
|
16 |
+
|
17 |
+
def get_cam_image(self,
|
18 |
+
input_tensor,
|
19 |
+
target_layer,
|
20 |
+
target_category,
|
21 |
+
activations,
|
22 |
+
grads,
|
23 |
+
eigen_smooth):
|
24 |
+
elementwise_activations = np.maximum(grads * activations, 0)
|
25 |
+
|
26 |
+
if eigen_smooth:
|
27 |
+
cam = get_2d_projection(elementwise_activations)
|
28 |
+
else:
|
29 |
+
cam = elementwise_activations.sum(axis=1)
|
30 |
+
return cam
|
pytorch_grad_cam/grad_cam_plusplus.py
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from pytorch_grad_cam.base_cam import BaseCAM
|
3 |
+
|
4 |
+
# https://arxiv.org/abs/1710.11063
|
5 |
+
|
6 |
+
|
7 |
+
class GradCAMPlusPlus(BaseCAM):
|
8 |
+
def __init__(self, model, target_layers, use_cuda=False,
|
9 |
+
reshape_transform=None):
|
10 |
+
super(GradCAMPlusPlus, self).__init__(model, target_layers, use_cuda,
|
11 |
+
reshape_transform)
|
12 |
+
|
13 |
+
def get_cam_weights(self,
|
14 |
+
input_tensor,
|
15 |
+
target_layers,
|
16 |
+
target_category,
|
17 |
+
activations,
|
18 |
+
grads):
|
19 |
+
grads_power_2 = grads**2
|
20 |
+
grads_power_3 = grads_power_2 * grads
|
21 |
+
# Equation 19 in https://arxiv.org/abs/1710.11063
|
22 |
+
sum_activations = np.sum(activations, axis=(2, 3))
|
23 |
+
eps = 0.000001
|
24 |
+
aij = grads_power_2 / (2 * grads_power_2 +
|
25 |
+
sum_activations[:, :, None, None] * grads_power_3 + eps)
|
26 |
+
# Now bring back the ReLU from eq.7 in the paper,
|
27 |
+
# And zero out aijs where the activations are 0
|
28 |
+
aij = np.where(grads != 0, aij, 0)
|
29 |
+
|
30 |
+
weights = np.maximum(grads, 0) * aij
|
31 |
+
weights = np.sum(weights, axis=(2, 3))
|
32 |
+
return weights
|
pytorch_grad_cam/guided_backprop.py
ADDED
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import torch
|
3 |
+
from torch.autograd import Function
|
4 |
+
from pytorch_grad_cam.utils.find_layers import replace_all_layer_type_recursive
|
5 |
+
|
6 |
+
|
7 |
+
class GuidedBackpropReLU(Function):
|
8 |
+
@staticmethod
|
9 |
+
def forward(self, input_img):
|
10 |
+
positive_mask = (input_img > 0).type_as(input_img)
|
11 |
+
output = torch.addcmul(
|
12 |
+
torch.zeros(
|
13 |
+
input_img.size()).type_as(input_img),
|
14 |
+
input_img,
|
15 |
+
positive_mask)
|
16 |
+
self.save_for_backward(input_img, output)
|
17 |
+
return output
|
18 |
+
|
19 |
+
@staticmethod
|
20 |
+
def backward(self, grad_output):
|
21 |
+
input_img, output = self.saved_tensors
|
22 |
+
grad_input = None
|
23 |
+
|
24 |
+
positive_mask_1 = (input_img > 0).type_as(grad_output)
|
25 |
+
positive_mask_2 = (grad_output > 0).type_as(grad_output)
|
26 |
+
grad_input = torch.addcmul(
|
27 |
+
torch.zeros(
|
28 |
+
input_img.size()).type_as(input_img),
|
29 |
+
torch.addcmul(
|
30 |
+
torch.zeros(
|
31 |
+
input_img.size()).type_as(input_img),
|
32 |
+
grad_output,
|
33 |
+
positive_mask_1),
|
34 |
+
positive_mask_2)
|
35 |
+
return grad_input
|
36 |
+
|
37 |
+
|
38 |
+
class GuidedBackpropReLUasModule(torch.nn.Module):
|
39 |
+
def __init__(self):
|
40 |
+
super(GuidedBackpropReLUasModule, self).__init__()
|
41 |
+
|
42 |
+
def forward(self, input_img):
|
43 |
+
return GuidedBackpropReLU.apply(input_img)
|
44 |
+
|
45 |
+
|
46 |
+
class GuidedBackpropReLUModel:
|
47 |
+
def __init__(self, model, use_cuda):
|
48 |
+
self.model = model
|
49 |
+
self.model.eval()
|
50 |
+
self.cuda = use_cuda
|
51 |
+
if self.cuda:
|
52 |
+
self.model = self.model.cuda()
|
53 |
+
|
54 |
+
def forward(self, input_img):
|
55 |
+
return self.model(input_img)
|
56 |
+
|
57 |
+
def recursive_replace_relu_with_guidedrelu(self, module_top):
|
58 |
+
|
59 |
+
for idx, module in module_top._modules.items():
|
60 |
+
self.recursive_replace_relu_with_guidedrelu(module)
|
61 |
+
if module.__class__.__name__ == 'ReLU':
|
62 |
+
module_top._modules[idx] = GuidedBackpropReLU.apply
|
63 |
+
print("b")
|
64 |
+
|
65 |
+
def recursive_replace_guidedrelu_with_relu(self, module_top):
|
66 |
+
try:
|
67 |
+
for idx, module in module_top._modules.items():
|
68 |
+
self.recursive_replace_guidedrelu_with_relu(module)
|
69 |
+
if module == GuidedBackpropReLU.apply:
|
70 |
+
module_top._modules[idx] = torch.nn.ReLU()
|
71 |
+
except BaseException:
|
72 |
+
pass
|
73 |
+
|
74 |
+
def __call__(self, input_img, target_category=None):
|
75 |
+
replace_all_layer_type_recursive(self.model,
|
76 |
+
torch.nn.ReLU,
|
77 |
+
GuidedBackpropReLUasModule())
|
78 |
+
|
79 |
+
if self.cuda:
|
80 |
+
input_img = input_img.cuda()
|
81 |
+
|
82 |
+
input_img = input_img.requires_grad_(True)
|
83 |
+
|
84 |
+
output = self.forward(input_img)
|
85 |
+
|
86 |
+
if target_category is None:
|
87 |
+
target_category = np.argmax(output.cpu().data.numpy())
|
88 |
+
|
89 |
+
loss = output[0, target_category]
|
90 |
+
loss.backward(retain_graph=True)
|
91 |
+
|
92 |
+
output = input_img.grad.cpu().data.numpy()
|
93 |
+
output = output[0, :, :, :]
|
94 |
+
output = output.transpose((1, 2, 0))
|
95 |
+
|
96 |
+
replace_all_layer_type_recursive(self.model,
|
97 |
+
GuidedBackpropReLUasModule,
|
98 |
+
torch.nn.ReLU())
|
99 |
+
|
100 |
+
return output
|
pytorch_grad_cam/hirescam.py
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from pytorch_grad_cam.base_cam import BaseCAM
|
3 |
+
from pytorch_grad_cam.utils.svd_on_activations import get_2d_projection
|
4 |
+
|
5 |
+
|
6 |
+
class HiResCAM(BaseCAM):
|
7 |
+
def __init__(self, model, target_layers, use_cuda=False,
|
8 |
+
reshape_transform=None):
|
9 |
+
super(
|
10 |
+
HiResCAM,
|
11 |
+
self).__init__(
|
12 |
+
model,
|
13 |
+
target_layers,
|
14 |
+
use_cuda,
|
15 |
+
reshape_transform)
|
16 |
+
|
17 |
+
def get_cam_image(self,
|
18 |
+
input_tensor,
|
19 |
+
target_layer,
|
20 |
+
target_category,
|
21 |
+
activations,
|
22 |
+
grads,
|
23 |
+
eigen_smooth):
|
24 |
+
elementwise_activations = grads * activations
|
25 |
+
|
26 |
+
if eigen_smooth:
|
27 |
+
print(
|
28 |
+
"Warning: HiResCAM's faithfulness guarantees do not hold if smoothing is applied")
|
29 |
+
cam = get_2d_projection(elementwise_activations)
|
30 |
+
else:
|
31 |
+
cam = elementwise_activations.sum(axis=1)
|
32 |
+
return cam
|
pytorch_grad_cam/layer_cam.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from pytorch_grad_cam.base_cam import BaseCAM
|
3 |
+
from pytorch_grad_cam.utils.svd_on_activations import get_2d_projection
|
4 |
+
|
5 |
+
# https://ieeexplore.ieee.org/document/9462463
|
6 |
+
|
7 |
+
|
8 |
+
class LayerCAM(BaseCAM):
|
9 |
+
def __init__(
|
10 |
+
self,
|
11 |
+
model,
|
12 |
+
target_layers,
|
13 |
+
use_cuda=False,
|
14 |
+
reshape_transform=None):
|
15 |
+
super(
|
16 |
+
LayerCAM,
|
17 |
+
self).__init__(
|
18 |
+
model,
|
19 |
+
target_layers,
|
20 |
+
use_cuda,
|
21 |
+
reshape_transform)
|
22 |
+
|
23 |
+
def get_cam_image(self,
|
24 |
+
input_tensor,
|
25 |
+
target_layer,
|
26 |
+
target_category,
|
27 |
+
activations,
|
28 |
+
grads,
|
29 |
+
eigen_smooth):
|
30 |
+
spatial_weighted_activations = np.maximum(grads, 0) * activations
|
31 |
+
|
32 |
+
if eigen_smooth:
|
33 |
+
cam = get_2d_projection(spatial_weighted_activations)
|
34 |
+
else:
|
35 |
+
cam = spatial_weighted_activations.sum(axis=1)
|
36 |
+
return cam
|