【问题标题】:How to get gradients of weights w.r.t. to a target neuron?如何获得权重梯度 w.r.t.到目标神经元?
【发布时间】:2019-09-25 13:27:06
【问题描述】:

我在网上找到了关于深度学习权重的总损失导数的代码。我试图找到权重相对于单个类而不是所有类的损失的导数。

我使用以下代码来获取输入图像相对于总损失的梯度。如果我将其可视化,它会显示像素对所有预测的重要性。但是,我想计算输入图像相对于特定类(例如“lady_bug”)的导数。这应该显示像素对于预测 lady_bug 的重要性。你知道我该怎么做吗?

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>]

【问题讨论】:

    标签: python keras gradient


    【解决方案1】:

    似乎代码正在使用输入的输出梯度。
    所以,这只是从输出中取出一个切片。

    警告:这考虑了常规模型输出。我不知道您在解码预测和以下列表中在做什么。

    gradients = K.gradients(model.output[:, lady_bug_class], model.input)   
    

    【讨论】:

      猜你喜欢
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 2017-01-26
      • 1970-01-01
      • 2017-12-14
      相关资源
      最近更新 更多