Skip to content

Instantly share code, notes, and snippets.

@cnd
Created April 29, 2020 18:04
Show Gist options
  • Save cnd/f8fc3c27c8951038c0ce2f1759dce1f5 to your computer and use it in GitHub Desktop.
Save cnd/f8fc3c27c8951038c0ce2f1759dce1f5 to your computer and use it in GitHub Desktop.
def grad_cam(input_model, model_x, orig_x, category_index, layer_name, class_names):
output = input_model.output
final_layer = Lambda(lambda x: target_category_loss(x, category_index, len(class_names)))
output = final_layer(output)
model = Model(inputs=input_model.input, outputs=output)
loss = K.sum(model.layers[-1].output)
conv_output = model.get_layer(layer_name).output
grads = normalize(K.gradients(loss, conv_output)[0])
gradient_function = K.function([model.layers[0].input, K.learning_phase()], [conv_output, grads])
output, grads_val = gradient_function([model_x, 0])
output, grads_val = output[0, :], grads_val[0, :, :, :]
weights = np.mean(grads_val, axis=(0, 1))
cam = np.zeros(output.shape[0: 2], dtype=np.float32)
for i, w in enumerate(weights):
cam += w * output[:, :, i]
cam = np.maximum(cam, np.zeros(output.shape[0: 2], dtype=np.float32))
cam = cam.squeeze()
cam = cv2.applyColorMap(np.uint8(255 * cam / np.max(cam)), cv2.COLORMAP_JET)
cam = cv2.resize(cam, (np.shape(orig_x)[0], np.shape(orig_x)[1]))
cam = 0.4 * cam + 0.6 * orig_x
return np.uint8(cam)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment