Open In App

Python – tensorflow.gradients()

Improve
Improve
Like Article
Like
Save
Share
Report

TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks. 

gradients() is used to get symbolic derivatives of sum of ys w.r.t. x in xs. It doesn’t work when eager execution is enabled.

Syntax: tensorflow.gradients( ys, xs, grad_ys, name, gate_gradients, aggregation_method, stop_gradients, unconnected_gradients)

Parameters:

  • ys: It is a Tensor or list of Tensors that need to be differentiated.
  • xs: It is a Tensor or list of Tensors which is used for differentiation.
  • grad_ys(optional): It is a Tensor or list of Tensors that is used to compute gradients for y.
  • name(optional): It is used group gradient operation together. It’s default value is gradients.
  • gate_gradients(optional): It used to avoid race condition. If true , it will add a tuple around the gradients returned for an operations.
  • aggregation_method(optional): It’s value is a constant defined in AggregationMethod class.
  • stop_gradients(optional): It’s a Tensor or list of tensors not to differentiate through.
  • unconnected_gradients(optional): It specifies the gradient value returned when the given input tensors are unconnected. Accepted values are constants defined in the UnconnectedGradients class.

Returns: A list of Tensor of length len(xs) where each tensor is the sum(dy/dx) for y in ys and for x in xs. 

Example 1:

Python3




# Importing the library
import tensorflow as tf
 
# Defining function
@tf.function
def gfg():
  a = tf.ones([1, 2])
  b = 5*a
 
  # Calculating gradient
  g1 = tf.gradients([b+a], [a])
 
  # Printing result
  print("res: ",g1)
 
# Calling the  function
gfg()


Output:

res:  [<tf.Tensor 'gradients/AddN:0' shape=(1, 2) dtype=float32>]

Example 2:

Python3




# Importing the library
import tensorflow as tf
 
# Defining function
@tf.function
def gfg():
  a = tf.ones([1, 2])
  b = 5*a
 
  # Calculating gradient
  g1 = tf.gradients([b], [a])
 
  # Printing result
  print("res: ",g1)
 
# Calling the  function
gfg()


Output:

res:  [<tf.Tensor 'gradients/mul_grad/Mul_1:0' shape=(1, 2) dtype=float32>]


Last Updated : 14 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads