Open In App

Tensorflow.js tf.util.assert() Function

Tensorflow.js is an open-source library that is being developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment.

The .util.assert() function is used to assert that the stated expression in the function as a parameter is true. And if it not true then an error is thrown along with the message stated in the method.



Syntax:  

tf.util.assert(expr, msg)

Parameters: This function accepts the following two parameters.



Return Value: It returns void.

Example 1: When the stated expression is true.




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Defining a constant x
const y = 5;
  
// Calling util.assert() method and
// printing output
tf.util.assert(y === 5, (msg) => {});
  
console.log("Successfully Executed, No Error Occurred")
console.log("Condition True")

Output:

Successfully Executed, No Error Occurred
Condition True

Example 2: When the stated expression is false and an error is thrown.




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Defining a constant x and
// all the parameters
const y = 3.6;
var exp = (y == 3.0)
var msg = 'value of y is not 3.6';
  
// Calling util.assert() method and
// printing output
var z = tf.util.assert(exp, msg);
console.log("true");

Output:

throw new Error(typeof msg === 'string' ? msg : msg());
Error: value of y is not 3.6

Reference: https://js.tensorflow.org/api/latest/#util.assert


Article Tags :