我想计算 TensorFlow.js 中输入向量的损失梯度。
这是我尝试过的:
function f(img) {
return tf.metrics.categoricalCrossentropy(model.predict(img), lbl);
// (Typo: the order of arguments should be flipped, but it does not affect the question here)
}
var g = tf.grad(f);
g(img).print();
img
是形状为 [1, 784] 的张量。 lbl
是形状为 [1, 10] 的张量。 model
是一个用 tf.Sequential
训练的普通 MNIST DNN。
对 g(img)
的调用失败并显示堆栈跟踪:
Uncaught TypeError: Cannot read property 'shape' of undefined
at gradFunc (Concat_grad.js:29)
at Object.s.gradient (engine.js:931)
at a (tape.js:158)
at tape.js:136
at engine.js:1038
at engine.js:433
at e.t.scopedRun (engine.js:444)
at e.t.tidy (engine.js:431)
at e.t.gradients (engine.js:1033)
at gradients.js:69
我错过了什么?
最佳答案
我原来的代码片段是正确的;有一个tf.grad
bug在导致此错误的 TensorFlow.js 2.6.0 和 2.5.0 版本中。
代码在 2.4.0 或新版本 2.7.0 中按预期工作。
关于tensorflow - 在tensorflow.js中,如何计算模型输入的梯度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64496947/