我如何计算在TensorFlow的急切执行模式下的梯度w.r.t.a是不可变的?

2024-04-26 21:10:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图计算我的模型相对于其输入的损失的梯度,以便创建一个对抗性的例子。由于模型的输入是不可训练的,我需要计算相对于张量的梯度,而不是变量。但是,我发现如果张量不是可训练变量,TensorFlow的GradientTape返回{}梯度:

import numpy as np
import tensorflow as tf

tf.enable_eager_execution()

a = tf.convert_to_tensor(np.array([1., 2., 3.]), dtype=tf.float32)
b = tf.constant([1., 2., 3.])
c = tf.Variable([1., 2., 3.], trainable=False)
d = tf.Variable([1., 2., 3.], trainable=True)

with tf.GradientTape() as tape:
    result = a + b + c + d

grads = tape.gradient(result, [a, b, c, d])

print(grads)打印:

^{pr2}$

我浏览了张量流的Eager Execution tutorialEager Execution guide,但找不到计算梯度w.r.t.a张量的解。在


Tags: 模型importtfasnpresultvariable梯度
1条回答
网友
1楼 · 发布于 2024-04-26 21:10:08

^{}文档揭示了一个简单的解决方案:

Trainable variables (created by tf.Variable or tf.get_variable, where trainable=True is default in both cases) are automatically watched. Tensors can be manually watched by invoking the watch method on this context manager.

在这种情况下

with tf.GradientTape() as tape:
    tape.watch(a)
    tape.watch(b)
    tape.watch(c)
    result = a + b + c + d

grads = tape.gradient(result, [a, b, c, d])

将导致print(grads)

^{pr2}$

相关问题 更多 >