Open In App
Related Articles

Tensorflow.js tf.metrics.sparseCategoricalAccuracy() Function

Improve Article
Improve
Save Article
Save
Like Article
Like

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

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks 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!

Last Updated : 21 Jun, 2021
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials