Tensorflow.js tf.valueAndGrads() Function
Last Updated :
21 Jul, 2021
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
import * as tf from "@tensorflow/tfjs"
const fn = (x, y) => x.add(y);
const gr = tf.valueAndGrads(fn);
const x = tf.tensor1d([66, 51]);
const y = tf.tensor1d([-21, -13]);
const {value, grads} = gr([x, y]);
const [dx, dy] = grads;
console.log( 'val' );
value.print();
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
import * as tf from "@tensorflow/tfjs"
const gr = tf.valueAndGrads((x, y) => x.div(y));
const x = tf.tensor1d([4.7, 5.8, 99.7]);
const y = tf.tensor1d([9.5, -20.5, null ]);
const {value, grads} = gr([x, y]);
const [dx, dy] = grads;
console.log( 'val' );
value.print();
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
Share your thoughts in the comments
Please Login to comment...