Python 如何获得目标神经元的权重w.r.t.梯度?
我在网上找到了代码,可以得到关于深度学习权重的总损失的导数。我试图找到权重对单个类而不是所有类的损失的导数 我使用下面的代码来获得输入图像相对于总损失的梯度。如果我将其可视化,它将显示像素对于所有预测的重要性。但是,我想计算输入图像相对于特定类(例如“lady_bug”)的导数。这应该表明像素对于预测lady_bug的重要性。你知道我怎么做吗Python 如何获得目标神经元的权重w.r.t.梯度?,python,keras,gradient,Python,Keras,Gradient,我在网上找到了代码,可以得到关于深度学习权重的总损失的导数。我试图找到权重对单个类而不是所有类的损失的导数 我使用下面的代码来获得输入图像相对于总损失的梯度。如果我将其可视化,它将显示像素对于所有预测的重要性。但是,我想计算输入图像相对于特定类(例如“lady_bug”)的导数。这应该表明像素对于预测lady_bug的重要性。你知道我怎么做吗 from keras.applications.vgg19 import VGG19 import numpy as np import cv2 from
from keras.applications.vgg19 import VGG19
import numpy as np
import cv2
from keras import backend as K
import matplotlib.pyplot as plt
from keras.applications.inception_v3 import decode_predictions
def get_model():
model = VGG19(include_top=True, weights='imagenet')
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
def predict(model, images):
numeric_prediction = model.predict(images)
categorical_prediction = decode_predictions(numeric_prediction, top=1)
return [(x[0][1], x[0][2]) for x in categorical_prediction]
def get_test_image():
# Image
image_path = "lady_bug.jpg"
image = cv2.imread(image_path)
my_image = cv2.resize(image, (224,224))
my_image = np.expand_dims(my_image, axis=0)
return my_image
def visualize_sample(sample, file_path):
plt.figure()
plt.imshow(sample)
plt.savefig(file_path, bbox_inches='tight')
def test_input_gradient():
images = get_test_image()
model = get_model()
prediction = predict(model, images)
print(prediction)
gradients = K.gradients(model.output, model.input) #Gradient of output wrt the input of the model (Tensor)
print(gradients)
sess = K.get_session()
evaluated_gradients = sess.run(gradients[0], feed_dict={model.input:
images})
visualize_sample((evaluated_gradients[0]*(10**9.5)).clip(0,255), "test.png")
if __name__ == "__main__":
test_input_gradient()
输出:
[('ladybug', 0.53532666)]
[<tf.Tensor 'gradients/block1_conv1/convolution_grad/Conv2DBackpropInput:0' shape=(?, 224, 224, 3) dtype=float32>]
[('ladybug',0.53532666)]
[]
代码似乎将输出的梯度与输入的梯度相比较。所以,这只是从输出中获取一个片段 警告:这将考虑常规模型输出。我不知道你在解码预测和下面的列表中做了什么
代码似乎将输出的梯度与输入的梯度相比较。
所以,这只是从输出中获取一个片段 警告:这将考虑常规模型输出。我不知道你在解码预测和下面的列表中做了什么
gradients = K.gradients(model.output[:, lady_bug_class], model.input)