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.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
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
# Importing the libraryimport tensorflow as tf# Defining function@tf.functiondef gfg(): a = tf.ones([1, 2]) b = 5*a # Calculating gradient g1 = tf.gradients([b+a], [a]) # Printing result print("res: ",g1)# Calling the functiongfg() |
Output:
res: [<tf.Tensor 'gradients/AddN:0' shape=(1, 2) dtype=float32>]
Example 2:
Python3
# Importing the libraryimport tensorflow as tf# Defining function@tf.functiondef gfg(): a = tf.ones([1, 2]) b = 5*a # Calculating gradient g1 = tf.gradients([b], [a]) # Printing result print("res: ",g1)# Calling the functiongfg() |
Output:
res: [<tf.Tensor 'gradients/mul_grad/Mul_1:0' shape=(1, 2) dtype=float32>]

