Open In App

How to Visualize Data with ml5.js?

Last Updated : 13 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The ml5.js is a Machine Learning Library for JavaScript that simplifies the integration of machine learning models into web applications. It provides pre-trained models and easy-to-use functions for tasks like image classification, object detection, and more. By using ml5.js, developers can visualize machine learning data in various ways, including through charts and graphs, making it easier to interpret and present model results interactively.

Below are the possible approaches to Visualize Data with ml5.js:

Static Data Visualization with Predefined Array

In this approach, we are using ml5.js with a predefined array of classification results to visualize data as a bar chart. The setup function initializes the canvas, and the drawChart function renders bars proportional to the confidence values of each classification, with labels displayed above the bars.

Example: In the below example, we are visualizing classification results using a bar chart.

HTML
<!DOCTYPE html>

<head>
    <title>Example 1</title>
    <script src=
 "https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js">
   </script>
    <script src=
 "https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/addons/p5.dom.min.js">
   </script>
    <script src=
 "https://unpkg.com/ml5@latest/dist/ml5.min.js">
  </script>
    <style>
        h1 {
            color: green;
            text-align: center;
        }

        h3 {
            text-align: center;
        }

        #chart {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 400px;
        }
    </style>
</head>

<body>
    <h1>GeeksforGeeks</h1>
    <h3>Classification Results Bar Chart</h3>
    <div id="chart"></div>
    <script src="script.js"></script>
</body>

</html>
JavaScript
let classifier;
let results = [
  {label: "Cat", confidence: 0.9},
  {label: "Dog", confidence: 0.8},
  {label: "Bird", confidence: 0.7}
];

function setup() {
  createCanvas(600, 400).parent('chart');
  drawChart();
}

function drawChart() {
  background(255);
  let barWidth = width / results.length;

  for (let i = 0; i < results.length; i++) {
    let barHeight = results[i].confidence * height;
    fill(0, 0, 255);
    rect(i * barWidth, height - barHeight, barWidth - 10, barHeight);
    fill(0);
    textSize(16);
    textAlign(CENTER, CENTER);
    text(results[i].label, i * barWidth + barWidth / 2, height - barHeight - 20);
  }
}

Output:

OP1
Output

Dynamic Image Classification and Visualization

In this approach, we dynamically visualize the classification results of an uploaded image using ml5.js and Chart.js. The image classifier is applied to the selected image, and the results are displayed both as text and as a bar chart, where the chart shows the confidence levels of the detected labels.

Example: In the below example, we are using ML5.js and Chart.js to create an image classification application.

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width,
                   initial-scale=1.0">
    <title>Visualize Data</title>
    <script src=
"https://unpkg.com/ml5@latest/dist/ml5.min.js"></script>
    <script src=
"https://cdn.jsdelivr.net/npm/chart.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;
            font-size: 2em;
        }

        .container {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            width: 80%;
            max-width: 1200px;
        }

        .left,
        .right {
            flex: 1;
            margin: 10px;
        }

        .left {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        img {
            max-width: 300px;
            height: auto;
            margin-top: 20px;
            border: 1px solid #ddd;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

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

        input[type="file"] {
            margin-top: 20px;
        }

        #resultChart {
            max-width: 600px;
            max-height: 400px;
            width: 100%;
        }
    </style>
</head>

<body>
    <h1>GeeksforGeeks</h1>
    <div class="container">
        <div class="left">
            <input type="file" id="file-input" accept="image/*">
            <img id="image" src="" alt="Image" style="display:none;">
            <p id="result"></p>
        </div>
        <div class="right">
            <canvas id="resultChart"></canvas>
        </div>
    </div>
    <script src="script.js"></script>
</body>

</html>
JavaScript
let classifier;
let imageElement = document.getElementById('image');
let resultElement = document.getElementById('result');
let chart;

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 () {
                classifyImage();
            };
        };
        reader.readAsDataURL(file);
    }
}

function classifyImage() {
    console.log('Classifying image...');
    classifier.classify(imageElement)
        .then(results => {
            console.log('Classification results:', results);
            if (results && results.length > 0) {
                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)}%`;
                displayResults(results);
            } else {
                resultElement.innerText = 'No classification results.';
            }
        })
        .catch(error => {
            console.error('Classification error:', error);
            resultElement.innerText = 'Error classifying image.';
        });
}

function displayResults(results) {
    if (chart) {
        chart.destroy();
    }

    const labels = results.map(result => result.label);
    const data = results.map(result => result.confidence * 100);

    const ctx = document.getElementById('resultChart').getContext('2d');
    chart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: 'Confidence (%)',
                data: data,
                backgroundColor: 'rgba(75, 192, 192, 0.2)',
                borderColor: 'rgba(75, 192, 192, 1)',
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: 'Confidence (%)',
                        font: {
                            size: 16
                        }
                    },
                    ticks: {
                        font: {
                            size: 14
                        }
                    }
                },
                x: {
                    title: {
                        display: true,
                        text: 'Labels',
                        font: {
                            size: 16
                        }
                    },
                    ticks: {
                        font: {
                            size: 14
                        }
                    }
                }
            },
            plugins: {
                legend: {
                    labels: {
                        font: {
                            size: 16
                        }
                    }
                }
            }
        }
    });
}

setup();

Output:

2
Output

Next Article

Similar Reads