python - 使用 tf.gradienttape 计算多个输入的梯度,但不返回

标签 python tensorflow

预训练的 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/

相关文章:

python - 如何获取Keras模型所有层的输出?

python - 我如何知道哪个预测针对哪个数据?那么,如何评估预测呢?

linux - 如何在 python 中将 '>' 作为参数传递给终端

java - 如何在Java中使用python代码?

python - 如何使用可变长度字符串解码 TFRecord 数据样本?

python - Tensorflow:不支持的可调用

python - OpenMP/Pybind11 : Accessing python object in for loop returns interned string error

python - 更改子类模型表中的列顺序

python - Latex 的 build_pdf 模块中的运行时错误 - python

python - 未能通过 GradientDescentOptimizer 找到零权重