Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptTensorflow.js tf.confusionMatrix() Function

Tensorflow.js tf.confusionMatrix() Function

Tensorflow.js is an open-source library that is developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment.

The .confusionMatrix() function is used to calculate the confusion matrix from the stated true labels coupled with predicted labels.

Syntax:

tf.confusionMatrix(labels, predictions, numClasses)

Parameters: 

  • labels: It is the stated target labels that are supposed to be a zero based integers in favor of the classes. It has shape [numExamples]. Where, numExamples is the measure of incorporated instances. It can be of type tf.Tensor1D, TypedArray, or an array.
  • predictions: It is the stated predicted classes that are supposed to be a zero based integers in favor of the classes. It should have shape equivalent to the stated labels. It can be of type tf.Tensor1D, TypedArray, or an array.
  • numClasses: It is the number of total classes of type integer. Moreover, its measure should be greater than the greatest element in the stated labels as well as predictions. It is of type number.

Return Value: It returns tf.Tensor2D object.

Example 1:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Defining predictions, labels and 
// numClasses
const lab = tf.tensor1d([3, 4, 1, 0, 1], 'int32');
const pred = tf.tensor1d([1, 3, 0, 4, 1], 'int32');
const num_Cls = 2;
  
// Calling tf.confusionMatrix() method
const output = tf.math.confusionMatrix(lab, pred, num_Cls);
  
// Printing output
output.print();


Output:

Tensor
    [[0, 0],
     [1, 1]]

Example 2:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Calling tf.confusionMatrix() method
const res = tf.math.confusionMatrix(
    tf.tensor1d([3.3, 4.5, null, 'a', 'b']), 
    tf.tensor1d([-2, 5.3, -0.1, 4.3, 12.5]), 4
);
  
// Printing output
res.print();


Output:

Tensor
    [[1, 0, 0, 0],
     [0, 0, 0, 0],
     [0, 0, 0, 0],
     [0, 0, 0, 0]]

Reference: https://js.tensorflow.org/api/latest/#confusionMatrix

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments