Skip to content

Instantly share code, notes, and snippets.

@jimmy15923
Last active February 11, 2019 06:25
Show Gist options
  • Save jimmy15923/aad522dd0fa57965215796bda942d46f to your computer and use it in GitHub Desktop.
Save jimmy15923/aad522dd0fa57965215796bda942d46f to your computer and use it in GitHub Desktop.
def grad_cam(img, model):
"""Gradient Activation Map for keras model
# Arguments
img: image to plot gradcam
model: keras model
# Returns
gradcam image
"""
img = np.expand_dims(img, 0)
last_conv_layer = model.get_layer('leaky_re_lu_17').output # setup the correct name for last conv layer
grads = K.gradients(model.get_layer('dense_1').output[:,1], last_conv_layer)[0]
pooled_grads = K.mean(grads, axis=(0, 1, 2))
out = model.output[:,1]
iterate = K.function([model.get_layer("input_1").input],
[pooled_grads, last_conv_layer[0], out])
pooled_grads_value, conv_layer_output_value, output = iterate([img])
# 2048 for ResNet-50, since the shape of feature maps is (NoneX?x?x2048)
for i in range(2048):
conv_layer_output_value[:,:,:,i] *= pooled_grads_value[i]
gradcam = np.mean(conv_layer_output_value, axis=-1)
gradcam = np.maximum(gradcam, 0)
gradcam /= np.max(gradcam)
import skimage
import scipy
cam = scipy.ndimage.zoom(gradcam, 16, mode="nearest")
gradcams.append(cam)
print(x, output)
return gradcams
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment