Open In App

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:

Syntax:



tf.valueAndGrads(f)

 Parameters:   

Return Value: It returns grads and value i.e. ( args: tf.Tensor[], dy?: tf.Tensor) => { grads: tf.Tensor[]; value: tf.Tensor; }.

Example 1: 




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




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


Article Tags :