2

I'm using tensorflow js in node and trying to encode my inputs.

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

These are imports, the suggested import statement (ES6) isn't permitted for me in my node environment? Though they seem to work fine here.

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.
};

This code produces an error that model.embed is not a function. Why? How do I properly implement an encoder in node.js?

1 Answer 1

3

load returns a promise that resolve to the model

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

If you would rather use await, the load method needs to be in an enclosing async function

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.
};
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, I'm shocked I didn't realize this. Model was undefined because USE hadn't finished loading yet. I guess im still not used to asynchronous programming. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.