Tuesday, October 7, 2025
HomeLanguagesPython – tensorflow.gradients()

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.

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>]
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32340 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6708 POSTS0 COMMENTS
Nicole Veronica
11872 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11936 POSTS0 COMMENTS
Shaida Kate Naidoo
6829 POSTS0 COMMENTS
Ted Musemwa
7090 POSTS0 COMMENTS
Thapelo Manthata
6780 POSTS0 COMMENTS
Umr Jansen
6784 POSTS0 COMMENTS