Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
keras-team
GitHub Repository: keras-team/keras-io
Path: blob/master/examples/vision/grad_cam.py
3507 views
1
"""
2
Title: Grad-CAM class activation visualization
3
Author: [fchollet](https://twitter.com/fchollet)
4
Date created: 2020/04/26
5
Last modified: 2021/03/07
6
Description: How to obtain a class activation heatmap for an image classification model.
7
Accelerator: GPU
8
"""
9
10
"""
11
Adapted from Deep Learning with Python (2017).
12
13
## Setup
14
"""
15
16
import os
17
18
os.environ["KERAS_BACKEND"] = "tensorflow"
19
20
import numpy as np
21
import tensorflow as tf
22
import keras
23
24
# Display
25
from IPython.display import Image, display
26
import matplotlib as mpl
27
import matplotlib.pyplot as plt
28
29
30
"""
31
## Configurable parameters
32
33
You can change these to another model.
34
35
To get the values for `last_conv_layer_name` use `model.summary()`
36
to see the names of all layers in the model.
37
"""
38
39
model_builder = keras.applications.xception.Xception
40
img_size = (299, 299)
41
preprocess_input = keras.applications.xception.preprocess_input
42
decode_predictions = keras.applications.xception.decode_predictions
43
44
last_conv_layer_name = "block14_sepconv2_act"
45
46
# The local path to our target image
47
img_path = keras.utils.get_file(
48
"african_elephant.jpg", "https://i.imgur.com/Bvro0YD.png"
49
)
50
51
display(Image(img_path))
52
53
54
"""
55
## The Grad-CAM algorithm
56
"""
57
58
59
def get_img_array(img_path, size):
60
# `img` is a PIL image of size 299x299
61
img = keras.utils.load_img(img_path, target_size=size)
62
# `array` is a float32 Numpy array of shape (299, 299, 3)
63
array = keras.utils.img_to_array(img)
64
# We add a dimension to transform our array into a "batch"
65
# of size (1, 299, 299, 3)
66
array = np.expand_dims(array, axis=0)
67
return array
68
69
70
def make_gradcam_heatmap(img_array, model, last_conv_layer_name, pred_index=None):
71
# First, we create a model that maps the input image to the activations
72
# of the last conv layer as well as the output predictions
73
grad_model = keras.models.Model(
74
model.inputs, [model.get_layer(last_conv_layer_name).output, model.output]
75
)
76
77
# Then, we compute the gradient of the top predicted class for our input image
78
# with respect to the activations of the last conv layer
79
with tf.GradientTape() as tape:
80
last_conv_layer_output, preds = grad_model(img_array)
81
if pred_index is None:
82
pred_index = tf.argmax(preds[0])
83
class_channel = preds[:, pred_index]
84
85
# This is the gradient of the output neuron (top predicted or chosen)
86
# with regard to the output feature map of the last conv layer
87
grads = tape.gradient(class_channel, last_conv_layer_output)
88
89
# This is a vector where each entry is the mean intensity of the gradient
90
# over a specific feature map channel
91
pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
92
93
# We multiply each channel in the feature map array
94
# by "how important this channel is" with regard to the top predicted class
95
# then sum all the channels to obtain the heatmap class activation
96
last_conv_layer_output = last_conv_layer_output[0]
97
heatmap = last_conv_layer_output @ pooled_grads[..., tf.newaxis]
98
heatmap = tf.squeeze(heatmap)
99
100
# For visualization purpose, we will also normalize the heatmap between 0 & 1
101
heatmap = tf.maximum(heatmap, 0) / tf.math.reduce_max(heatmap)
102
return heatmap.numpy()
103
104
105
"""
106
## Let's test-drive it
107
"""
108
109
# Prepare image
110
img_array = preprocess_input(get_img_array(img_path, size=img_size))
111
112
# Make model
113
model = model_builder(weights="imagenet")
114
115
# Remove last layer's softmax
116
model.layers[-1].activation = None
117
118
# Print what the top predicted class is
119
preds = model.predict(img_array)
120
print("Predicted:", decode_predictions(preds, top=1)[0])
121
122
# Generate class activation heatmap
123
heatmap = make_gradcam_heatmap(img_array, model, last_conv_layer_name)
124
125
# Display heatmap
126
plt.matshow(heatmap)
127
plt.show()
128
129
130
"""
131
## Create a superimposed visualization
132
"""
133
134
135
def save_and_display_gradcam(img_path, heatmap, cam_path="cam.jpg", alpha=0.4):
136
# Load the original image
137
img = keras.utils.load_img(img_path)
138
img = keras.utils.img_to_array(img)
139
140
# Rescale heatmap to a range 0-255
141
heatmap = np.uint8(255 * heatmap)
142
143
# Use jet colormap to colorize heatmap
144
jet = mpl.colormaps["jet"]
145
146
# Use RGB values of the colormap
147
jet_colors = jet(np.arange(256))[:, :3]
148
jet_heatmap = jet_colors[heatmap]
149
150
# Create an image with RGB colorized heatmap
151
jet_heatmap = keras.utils.array_to_img(jet_heatmap)
152
jet_heatmap = jet_heatmap.resize((img.shape[1], img.shape[0]))
153
jet_heatmap = keras.utils.img_to_array(jet_heatmap)
154
155
# Superimpose the heatmap on original image
156
superimposed_img = jet_heatmap * alpha + img
157
superimposed_img = keras.utils.array_to_img(superimposed_img)
158
159
# Save the superimposed image
160
superimposed_img.save(cam_path)
161
162
# Display Grad CAM
163
display(Image(cam_path))
164
165
166
save_and_display_gradcam(img_path, heatmap)
167
168
"""
169
## Let's try another image
170
171
We will see how the grad cam explains the model's outputs for a multi-label image. Let's
172
try an image with a cat and a dog together, and see how the grad cam behaves.
173
"""
174
175
img_path = keras.utils.get_file(
176
"cat_and_dog.jpg",
177
"https://storage.googleapis.com/petbacker/images/blog/2017/dog-and-cat-cover.jpg",
178
)
179
180
display(Image(img_path))
181
182
# Prepare image
183
img_array = preprocess_input(get_img_array(img_path, size=img_size))
184
185
# Print what the two top predicted classes are
186
preds = model.predict(img_array)
187
print("Predicted:", decode_predictions(preds, top=2)[0])
188
189
"""
190
We generate class activation heatmap for "chow," the class index is 260
191
"""
192
193
heatmap = make_gradcam_heatmap(img_array, model, last_conv_layer_name, pred_index=260)
194
195
save_and_display_gradcam(img_path, heatmap)
196
197
"""
198
We generate class activation heatmap for "egyptian cat," the class index is 285
199
"""
200
201
heatmap = make_gradcam_heatmap(img_array, model, last_conv_layer_name, pred_index=285)
202
203
save_and_display_gradcam(img_path, heatmap)
204
205