如何使用 keras.backend.gradients() 获取梯度值

Ali*_*arv 4 python gradient neural-network keras tensorflow

我试图获得 Keras 模型输出相对于模型输入 (x)(不是权重)的导数。似乎最简单的方法是使用来自 keras.backend 的“梯度”,它返回梯度张量(https://keras.io/backend/)。我是 tensorflow 的新手,还不适应。我已经得到了梯度张量,并试图为不同的输入值 (x) 获得它的数值。但似乎梯度值与输入 x 无关(这不是预期的),或者我做错了什么。任何帮助或评论将不胜感激。

import keras
import numpy as np
import matplotlib.pyplot as plt
from keras.layers import Dense, Dropout, Activation
from keras.models import Sequential
import keras.backend as K
import tensorflow as tf
%matplotlib inline

n = 100         # sample size
x = np.linspace(0,1,n)    #input
y = 4*(x-0.5)**2          #output
dy = 8*(x-0.5)       #derivative of output wrt the input
model = Sequential()
model.add(Dense(32, input_dim=1, activation='relu'))            # 1d input
model.add(Dense(32, activation='relu'))
model.add(Dense(1))                                             # 1d output

# Minimize mse
model.compile(loss='mse', optimizer='adam', metrics=["accuracy"])
model.fit(x, y, batch_size=10, epochs=1000, verbose=0)

gradients = K.gradients(model.output, model.input)              #Gradient of output wrt the input of the model (Tensor)
print(gradients)

#value of gradient for the first x_test
x_test_1 = np.array([[0.2]])
sess = tf.Session()
sess.run(tf.global_variables_initializer())
evaluated_gradients_1 = sess.run(gradients[0], feed_dict={model.input: 
x_test_1})
print(evaluated_gradients_1)

#value of gradient for the second x_test
x_test_2 = np.array([[0.6]])
evaluated_gradients_2 = sess.run(gradients[0], feed_dict={model.input: x_test_2})
print(evaluated_gradients_2)
Run Code Online (Sandbox Code Playgroud)

我的代码的输出:

[<tf.Tensor 'gradients_1/dense_7/MatMul_grad/MatMul:0' shape=(?, 1) dtype=float32>]
[[-0.21614937]]
[[-0.21614937]]
Run Code Online (Sandbox Code Playgroud)

对于不同的运行,评估的梯度_1 和评估的梯度_2 是不同的,但总是相等的!我预计它们在同一次运行中会有所不同,因为它们适用于不同的输入值 (x)。网络的输出似乎是正确的。这是网络输出图:网络输出与真实值

Ali*_*arv 5

答案如下:

sess = tf.Session()
sess.run(tf.global_variables_initializer())
Run Code Online (Sandbox Code Playgroud)

应替换为:

sess = K.get_session()
Run Code Online (Sandbox Code Playgroud)

前者创建一个新的 tensorflow 会话并初始化所有值,这就是为什么它给出随机值作为梯度函数的输出。后者提取了在 Keras 内部使用的会话,该会话具有训练后值。