As @edkeveked answered, but that used the VanillaJS.
For me, I had to do that in NodeJS since I was working on the backend.
I have had a good time doing that let me share that.
First, install the following packages.
npm install @tensorflow/tfjs @tensorflow-models/universal-sentence-encoder
Import the packages
const tf = require("@tensorflow/tfjs")
const sentenceEncoder = require("@tensorflow-models/universal-sentence-encoder")
And load the model (In my case I saved a promise outside the function and awaited it inside the function call. In this way, we will load it when the script loads and when the function is called it will immediately resolve.
const modelPromise = sentenceEncoder.load()
Create the embeddings for both strings and then calculate cosineSimilarity
const calculateSemanticSimilarity = async ({ text_a, text_b }) => {
const model = await modelPromise
const embeddings = (await model.embed([text_a, text_b])).unstack()
return tf.losses.cosineDistance(embeddings[0], embeddings[1], 0).dataSync()[0]
}
module.exports = { calculateSemanticSimilarity }