Python – tensorflow.gradients()
TensorFlow 是由 Google 设计的开源Python库,用于开发机器学习模型和深度学习神经网络。
gradients()用于获取 xs 中 ys wrt x 之和的符号导数。启用急切执行时它不起作用。
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.
示例 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()
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()
输出:
res: []
示例 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()
输出:
res: []