如何使用 javascript api 在 keras 模型上调用多维预测

How to call a multidimensional prediction on a keras model with a javascript api

我已经基于keraslstm_text_generation例子训练了一个模型,我想用前端javascript.

对这个模型进行预测

首先我尝试使用 keras.js,但是它的预测函数只需要一维 Float32Array 向量,所以我无法使用它,因为 lstm_text_generation 示例使用多维形状数组 (1, maxlen, len(chars)).

接下来我尝试使用 tensorflow.js, using this tutorial 将我的 keras 模型移植到 model.json 文件。一切似乎都工作正常,直到我执行实际预测时它冻结并给我警告 Orthogonal initializer is being called on a matrix with more than 2000 (65536) elements: Slowness may result.

我注意到在许多 tensorflow.js 示例中,人们将他们的数组转换为 tensor2d,但我这样做了并且它对我的代码的性能没有影响。

对于任何好奇的人,这是我写的 javascript 代码...

async function predict_from_model() {
  const model = await tf.loadModel('https://raw.githubusercontent.com/98mprice/death-grips-lyrics-generator/master/model.json');
  try {
    var seed = "test test test test test test test test"
    var maxlen = 40
    for (var i = 0; i < 1; i++) {
      var x_pred = nj.zeros([1, maxlen, 61]).tolist()
      for (var j = 0; j < seed.length; j++) {
        x_pred[0][j][char_indices[seed.charAt(j)]] = 1
      }
      console.log("about to predict") 
      const preds = model.predict(x_pred) //gets stuck here
      console.log("prediction done")
    }
  } catch (err) {
    // handle error
  }
}

...执行与 lstm_text_generation.py 示例中的 on_epoch_end() 相同的功能。 x_pred 的输出在 python 和 javascript 代码中是相同的,所以我认为问题不在于此。

我认为我需要在 tensorflow.js 中进行一些优化,但我不确定是什么。有谁知道如何解决我上面的任何问题 and/or 任何其他 javascript 库可以满足我的目的?

x_pred 需要是张量,创建具有自定义值的张量的最简单方法是 tf.buffer, which can be initialized with a TypedArray or can be modified using .set() which would be better for you, because most of your values are 0 and buffer are filled with zeros by default. And to create a tensor out of a buffer just use .toTensor();

所以它会像这样:

var x_pred = tf.buffer([1, maxlen, 61]);
for (var j = 0; j < seed.length; j++) {
  x_pred.set(1, 0, j, char_indices[seed.charAt(j)]);
}
console.log("about to predict") 
const preds = model.predict(x_pred.toTensor());
console.log("prediction done")