Open In App

Tensorflow.js tf.metrics.categoricalCrossentropy() Function

Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. It also helps the developers to develop ML models in JavaScript language and can use ML directly in the browser or in Node.js.

The tf.metrics.categoricalCrossentropy() function categorically finds the categorical crossentropy between a target and an output tensor.



Syntax:

tf.metrics.categoricalCrossentropy(yTrue, yPred)

Parameters: This function accepts the following two parameters:



Return Value: It returns the tf.Tensor object.

Example 1:




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Initialising first 2d tensor.
let geek1 = tf.tensor2d([[2, 4], [1, 3]]);
  
// Initialising second 2d tensor.
let geek2 = tf.tensor2d([11, 22, 33, 44], [2, 2]);
  
// Using .categoricalCrossentropy() function
// to find categorical accuracy metric.
let result = tf.metrics.categoricalCrossentropy(geek1, geek2);
  
// Printing the result.
result.print();

Output:

Tensor
    [3.8190854, 2.526145]

Example 2:




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Using .categoricalCrossentropy() function
// to find categorical accuracy metric
tf.metrics.categoricalCrossentropy(
  tf.tensor1d([1, 2]), 
   tf.tensor2d([50], [1, 1]))
      .print();

Output:

Tensor
    [4e-7]

Reference: https://js.tensorflow.org/api/3.6.0/#metrics.categoricalCrossentropy

Article Tags :