I am trying to use the Grad-CAM algorithm to get the attention value of 1DResNet-18. I import 15 test samples from 'test_data.npy', and the shape of each test sample (Raman spectrum) of mine is (1, 861). The model 'model_trained.hdf5' was already trained.
I used Keras 2.2.4 and tensorflow 1.12.0
When I set I set the breakpoint at ‘pooled_grads_value, conv_layer_output_value = iterate([X_test_r])’, and begun to debug, I got this error.
PS:
I want use the attention value to plot this picture, this attention value determines the color change in the graph.
__________________________________________________________________________________________________
Traceback (most recent call last):
File "D:\anaconda env\envs\py36\lib\site-packages\tensorflow\python\framework\ops.py", line 3490, in as_graph_element
return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
File "D:\anaconda env\envs\py36\lib\site-packages\tensorflow\python\framework\ops.py", line 3569, in _as_graph_element_locked
raise ValueError("Tensor %s is not an element of this graph." % obj)
ValueError: Tensor Tensor("Mean:0", shape=(512,), dtype=float32) is not an element of this graph.
Process finished with exit code 1
This is my code:
import tensorflow as tf
import keras
import numpy as np
from tensorflow.python.keras.backend import set_session
from tensorflow.python.keras.models import load_model
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
keras.backend.tensorflow_backend.set_session(tf.Session(config=config))
from keras import backend as K
import os
import numpy as np
os.environ["CUDA_VISIBLE_DEVICES"]="0"
w = 0
nb_features = 861
data_test = np.load('./data/test_data.npy')
print('shape of test data is:'data_test.shape)
data_test = data_test[0:1] #get the first test sample
X_test_r = np.zeros((len(data_test), nb_features, 1))
X_test_r[:, :, 0] = data_test[:, :nb_features]
# prediction
session = tf.Session(graph=tf.Graph())
with session.graph.as_default():
K.set_session(session)
model = load_model('./model_trained.hdf5')
model.summary()
y_pre_i = model.predict(X_test_r) #one-hot矩阵
african_elephant_output = model.output[:, 0]
last_conv_layer = model.get_layer('conv1d_20')
grads = K.gradients(african_elephant_output, last_conv_layer.output)[0]
# shape of (512,)
pooled_grads = K.mean(grads, axis=(0, 1))
iterate = K.function(inputs=[model.input],
outputs=[pooled_grads, last_conv_layer.output[0]])
pooled_grads_value, conv_layer_output_value = iterate([X_test_r])
for i in range(512):
conv_layer_output_value[:, :, i] *= pooled_grads_value[i]
heatmap = np.mean(conv_layer_output_value, axis=-1)
import matplotlib.pyplot as plt
heatmap = np.maximum(heatmap, 0) # Relu
heatmap /= np.max(heatmap) # Norm
plt.matshow(heatmap)
plt.show()
