Saturday, October 18, 2025
HomeLanguagesJavascriptTensorflow.js tf.metrics.categoricalCrossentropy() Function

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:

  • yTrue: It is the truth tensor, and it is of type tf.Tensor.
  • yPred: It is the prediction tensor, and it is 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"
  
// 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:

Javascript




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

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

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS