Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Tensorflow.js tf.grad() Function

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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:

  • f: The specified function f(x) for which gradient is being calculated.

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

Example 1:

Javascript




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

Javascript




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


My Personal Notes arrow_drop_up
Last Updated : 12 May, 2021
Like Article
Save Article
Similar Reads
Related Tutorials