在 Node.js 中使用 Tensorflows 通用句子编码器?

Using Tensorflows Universal Sentence Encoder in Node.js?

我在节点中使用 tensorflow js 并尝试对我的输入进行编码。

const tf = require('@tensorflow/tfjs-node');
const argparse = require('argparse');
const use = require('@tensorflow-models/universal-sentence-encoder');

这些是导入,在我的节点环境中不允许使用建议的导入语句 (ES6)?虽然他们在这里似乎工作得很好。

const encodeData = (tasks) => {
  const sentences = tasks.map(t => t.input);
  let model = use.load();
  let embeddings = model.embed(sentences);
  console.log(embeddings.shape);
  return embeddings;  // `embeddings` is a 2D tensor consisting of the 512-dimensional embeddings for each sentence.
};

此代码产生一个错误,指出 model.embed 不是一个函数。为什么?如何在 node.js 中正确实施编码器?

load returns 解决模型的承诺

use.load().then(model => {
  // use the model here
  let embeddings = model.embed(sentences);
   console.log(embeddings.shape);
})

如果您更愿意使用 awaitload 方法需要在封闭的 async 函数中

const encodeData = async (tasks) => {
  const sentences = tasks.map(t => t.input);
  let model = await use.load();
  let embeddings = model.embed(sentences);
  console.log(embeddings.shape);
  return embeddings;  // `embeddings` is a 2D tensor consisting of the 512-dimensional embeddings for each sentence.
};