Build a Machine Learning Model for Image Classification with Node.js and Hugging Face in Just 3 Lines of Code.
RouCodes
Posted on February 14, 2024
Hello dev.Community! š In this post, I'll guide you through the process of image classification using JavaScript with the assistance of Hugging Face AI Models.
First and foremost, let's select a random image online and download it. For example, I came across this picture during a quick Google search. Once we have our chosen image, let's open Visual Studio Code (VSCode) and initiate our Node.js project by executing the following command in the terminal:
After running this command, a package.json file will be generated.
Now, let's get down to business and install our Hugging Face model. If you're not familiar with
Hugging Face
It's a company renowned for its Natural Language Processing (NLP) platform and an extensive open-source community that offers various pre-trained models, including transformers for tasks like text generation, translation, and sentiment analysis.
To install our specific model, Xenova/transformers.js, use the following terminal command:*
Xenova/transformers.js
with this command in terminal:
To install our specific model, Xenova/transformers.js, use the following terminal command:
npm install Xenova/transformers.js --save
Upon installing the model, a dependency entry will be added to the package.json file, as depicted below:
Next, modify the package.json by adding "type": "module" because we want to leverage ES6 features.
Next step we create an index.js file in our project folder , you need to write these lines of code :
Here we imported pipeline from Xenova/transformers.js then initialize a pipe to use with an async function to tell what this pipeline is for also the task we want to accomplish is we want to make an image classification , you can specify also a specific model you want to use but here in this post we just stick with the default one cause it will quicker to download , we declared also a const called result so we can process an image so we need to provide an absolute path for the image,finally we just console.log the result.
Run Node index in terminal :
So as shown in terminal label it tell us that is a lion king and a score of possibiliy with a high percantage 99% but if we want our result to be more accurate add the option topk:6 to the result constant.
here it shows other labels with 0% percantage so defiently it is a lion
š¦!
Posted on February 14, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
February 14, 2024