预训练的 DNN 模型需要两个输入,我想计算两个输入的输出梯度
ta = tf.cast(input1,tf.float32) #ta in 2 dimension, tb in 3 dimension
tb = tf.cast(input2,tf.float32)
inp_tensor_list = [ta,tb]
with tf.GradientTape() as tape:
pred = model(inp_tensor_list) #pred return correct value here
grad = tape.gradient(pred, inp_tensor_list)
毕业[无,无]
如何解决?谢谢
已解决的更新
使用 tf.Variable 代替 tf.cast
最佳答案
您需要将变量传递给 tape.gradient
调用,如下所示
grad = Tape.gradient(pred, model.trainable_variables)
编辑:
如果你想计算张量的梯度,你需要明确要求磁带跟踪所述张量上的操作。
ta = tf.cast(input1,tf.float32) #ta in 2 dimension, tb in 3 dimension
tb = tf.cast(input2,tf.float32)
inp_tensor_list = [ta,tb]
with tf.GradientTape() as tape:
tape.watch(ta)
tape.watch(tb)
pred = model(inp_tensor_list) #pred return correct value here
grad = tape.gradient(pred, inp_tensor_list)
关于python - 使用 tf.gradienttape 计算多个输入的梯度,但不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68434740/