tf.gradients() 对 ys 求和,是吗?

tf.gradients() sums over ys, does it?

https://www.tensorflow.org/versions/r1.6/api_docs/python/tf/gradients

在 tf.gradients(ys, xs) 的文档中指出

Constructs symbolic derivatives of sum of ys w.r.t. x in xs

我对求和部分感到困惑,我在其他地方读到过,这对批次中每个 x 的批次中的导数 dy/dx 求和。但是,每当我使用它时,我都看不到这种情况的发生。举个简单的例子:

x_dims = 3
batch_size = 4

x = tf.placeholder(tf.float32, (None, x_dims))

y = 2*(x**2)

grads = tf.gradients(y,x)

sess = tf.Session()

x_val = np.random.randint(0, 10, (batch_size, x_dims))
y_val, grads_val = sess.run([y, grads], {x:x_val})

print('x = \n', x_val)
print('y = \n', y_val)
print('dy/dx = \n', grads_val[0])

这给出了以下输出:

x = 
 [[5 3 7]
 [2 2 5]
 [7 5 0]
 [3 7 6]]
y = 
 [[50. 18. 98.]
 [ 8.  8. 50.]
 [98. 50.  0.]
 [18. 98. 72.]]
dy/dx = 
 [[20. 12. 28.]
 [ 8.  8. 20.]
 [28. 20.  0.]
 [12. 28. 24.]]

这是我期望的输出,只是批处理中每个元素的导数 dy/dx。我没有看到任何求和发生。我在其他示例中看到,此操作之后除以批处理大小以计算 tf.gradients() 对批处理的梯度求和(参见此处:https://pemami4911.github.io/blog/2016/08/21/ddpg-rl.html)。为什么这是必要的?

我正在使用 Tensorflow 1.6 和 Python 3.

如果 y 和 x 具有相同的形状,则 dy/dx 的总和恰好是一个值的总和。但是,如果每个 x 有多个 y,则对梯度求和。

import numpy as np
import tensorflow as tf

x_dims = 3
batch_size = 4

x = tf.placeholder(tf.float32, (None, x_dims))
y = 2*(x**2)
z = tf.stack([y, y]) # There are twice as many z's as x's

dy_dx = tf.gradients(y,x)
dz_dx = tf.gradients(z,x)

sess = tf.Session()

x_val = np.random.randint(0, 10, (batch_size, x_dims))
y_val, z_val, dy_dx_val, dz_dx_val = sess.run([y, z, dy_dx, dz_dx], {x:x_val})

print('x.shape =', x_val.shape)
print('x = \n', x_val)
print('y.shape = ', y_val.shape)
print('y = \n', y_val)
print('z.shape = ', z_val.shape)
print('z = \n', z_val)
print('dy/dx = \n', dy_dx_val[0])
print('dz/dx = \n', dz_dx_val[0])

产生以下输出:

x.shape = (4, 3)
x = 
 [[1 4 8]
 [0 2 8]
 [2 8 1]
 [4 5 2]]

y.shape =  (4, 3)
y = 
 [[  2.  32. 128.]
 [  0.   8. 128.]
 [  8. 128.   2.]
 [ 32.  50.   8.]]

z.shape =  (2, 4, 3)
z = 
 [[[  2.  32. 128.]
  [  0.   8. 128.]
  [  8. 128.   2.]
  [ 32.  50.   8.]]

 [[  2.  32. 128.]
  [  0.   8. 128.]
  [  8. 128.   2.]
  [ 32.  50.   8.]]]

dy/dx = 
 [[ 4. 16. 32.]
 [ 0.  8. 32.]
 [ 8. 32.  4.]
 [16. 20.  8.]]
dz/dx = 
 [[ 8. 32. 64.]
 [ 0. 16. 64.]
 [16. 64.  8.]
 [32. 40. 16.]]

特别注意 dz/dx 的值是 dy/dz 的两倍,因为它们是在堆栈的输入上求和的。