Having trouble accessing the loadTokenizer function in Tensorflow JS

As a beginner with Tensorflow.js concepts, I recently attempted to tokenize a sentence using the Universal Sentence Encoder in Javascript. You can explore more about it on Github Reference

$ npm install @tensorflow/tfjs @tensorflow-models/universal-sentence-encoder

After running this command, a package-lock.json file was generated which I placed alongside my index.html file within the same directory structure shown below.

/*
  Folder
    |_index.html
    |_package-lock.json
    |_index.js
    |_index.css
*/

Within index.html:

<head>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/universal-sentence-encoder"></script>   
  <script src="index.js" defer></script> 
</head>

Contents of index.js:

function tokenizePad(text){
    text = use.loadTokenizer().then(tokenizer => {
        tokenizer.encode(text); 
    });
    return text;
}

text = "I enjoy my holiday very much."
var tokenized = tokenizePad(text); //error

The console displayed an error message as follows:

Uncaught TypeError: use.loadTokenizer is not a function

Is there a solution to this issue? Are there alternative methods to achieve the desired outcome of converting the string into an array of encoded values like [341, 4125, 8, 140, 31, 19, 54, ......] mentioned in the Github Reference link?

Answer №1

I faced a similar challenge and came up with the solution below:

import use from 'module';

use.load().then(useObj => {
    model = useObj.model;
    tokenizer = useObj.tokenizer;

    text = "I absolutely love going on vacation."
    var tokenized = tokenizer.encode(text); 

    console.log(tokenized); //[7933, 2222, 0, 109, 7933, 2222, 0, 154, 2174, 48, 7933, 2222, 0, 1272, 7933, 2222, 0, 645, 336, 944, 7933, 2222, 0, 5568, 7933, 2222, 0, 47, 1788, 6]
});

The approach above focuses on character-level encoding. If you discover a method for word-based encoding, please share that with me.

Answer №2

This code snippet showcases a more sophisticated and refined approach. Begin by importing it in the following manner:

import * as USE from '@tensorflow-models/universal-sentence-encoder';

Then proceed to utilize it with USE:

