如何在Tensorflow 2.0中计算输出wrt输入的梯度

问题描述 投票:1回答:2

我有一个训练有素的Tensorflow 2.0模型(来自tf.keras.Sequential()),它采用26列(X)的输入层,并产生1列(Y)的输出层。

在TF 1.x中,我可以使用以下方法计算输出相对于输入的的梯度:

model = load_model('mymodel.h5')
sess = K.get_session()
grad_func = tf.gradients(model.output, model.input)
gradients = sess.run(grad_func, feed_dict={model.input: X})[0]

在TF2中,当我尝试运行tf.gradients()时,出现错误:

RuntimeError:启用急切执行时不支持tf.gradients。请改用tf.GradientTape。

在问题In TensorFlow 2.0 with eager-execution, how to compute the gradients of a network output wrt a specific layer?中,我们看到了有关如何计算相对于中间层的渐变的答案,但我看不到如何将其应用于相对于输入的渐变。在tf.GradientTape的Tensorflow help上,有一些示例为简单函数(而非神经网络)计算梯度。

如何使用tf.GradientTape来计算输出相对于输入的梯度?

python-3.x tensorflow neural-network tensorflow2.0
2个回答
1
投票

这应该在TF2中有效:

inp = tf.Variable(np.random.normal(size=(25, 120)), dtype=tf.float32)

with tf.GradientTape() as tape:
    preds = model(inp)

grads = tape.gradient(preds, inp)

基本上,您可以使用与TF1相同的方法,但是使用GradientTape


1
投票

我希望这是您要寻找的。这将给出输出w.r.t.的梯度。输入。

# Whatever the input you like goes in as the initial_value
x = tf.Variable(np.random.normal(size=(25, 120)), dtype=tf.float32)
y_true = np.random.choice([0,1], size=(25,10))

print(model.output)
print(model.predict(x))
with tf.GradientTape() as tape:
  pred = model.predict(x)

grads = tape.gradients(pred, x)
© www.soinside.com 2019 - 2024. All rights reserved.