Open In App

Tensorflow.js tf.metrics.sparseCategoricalAccuracy() Function

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

The .metrics.sparseCategoricalAccuracy() function is sparse categorical accuracy metric function which uses indices and logits in order to return tf.Tensor object.



Syntax:  

tf.metrics.sparseCategoricalAccuracy(yTrue, yPred) 

Parameters:  



Return Value: It returns the tf.Tensor object.

Example 1:  




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Defining indices and logits
const y = tf.tensor1d([1, 2, 1, 7]);
const z = tf.tensor2d([[1, 1, 9], [0.2, 0, 1], [0.1], [1.8]]);
  
// Calling metrics.sparseCategoricalAccuracy() 
// method
const sparseCategoricalAccuracy = 
    tf.metrics.sparseCategoricalAccuracy(y, z);
  
// Printing output
sparseCategoricalAccuracy.print();

Output:

Tensor
    [0, 1, 1, 0]

Example 2:




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Calling metrics.sparseCategoricalAccuracy()
// method and printing output
tf.metrics.sparseCategoricalAccuracy(
    tf.tensor1d([2, 3, null, 'a']), 
    tf.tensor2d([[0, 0, 0], [0, 0, 1], 
    [2, 2, 2], [6, 7, 8]])
).print();

Output:

Tensor
    [0, 0, 1, 0]

Reference: https://js.tensorflow.org/api/latest/#metrics.sparseCategoricalAccuracy

Article Tags :