How to Visualize Data with ml5.js?
Last Updated :
13 Aug, 2024
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:
OutputDynamic 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:
Output
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read