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

时间:2019-12-24 22:35:55

标签: javascript node.js tensorflow tensorflow.js encoder

我在node中使用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中正确实现编码器?

1 个答案:

答案 0 :(得分:1)

load返回解析为模型的承诺

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

如果您更愿意使用await,则load方法必须包含在封闭的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.
};