// Load the model.
USE.load().then(model => {
  // Embed an array of sentences.
  const sentences = [
    'Greetings.',
    'How do you do?'
  ];
  model.embed(sentences).then(embeddings => {
    // The variable `embeddings` is a 2D tensor containing 512-dimensional embeddings for each sentence.
    // Therefore, in this scenario, `embeddings` has dimensions [2, 512].
    embeddings.print(true /* verbose */);
  });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What should we do to resolve the uncommon use of the 'this' es-lint error? Which rule should we disable?

Recently, I encountered an issue with my Nuxt setup that is configured with el-lint and prettier. Every time I try to use 'this' within my template, it throws up an error unexpectedly. 6:15 error Unexpected usage of 'this' vue/this ...

What is the best way to keep calling an AJAX function until it receives a response from a previous AJAX call

I am looking to continuously call my ajax function until the previous ajax call receives a response. Currently, the page is loading every second and triggering the ajax function, but I want it to keep calling the ajax function until the previous one has c ...

The IIS URL rewrite is causing issues with the rewriting of CSS and JS files

Struggling with my URL rewrites - every time I set up a rewrite for a page, it ends up affecting the CSS and JS files linked within the webpage, resulting in them not displaying properly. In an attempt to fix this issue, I tried using fully qualified path ...

The integration between Javascript, PHP, and SQL Server does not display the retrieved data

I am a beginner in PHP and have limited knowledge of Javascript. I am attempting to create a chronometer where the time limit is retrieved from a SQL SERVER database. However, when I assign the value obtained in PHP to a Javascript variable, it returns -1. ...

JavaScript For Each loops are really starting to frustrate me

My issue seems to be straightforward. I am attempting to update a list of objects called localData with another list of objects that I received after making an AJAX request (referred to as data). The process involves using two loops, however, when I atte ...

How can I utilize the "remark" tool to handle Markdown files with URLs that don't adhere to Markdown formatting? Are there any supplemental plugins available for this

My markdown file has frontmatter and sometimes includes inline URLs that are not properly formatted with markdown syntax. I'm looking for a way to handle these non-markdown URLs within the markdown file - possibly by parsing them into HTML URLs using ...

A JSON request is being processed within a while loop

Attempting to complete what I initially thought was a simple task has led me to believe that I may have oversimplified the process or made a mistake in my loop. My objective is to browse through a series of links containing JSON objects in order to identif ...

Interactive JQuery calendar

Can anybody assist me with this issue? I am seeing question marks in the graphic and I'm not sure why. I remember encountering these symbols before and I believe it has something to do with charset. Currently, I am using: <meta http-equiv="Content ...

Encountering a SyntaxError while implementing lightweight-charts in NextJS

I'm encountering an issue while trying to integrate the lightweight-charts package into my nextjs project. When attempting to utilize the createChart function, I am receiving a syntax error in my Node.js console. ...\lightweight-charts\dist& ...

Having difficulty integrating plugins like Lighthouse into my Cypress project

I need assistance with integrating the cypress automation plugin into my project. I made changes to my index.js file in the plugin folder, but now I am receiving this error: cy.lighthouse() is not a function Here is my index.js file content: const { light ...

I have successfully implemented an onChange function with its corresponding set of parameters. However, I now desire to extend its functionality by incorporating

I have an onchange function that triggers when the "pending" option is selected in a select dropdown menu. This function adds a predefined value to an input field. However, I also want this functionality to apply when the page loads. Currently, the "pendin ...

It appears that the Facebook share feature is not picking up any meta OG tags

There seems to be an issue with my Facebook share functionality as it's not reading any of the meta tags. It is indicating that the required properties such as og:url, og:type, og:title, og:image, og:description, and fb:app_id are missing. <script ...

The AngularJS ngModel directive encounters issues when used within a ui-bootstrap tabset

Check out the code snippet below to see the issue at hand: <!DOCTYPE html> <html ng-app="plunker"> <head> <title>AngularJS Plunker</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/cs ...

Accessing loop variables in Render and passing them into componentDidMount() in ReactJS to include as a query parameter in an API call

Within the render function, I am using a loop to rotate an array of coordinates in order to position markers on a map. {coords.map(({ lat, lng }, index) => (code goes here and so on))} I intend to replace query parameters with the variable generated f ...

Guide on implementing jQuery Validation plugin with server-side validation at the form level

Does anyone have a suggestion for how to handle server-side validation errors that occur after passing the initial client-side validation on a form? $("#contact_form").validate({ submitHandler: function(form) { $.ajax({ type: 'POST', ...

Maxlength and Minlength attributes are not considered when using input type=“number”

Why is the maxlength attribute not functioning properly for this input element? <input type="number" maxlength="5" maxlength="10" /> ...

Is it considered best practice to call the same function within itself in a function?

function takeANumber() { let startHealth = parseInt(prompt("Please enter a positive number:")); // I am recursively calling the same function within an if block to ensure that the input is a valid number greater than zero. Is this considered good practic ...

What is the best way to link a newly created contact to the current user in Mongoose?

I'm faced with the challenge of creating a contact that is specifically added to the current user's contact array. Currently, my controller only creates a generic contact and doesn't cater to the individual user. Controller: function cont ...

When I open Firefox, all I see is a blank page with only the h2 heading displayed

I am trying to print the text "I can print" on a page, but only the title shows up and the rest of the page is blank. What mistake might I be making? <!DOCTYPE html> <html> <head> <title>Object exercise 4</title> </head& ...

Sweetalert seems to have hit a roadblock and is not functioning properly. An error has been detected in its TS file

Currently, I am responsible for maintaining an application that utilizes Angular 7.0.7 and Node 10.20.1. Everything was running smoothly until yesterday when my PC unexpectedly restarted. Upon trying to run ng serve, I encountered the following error: E ...