我所追求的功能是能够在给定一些数据的情况下告诉给定变量的梯度与我的误差函数有关.
实现这一目标的一种方法是查看变量在调用训练后变化了多少,但显然可以根据学习算法大量变化(例如,几乎不可能用RProp这样的东西来判断)并且只是不是很干净.
提前致谢.
mrr*_*rry 55
该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]
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用此符号渐变来评估某些特定点(数据)中的渐变:
sess = tf.Session()
var_grad_val = sess.run(var_grad, feed_dict={data: ...})
Run Code Online (Sandbox Code Playgroud)
在TensorFlow 2.0中,您可以GradientTape用来实现这一目标。GradientTape记录在上下文中发生的任何计算的梯度。以下是如何执行此操作的示例。
import tensorflow as tf
# Here goes the neural network weights as tf.Variable
x = tf.Variable(3.0)
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 weight w.r.t loss
dy_dx = tape.gradient(y, x)
print(dy_dx) # Returns 6
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35651 次 |
| 最近记录: |