Python – tensorflow.gradients()

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.

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:


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

Example 2:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:


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




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.