I'm following the text classification with movie reviews TensorFlow tutorial, and wanted to extend the project by looking, for a certain input, which words influenced the classification the most.
I understand this is called a saliency map, but I'm having trouble calculating it. I believe that I need to calculate the gradients of the output with respect to the input. I tried to implement code similar to the code in this answer to no avail. A confounding issue is that the model uses an embedding layer, which doesn't propagate the gradient, so I think one needs to calculate the gradients with the input being the output of the embedding layer.
It's probably wrong for all sorts of reasons, but this is the closest I've gotten with the Python code:
# Create the saliency function input_tensors = [model.layers.input, keras.backend.learning_phase()] model_input = model.layers.input model_output = model.output gradients = model.optimizer.get_gradients(model_output, model_input) compute_gradients = keras.backend.function(inputs=input_tensors, outputs=gradients) # Word encoding idx = 0 # Calculate the saliency for the first training example embeddings = model.layers.get_weights() embedded_training_data = embeddings[train_data[idx]] matrix = compute_gradients([embedded_training_data.reshape(sum([(1,), embedded_training_data.shape], ())), train_labels[idx]])
But the final matrix is the same row repeated and I'm not sure how to interpret it. Any help would be greatly appreciated. Thankfully, as this is extending a tutorial, there is a complete working example of the code!