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 library import * as tf from "@tensorflow/tfjs" // Defining function const fn = (x, y) => x.add(y); // Calling valueAndGrads() method const gr = tf.valueAndGrads(fn); // Defining tf.tensor1d inputs const x = tf.tensor1d([66, 51]); const y = tf.tensor1d([-21, -13]); // Defining value and grads const {value, grads} = gr([x, y]); const [dx, dy] = grads; // Printing value console.log( 'val' ); value.print(); // Printing gradients console.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 library import * as tf from "@tensorflow/tfjs" // Calling valueAndGrads() method // with its parameter const gr = tf.valueAndGrads((x, y) => x.div(y)); // Defining tf.tensor1d inputs of // floating point numbers const x = tf.tensor1d([4.7, 5.8, 99.7]); const y = tf.tensor1d([9.5, -20.5, null ]); // Defining value and grads const {value, grads} = gr([x, y]); const [dx, dy] = grads; // Printing value console.log( 'val' ); value.print(); // Printing gradients console.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