Open In App

How to Set Up the ml5.js Library?

Last Updated : 30 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

ml5.js library is a machine learning library for JavaScript that simplifies the integration of machine learning models into web applications. It provides pre-trained models and a user-friendly API, making it accessible for both beginners and experienced developers. To set it up, we simply include the ml5.js script in our HTML file and initialize the models we want to use in our JavaScript code.

Steps to Setting Up the ml5.js Library

Setting up ml5.js in our project is simple. Follow the below steps to install and use ml5.js in JavaScript.

Step 1: Create a Project Directory

Open the VSCode terminal and create a new directory for our project. Navigate into the directory using cd command.

mkdir ml5js_project 
cd ml5js_project
OP1
Terminal commands

Step 2: Create an index.html file and script.js

Once we are navigated to the directory. Create index.html and script.js files.

OP2
Project structure

Step 3: Use the CDN Link

Add the necessary CDN link for ml5.js in the <head> section of index.html for easy setup and access to these library without downloading them locally.

<script src="https://unpkg.com/ml5@latest/dist/ml5.min.js"></script>

Example: Classifying Image: In this example, an image classification application is built using ml5.js. The script loads the MobileNet model and allows users to upload an image, which is then classified using the model. The result with the highest confidence is displayed, showing the label and confidence percentage.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Example 1</title>
    <script src=
"https://unpkg.com/ml5@latest/dist/ml5.min.js"></script>
    <style>
        body {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            font-family: Arial, sans-serif;
            text-align: center;
            background-color: #f0f0f0;
        }

        h1 {
            color: green;
            margin-bottom: 20px;
        }

        img {
            max-width: 400px;
            height: auto;
            margin-top: 20px;
        }

        #result {
            margin-top: 20px;
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }

        input[type="file"] {
            margin-top: 20px;
        }
    </style>
</head>

<body>
    <h1>GeeksforGeeks</h1>
    <input type="file" id="file-input" 
           accept="image/*">
    <br>
    <img id="image" src="" alt="Image">
    <p id="result"></p>
    <script src="script.js"></script>
</body>
</html>
JavaScript
let classifier;
let imageElement = document.getElementById('image');
let resultElement = document.getElementById('result');
function setup() {
    classifier = ml5.imageClassifier('MobileNet', modelLoaded);
}
function modelLoaded() {
    console.log('Model Loaded!');
}
document.getElementById('file-input')
        .addEventListener('change', handleFileSelect);
function handleFileSelect(event) {
    let file = event.target.files[0];
    if (file) {
        let reader = new FileReader();
        reader.onload = function (e) {
            imageElement.src = e.target.result;
            imageElement.style.display = 'block';
            imageElement.onload = function () {
                classifyFn();
            };
        };
        reader.readAsDataURL(file);
    }
}
function classifyFn() {
    console.log('Classifying image...');
    classifier.classify(imageElement)
        .then(results => {
            console.log('Classification results:', results);
            let highestConfidenceResult = results.reduce((max, result) =>
                result.confidence > max.confidence ? result : max,
                { label: '', confidence: 0 }
            );
            resultElement.innerText = `Label: ${highestConfidenceResult.label}\nConfidence: 
            ${(highestConfidenceResult.confidence * 100).toFixed(2)}%`;
        })
        .catch(error => {
            console.error('Classification error:', error);
            resultElement.innerText = 'Error classifying image.';
        });
}
setup();

Output:


Next Article

Similar Reads