Front Page DeepExplainer MNIST ExampleΒΆ

A simple example showing how to explain an MNIST CNN trained using Keras with DeepExplainer.

[1]:
# this is the code from https://github.com/keras-team/keras/blob/master/examples/mnist_cnn.py
from __future__ import print_function
from tensorflow import keras
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras import backend as K

batch_size = 128
num_classes = 10
epochs = 12

# input image dimensions
img_rows, img_cols = 28, 28

# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
x_train shape: (60000, 28, 28, 1)
60000 train samples
10000 test samples
Epoch 1/12
469/469 [==============================] - 3s 6ms/step - loss: 2.2744 - accuracy: 0.1710 - val_loss: 2.2266 - val_accuracy: 0.3799
Epoch 2/12
469/469 [==============================] - 3s 6ms/step - loss: 2.2010 - accuracy: 0.2961 - val_loss: 2.1392 - val_accuracy: 0.6018
Epoch 3/12
469/469 [==============================] - 3s 6ms/step - loss: 2.1095 - accuracy: 0.4158 - val_loss: 2.0201 - val_accuracy: 0.7019
Epoch 4/12
469/469 [==============================] - 3s 6ms/step - loss: 1.9825 - accuracy: 0.5015 - val_loss: 1.8575 - val_accuracy: 0.7410
Epoch 5/12
469/469 [==============================] - 3s 6ms/step - loss: 1.8225 - accuracy: 0.5543 - val_loss: 1.6553 - val_accuracy: 0.7576
Epoch 6/12
469/469 [==============================] - 3s 6ms/step - loss: 1.6373 - accuracy: 0.5940 - val_loss: 1.4329 - val_accuracy: 0.7700
Epoch 7/12
469/469 [==============================] - 3s 6ms/step - loss: 1.4548 - accuracy: 0.6216 - val_loss: 1.2223 - val_accuracy: 0.7899
Epoch 8/12
469/469 [==============================] - 3s 6ms/step - loss: 1.2902 - accuracy: 0.6561 - val_loss: 1.0445 - val_accuracy: 0.8035
Epoch 9/12
469/469 [==============================] - 3s 6ms/step - loss: 1.1648 - accuracy: 0.6743 - val_loss: 0.9074 - val_accuracy: 0.8184
Epoch 10/12
469/469 [==============================] - 3s 6ms/step - loss: 1.0600 - accuracy: 0.6961 - val_loss: 0.8037 - val_accuracy: 0.8279
Epoch 11/12
469/469 [==============================] - 3s 6ms/step - loss: 0.9834 - accuracy: 0.7104 - val_loss: 0.7252 - val_accuracy: 0.8388
Epoch 12/12
469/469 [==============================] - 3s 6ms/step - loss: 0.9112 - accuracy: 0.7304 - val_loss: 0.6630 - val_accuracy: 0.8478
Test loss: 0.6629576683044434
Test accuracy: 0.8478000164031982
[4]:
# this is the code from https://github.com/keras-team/keras/blob/master/examples/mnist_cnn.py
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K

batch_size = 128
num_classes = 10
epochs = 12

# input image dimensions
img_rows, img_cols = 28, 28

# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
x_train shape: (60000, 28, 28, 1)
60000 train samples
10000 test samples
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-2110b63e35a3> in <module>
     42 model.add(Conv2D(32, kernel_size=(3, 3),
     43                  activation='relu',
---> 44                  input_shape=input_shape))
     45 model.add(Conv2D(64, (3, 3), activation='relu'))
     46 model.add(MaxPooling2D(pool_size=(2, 2)))

~/anaconda3/lib/python3.7/site-packages/keras/engine/sequential.py in add(self, layer)
    164                     # and create the node connecting the current layer
    165                     # to the input layer we just created.
--> 166                     layer(x)
    167                     set_inputs = True
    168             else:

~/anaconda3/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py in symbolic_fn_wrapper(*args, **kwargs)
     73         if _SYMBOLIC_SCOPE.value:
     74             with get_graph().as_default():
---> 75                 return func(*args, **kwargs)
     76         else:
     77             return func(*args, **kwargs)

~/anaconda3/lib/python3.7/site-packages/keras/engine/base_layer.py in __call__(self, inputs, **kwargs)
    444                 # Raise exceptions in case the input is not compatible
    445                 # with the input_spec specified in the layer constructor.
--> 446                 self.assert_input_compatibility(inputs)
    447
    448                 # Collect input shapes to build layer.

~/anaconda3/lib/python3.7/site-packages/keras/engine/base_layer.py in assert_input_compatibility(self, inputs)
    308         for x in inputs:
    309             try:
--> 310                 K.is_keras_tensor(x)
    311             except ValueError:
    312                 raise ValueError('Layer ' + self.name + ' was called with '

~/anaconda3/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py in is_keras_tensor(x)
    693     ```
    694     """
--> 695     if not is_tensor(x):
    696         raise ValueError('Unexpectedly found an instance of type `' +
    697                          str(type(x)) + '`. '

~/anaconda3/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py in is_tensor(x)
    701
    702 def is_tensor(x):
--> 703     return isinstance(x, tf_ops._TensorLike) or tf_ops.is_dense_tensor_like(x)
    704
    705

AttributeError: module 'tensorflow.python.framework.ops' has no attribute '_TensorLike'
[ ]:

[ ]:

[ ]:

[2]:
# ...include code from https://github.com/keras-team/keras/blob/master/examples/mnist_cnn.py

import shap
import numpy as np

# select a set of background examples to take an expectation over
background = x_train[np.random.choice(x_train.shape[0], 100, replace=False)]

# explain predictions of the model on three images
e = shap.DeepExplainer(model, background)
# ...or pass tensors directly
# e = shap.DeepExplainer((model.layers[0].input, model.layers[-1].output), background)
shap_values = e.shap_values(x_test[1:5])
WARNING:tensorflow:From /home/slundberg/projects/shap/shap/explainers/_deep/deep_tf.py:235: set_learning_phase (from tensorflow.python.keras.backend) is deprecated and will be removed after 2020-10-11.
Instructions for updating:
Simply pass a True/False value to the `training` argument of the `__call__` method of your layer or model.
Using TensorFlow backend.
keras is no longer supported, please use tf.keras instead.
[3]:
# plot the feature attributions
shap.image_plot(shap_values, -x_test[1:5])
../../../_images/example_notebooks_image_examples_image_classification_Front_Page_DeepExplainer_MNIST_Example_7_0.png
[3]:
# plot the feature attributions
shap.image_plot(shap_values, -x_test[1:5])
../../../_images/example_notebooks_image_examples_image_classification_Front_Page_DeepExplainer_MNIST_Example_8_0.png

The plot above shows the explanations for each class on four predictions. Note that the explanations are ordered for the classes 0-9 going left to right along the rows.