tensorflow - 在tensorflow.js中,如何计算模型输入的梯度?

标签 tensorflow tensorflow.js

我想计算 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/

相关文章:

javascript - 继续获取 : "Attempted import error: ' loadFrozenModel' is not exported from '@tensorflow/tfjs-converter' "

Tensorflow卷积神经网络-使用小数据集进行训练,将随机变化应用于图像

javascript - Tensorflow Js 中多时间序列预测的最佳方法

javascript - 使用 tf.browser.toPixels() 时内存泄漏

tensorflow - 在 python 中保存 Keras/Sklearn 并在 tensorflow.js 中加载保存的模型

python - 如何使用 keras-self-attention 包可视化注意力 LSTM?

tensorflow - CUDA 和 cuDNN 在 Windows 上的安装问题

python - 如何消除棋盘伪影

c++ - tensorflow :转置需要一个大小为 1 的 vector 。但输入(1)是一个大小为 2 的 vector