如何获得 TensorFlow 变量的损失梯度?
How do I get the gradient of the loss at a TensorFlow variable?
我追求的功能是能够在给定一些数据的情况下判断给定变量相对于我的误差函数的梯度。
执行此操作的一种方法是查看调用训练后变量发生了多少变化,但显然这可能会根据学习算法发生巨大变化(例如,几乎不可能用类似的东西来判断RProp) 而且不是很干净。
提前致谢。
tf.gradients()
函数允许您计算一个张量相对于一个或多个其他张量(包括变量)的符号梯度。考虑以下简单示例:
data = tf.placeholder(tf.float32)
var = tf.Variable(...) # Must be a tf.float32 or tf.float64 variable.
loss = some_function_of(var, data) # some_function_of() returns a `Tensor`.
var_grad = tf.gradients(loss, [var])[0]
然后您可以使用此符号梯度来评估某些特定点(数据)的梯度:
sess = tf.Session()
var_grad_val = sess.run(var_grad, feed_dict={data: ...})
在 TensorFlow 2.0 中,您可以使用 GradientTape
来实现这一点。 GradientTape
记录在此上下文中发生的任何计算的梯度。下面是您可以如何执行此操作的示例。
import tensorflow as tf
# Here goes the neural network weights as tf.Variable
x = tf.Variable(3.0)
# TensorFlow operations executed within the context of
# a GradientTape are recorded for differentiation
with tf.GradientTape() as tape:
# Doing the computation in the context of the gradient tape
# For example computing loss
y = x ** 2
# Getting the gradient of network weights w.r.t. loss
dy_dx = tape.gradient(y, x)
print(dy_dx) # Returns 6
我追求的功能是能够在给定一些数据的情况下判断给定变量相对于我的误差函数的梯度。
执行此操作的一种方法是查看调用训练后变量发生了多少变化,但显然这可能会根据学习算法发生巨大变化(例如,几乎不可能用类似的东西来判断RProp) 而且不是很干净。
提前致谢。
tf.gradients()
函数允许您计算一个张量相对于一个或多个其他张量(包括变量)的符号梯度。考虑以下简单示例:
data = tf.placeholder(tf.float32)
var = tf.Variable(...) # Must be a tf.float32 or tf.float64 variable.
loss = some_function_of(var, data) # some_function_of() returns a `Tensor`.
var_grad = tf.gradients(loss, [var])[0]
然后您可以使用此符号梯度来评估某些特定点(数据)的梯度:
sess = tf.Session()
var_grad_val = sess.run(var_grad, feed_dict={data: ...})
在 TensorFlow 2.0 中,您可以使用 GradientTape
来实现这一点。 GradientTape
记录在此上下文中发生的任何计算的梯度。下面是您可以如何执行此操作的示例。
import tensorflow as tf
# Here goes the neural network weights as tf.Variable
x = tf.Variable(3.0)
# TensorFlow operations executed within the context of
# a GradientTape are recorded for differentiation
with tf.GradientTape() as tape:
# Doing the computation in the context of the gradient tape
# For example computing loss
y = x ** 2
# Getting the gradient of network weights w.r.t. loss
dy_dx = tape.gradient(y, x)
print(dy_dx) # Returns 6