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

时间:2019-12-02 19:07:06

标签: python-3.x tensorflow neural-network tensorflow2.0

我有一个训练有素的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 如何用于计算输出相对于输入的梯度?

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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

答案 2 :(得分:0)

在上述情况下,我们应该使用 tape.watch()

for (x, y) in test_dataset:
    with tf.GradientTape() as tape:
        tape.watch(x)

        pred = model(x)

grads = tape.gradient(pred, x)

但是 grads 只会有输入的 grads

下面的方法更好,你可以用model来预测预测结果并计算loss,然后用loss计算所有可训练变量的grads

with tf.GradientTape() as tape:
    predictions = model(x, training=True)
    loss = loss_function(y, predictions)
grads = tape.gradient(loss, model.trainable_variables)
相关问题