Python ELI5 Explaining Keras image classifier predictions with Grad-CAM: Loading our model and data, Explaining our model prediction, Choosing the target class, Choosing a hidden activation layer














































Python ELI5 Explaining Keras image classifier predictions with Grad-CAM: Loading our model and data, Explaining our model prediction, Choosing the target class, Choosing a hidden activation layer



Loading our model and data

To begin out, we  have to get our modules in place

from PIL import Image
from IPython.display import display
import numpy as np

# you may want to keep logging enabled when doing your own work
import logging
import tensorflow as tf
tf.get_logger().setLevel(logging.ERROR)
# disable Tensorflow warnings for this tutorial
import warnings
warnings.simplefilter(
"ignore") # disable Keras warnings for this tutorial
import keras
from keras.applications import mobilenet_v2

import eli5

Then we will load our image classifier

model = mobilenet_v2.MobileNetV2(include_top=True, weights='imagenet', classes=1000)

# check the input format
print(model.input_shape)
dims = model.input_shape[
1:3] # -> (height, width)
print(dims)




It can be seen that we need a numpy tensor of shape with a detailed height and width.

Then we will load our sample image:

# we start from a path / URI.
# If you already have an image loaded, follow the subsequent steps
image_uri = 'imagenet-samples/cat_dog.jpg'

# this is the original "cat dog" image used in the Grad-CAM paper
# check the image with Pillow
im = Image.open(image_uri)
print(type(im))
display(I'm)

<class 'PIL.JpegImagePlugin.JpegImageFile'>