Skip to content
Related Articles

Related Articles

Improve Article

Tensorflow.js tf.metrics.sparseCategoricalAccuracy() Function

  • Last Updated : 21 Jun, 2021
Geek Week

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

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!




My Personal Notes arrow_drop_up
Recommended Articles
Page :