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

时间:2018-08-15 12:45:17

标签: python python-3.x tensorflow machine-learning gradient-descent

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

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

  

构造w的ys和的符号导数。 xs 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。

1 个答案:

答案 0 :(得分:0)

如果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值的两倍,因为它们是在堆栈的输入上求和的。