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

How can I create a timed slideshow of images?

Is there a way to make a series of images slide automatically after closing or stopping a video? To see the specific website in question, click here: Upon visiting the site, a video pops up. How can I program the image slides to transition every 7 secon ...

Dramatist experiencing the error message "npm ERR! unable to identify executable to run"

Recently delved into the world of Playwright and decided to run the pre-installed tests. However, I'm facing failures that I can't seem to figure out. $ npx playwright tests ...

Issues encountered while attempting to verify password confirmation within a React form using Joi

I have been struggling to implement a schema for validating a 'confirm password' form field. While researching how to use Joi for validation, I noticed that many people recommend using the Joi.any() function. However, every time I attempt to use ...

Examine the state of each element within a div separately

I have a div containing elements with the class 'container'. Each of these container elements has multiple child divs with the class 'children'. I am looking to perform an action on the child divs when they become visible in the viewpor ...

Error: EACCES - Access Denied on Windows operating system

Up until this evening, everything was working fine. However, after uninstalling VSCode and reinstalling it, I encountered an issue when trying to run npm run app. I have tried running VS Code and the command prompt as an administrator, but with no luck. Th ...

JavaScript event in Chrome extension triggers a browser notification and allows for modification using a specific method

I am currently developing a Chrome extension that is designed to take specific actions when system notifications appear, with the main goal being to close them automatically. One example of such a notification is the "Restore pages?" prompt: https://i.sta ...

Spontaneous visual paired with text upon refreshing

I am new to Java script and I am working on creating a web page that displays two random numbers every time it is refreshed. Depending on these numbers, specific text should be shown. These numbers are represented by images ranging from 0 to 5. Currently ...

The URL switches back and forth from "localhost:8100" to "localhost:8100/some-route" while displaying a blank white screen

After working on my ionic app without any issues, I restarted my computer only to find that when I tried to run the project again, I was met with a blank white screen on both the browser and device. Even when I reverted back to an earlier branch, the URL c ...

Transferring files and folders to the Electron Distribution directory

In short: I'm looking for a way to automate the process of copying files/directories from my src folder to dist/resources when packaging using Electron-packager. This need arose because I have JSON files in folders that need to be transferred to a sp ...

Tips for integrating Tailwind CSS into Create React App using React

I recently started using tailwindcss with my react app. I tried to follow the guide from tailwindcss but encountered various issues and bugs along the way. If anyone has advice on how to successfully start a project using tailwind and react, I would apprec ...

Is it a graphics card malfunction or a coding complication? Delving into THREE.JS WebGL

Recently, I created a cool scene using three.js that was running perfectly until today. Strangely, without any changes to the code, I started encountering an error in every major browser - Chrome, Firefox, and Edge. The error message I am seeing is: THREE. ...

Encountering an issue such as receiving the 'Error eacces mkdir' message when trying to execute the 'npm install -g create-react-app' command

Encountered an error while trying to install reactjs on Ubuntu using the npm install -g create-react-app command. The error message is as follows. Can someone please assist me in resolving this issue? This is the error I am receiving: npm ERR! Error: EAC ...

If the item already exists within the array, I aim to replace the existing object with the new one

I am faced with a situation where I have an array of objects, and when a user selects an option, it adds a new object to the array. My goal is to write a code that can check if this new object's key already exists in one of the objects within the arra ...

Hidden button trigger is malfunctioning

I am attempting to activate a hidden button, but the event does not seem to be triggering. Here is the code snippet: <div class="dyn-inp-group"> <div class="dyn-inps"> <div class="form-group form-group-options col-xs-12 dyn-inp" ...

How come the function is being triggered by my onclick button as soon as the page loads?

Currently, I am experiencing a challenge in my NodeJS project with Express. The issue lies with my EJS client side file when it comes to handling button click events. In my EJS file, I have imported a function from a JS file and can invoke it using <% ...

Having difficulty with sending an AJAX GET request to connect to mongodb

I've been facing a challenging task of displaying data from a mongodb collection on the browser using nodejs and express. Here's the client-side call: document.onload= $(function (e) { var i = 0; $.ajax({ type: "GET", url: "http://localh ...

The "smiley" character added to the information during an Ajax call

Encountering an unusual issue. A colon (:) character is being appended to the JSON data sent to the server via AJAX request. https://example.com/image1.png The colon character seems to appear after sending the JSON, but it does not show up when inspectin ...

Bootstrap tab content getting shifted downwards

Having an issue with the Tab plugin in Bootstrap on a particular page. The tab body is being pushed down 400px below the actual tabs. This behavior is only occurring on this specific page, while most other pages using the same plugin are functioning fine. ...

Combining two arrays by finding common elements

Currently, I am working on a project where I retrieve data from the server, and each piece of data has to adhere to a specific format: const DATA = [ { title: {title: 'Main dishes'}, data: [ {_id: 1, type: 'Pizza'}, ...

Creating a private variable to perform a select_sum query

I have defined private variables in my CodeIgniter code like this: private $table = 'phone'; private $column_order = array(null, 'name', 'price'); private $type = array('type'); private $battery_consumption = array ...