我想在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。
对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
我遗漏了什么?
发布于 2020-10-27 23:27:23
我的原始代码片段是正确的;在2.6.0和2.5.0版本的tf.grad
错误中有一个导致此错误的TensorFlow.js。
代码按照2.4.0或新版本2.7.0的要求工作。
发布于 2020-10-26 00:23:43
通过将model.predict
移除在f
范围之外,tf.grad
将工作。
function f(img) {
return tf.metrics.categoricalCrossentropy(img, lbl);
}
var g = tf.grad(f);
const output = model.predict(img);
g(output).print();
从2.7 +
版本中修复的顺序模型似乎有错误。
https://stackoverflow.com/questions/64496947
复制