Tensorflow.js tf.valueAndGrads() Function

Tensorflow.js is an open-source library that is developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment.
The .valueAndGrads() function is equivalent to tf.grads() method, but it also returns the measure of f(). It is effective at which time f() returns an approximative that you need to demonstrate.
Note: The output here is an affluent object along with the below features:
- grads: It is the gradients of f() with reference to every input i.e. the output of grads() method.
- value: It is the value reverted through f(x).
Syntax:
tf.valueAndGrads(f)
Parameters:
- f: It is the specified function f(x) for which the gradient is to be computed. It is of type (…args: tf.Tensor[]) => tf.Tensor.
Return Value: It returns grads and value i.e. ( args: tf.Tensor[], dy?: tf.Tensor) => { grads: tf.Tensor[]; value: tf.Tensor; }.
Example 1:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs"// Defining functionconst fn = (x, y) => x.add(y);// Calling valueAndGrads() methodconst gr = tf.valueAndGrads(fn);// Defining tf.tensor1d inputsconst x = tf.tensor1d([66, 51]);const y = tf.tensor1d([-21, -13]);// Defining value and gradsconst {value, grads} = gr([x, y]);const [dx, dy] = grads;// Printing valueconsole.log('val');value.print();// Printing gradientsconsole.log('dx');dx.print();console.log('dy');dy.print(); |
Output:
val
Tensor
[45, 38]
dx
Tensor
[1, 1]
dy
Tensor
[1, 1]
Example 2:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs"// Calling valueAndGrads() method // with its parameterconst gr = tf.valueAndGrads((x, y) => x.div(y));// Defining tf.tensor1d inputs of // floating point numbersconst x = tf.tensor1d([4.7, 5.8, 99.7]);const y = tf.tensor1d([9.5, -20.5, null]);// Defining value and gradsconst {value, grads} = gr([x, y]);const [dx, dy] = grads;// Printing valueconsole.log('val');value.print();// Printing gradientsconsole.log('dx');dx.print();console.log('dy');dy.print(); |
Output:
val
Tensor
[0.4947368, -0.2829268, Infinity]
dx
Tensor
[0.1052632, -0.0487805, Infinity]
dy
Tensor
[-0.0520776, -0.0138013, -Infinity]
Reference: https://js.tensorflow.org/api/latest/#valueAndGrads
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek 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!



