Skip to content

Commit 044e86b

Browse files
author
whyboris
committed
attention
1 parent e12ae09 commit 044e86b

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

attention.py

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,5 +23,45 @@
2323
predictions = model.predict(x)
2424
print('predicted: ', decode_predictions(predictions, top=3)[0])
2525

26-
print(np.argmax(predictions[0]))
26+
print(np.argmax(predictions[0])) # output of this needs to be on the next line
27+
28+
cat_output = model.output[:, 285] # this number comes from the output of previous line
29+
30+
last_conv_layer = model.get_layer('block3_conv3')
31+
32+
from keras import backend as K
33+
34+
grads = K.gradients(cat_output, last_conv_layer.output)[0]
35+
36+
pooled_grads = K.mean(grads, axis=(0, 1, 2))
37+
38+
iterate = K.function([model.input], [pooled_grads, last_conv_layer.output[0]])
39+
40+
pooled_grads_value, conv_layer_output_value = iterate([x])
41+
42+
for i in range (255):
43+
conv_layer_output_value[:, :, i] *= pooled_grads_value[i]
44+
45+
heatmap = np.mean(conv_layer_output_value, axis=-1)
46+
47+
import matplotlib.pyplot as plt
48+
49+
heatmap = np.maximum(heatmap, 0)
50+
heatmap /= np.max(heatmap)
51+
plt.matshow(heatmap)
52+
plt.show()
53+
54+
import cv2
55+
56+
img = cv2.imread(img_path)
57+
58+
heatmap = cv2.resize(heatmap, (img.shape[1], img.shape[0]))
59+
60+
heatmap = np.uint8(255 * heatmap)
61+
62+
heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
63+
64+
superimposed_img = heatmap * 0.4 + img
65+
66+
cv2.imwrite('../heatmap.jpg', superimposed_img)
2767

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
autopep8
2+
cv2
23
jupyter
34
keras
45
matplotlib

0 commit comments

Comments
 (0)