Skip to content
Related Articles

Related Articles

Tensorflow.js tf.metrics.sparseCategoricalAccuracy() Function

Improve Article
Save Article
  • Last Updated : 21 Jun, 2021
Improve Article
Save Article

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:  

  • yTrue: It is the stated true labels i.e. indices and it can be of type tf.Tensor.
  • yPred: It is the predicted expectancies or logits and it can be of type tf.Tensor.

Return Value: It returns the tf.Tensor object.

Example 1:  

Javascript




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

Javascript




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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!