Open In App

Tensorflow.js tf.grad() Function

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

The tf.grad() function is used to return the gradient of the specified function f(x) with respect to x.



Syntax:  

tf.grad (f)

Parameters: This function accepts a parameter which is illustrated below:



Return Value: It returns the gradient of the specified function f(x) with respect to x.

Example 1:




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Initializing a function f(x) = x^2
const f = x => x.square();
  
// Calling the .grad() function which 
// calculates f'(x) and gives value as 2x
const g = tf.grad(f);
  
// Initializing a tensor of values for
// which gradient will be returned
const x = tf.tensor1d([1, 2, 3]);
  
// Getting the values of gradient of the
// function f(x) for the above specified
// tensor 
g(x).print();

Output:

Tensor
   [2, 4, 6]

Example 2:




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Using the function f(x) = x^3 as the 
// parameter for the .grad() function which 
// calculates f'(x) and gives value as 3x^2
const g = tf.grad(x => x.pow(tf.scalar(3, 'int32')));
  
// Initializing a tensor of values for
// which gradient will be returned
const x = tf.tensor1d([0, 1, 2]);
  
// Getting the values of gradient of the
// function f(x) for the above specified
// tensor 
g(x).print();

Output:

Tensor
   [0, 3, 12]

Reference: https://js.tensorflow.org/api/latest/#grad


Article Tags :