Open In App

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: 



Return Value: It returns tf.Tensor2D object.

Example 1:




// 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:




// 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


Article Tags :