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
How to use HTML for Data Visualization ?
In this article, we are going to discuss Data Visualization techniques that can be employed to make the communication of data easier and more effective. Data Visualization in HTML involves presenting data in graphical or visual formats using HTML, CSS, and SVG. It enhances data comprehension and ins
2 min read
How to Get Started with ml5.js?
ml5.js is designed to make machine learning accessible to everyone, including artists, educators, and students. Built on top of TensorFlow.js, ml5.js abstracts the complexities of machine learning and offers a simple, high-level API. This enables developers to easily incorporate machine learning mod
4 min read
Visualizing Google Forms Data with Matplotlib
In this article, we will see how can we visualize the data of google forms with the Matplotlib library. Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. It is a plotting library for the Python programming language and its numerical mathem
7 min read
Data visualization With Pygal
Pygal is an open-source Python library designed for creating interactive SVG (Scalar Vector Graphics) charts. It is known for its simplicity and ability to produce high-quality visualizations with minimal code. Pygal is particularly useful for web applications, as it integrates well with frameworks
10 min read
How to use Jinja for Data Visualization
Jinja is a powerful templating engine for rendering text whether it be HTML, LaTeX, or just anything that is just pure text. This article provides an introduction to how to utilize Jinja for Data Visualization. First, it presents the idea and finally provides an example of rendering a simple bar gra
5 min read
Top Free Data Visualization Tools
Data visualization tools refer to software applications that convert data inputs into attractive visual representations such as maps, graphs and charts for analysis. These tools help businesses and individuals to understand complex data sets, identify trends and make informed decisions. In this arti
6 min read
12 Useful Ways to Visualize Your Data (with Examples)
In today's data-driven world, Data visualization is a powerful tool for getting insights and trends that are effectively communicated by businesses, researchers, and individuals alike. The sheer volume of data generated every day makes it increasingly important for ways to be found to make sense of
11 min read
Data Visualization With Altair
Nowadays, Data is an important entity. It should be processed in such a way so that the companies can understand the psychology of the consumers. Data visualization is an important step in processing of data. Altair is a declarative statistical visualization library for Python, built on Vega and Veg
9 min read
How to Create a Neural Network with ml5JS?
Creating a neural network might sound complex, but with ml5.js, it becomes much easier. This JavaScript library is built on top of TensorFlow.js, and it simplifies the process of adding machine learning to your web projects. This article helps to create a basic neural network using ml5.js. In the co
3 min read
Top 15 Data Visualization Frameworks
Data Visualization Frameworks are known as tools and libraries that can assist analysts, data scientists, and decision-makers in transforming raw data into meaningful visuals. Such frameworks provide all sorts of things, starting with a basic chart and graphical representation of data and going up t
11 min read