zim*_*rmc 6 python deep-learning tensorflow
我一直在使用tf.gradients()函数并遇到了我意想不到的行为。也就是说,它似乎无法计算切片变量的梯度。我举了一个例子,希望能说明我的意思:
import tensorflow as tf
a = tf.Variable([1.0])
b = tf.Variable([1.0])
c = tf.concat(0, [a, b])
print(c) # >Tensor("concat:0", shape=(2,), dtype=float32)
grad_full = tf.gradients(c, c)
grad_slice1 = tf.gradients(c, a)
grad_slice2 = tf.gradients(c, c[:, ]) # --> Here the gradient is None
grad_slice3 = tf.gradients(c, c[0, ]) # --> Here the gradient is None
print(grad_full) # >[<tf.Tensor 'gradients/Fill:0' shape=(2,) dtype=float32>]
print(grad_slice1) # >[<tf.Tensor 'gradients_1/concat_grad/Slice:0' shape=(1,) dtype=float32>]
print(grad_slice2) # >[None]
print(grad_slice3) # >[None]
sess = tf.Session()
sess.run(tf.initialize_all_variables())
grad_full_v, grad_slice_v = sess.run([grad_full[0], grad_slice1[0]])
print(grad_full_v) # >[ 1. 1.]
print(grad_slice_v) # >[ 1.]
Run Code Online (Sandbox Code Playgroud)
我的问题是:
1)我是否按照预期方式使用 tf.gradients() 函数?
2)如果是这样,这种行为有原因吗?根据我的理解,切片不一定会破坏反向传播。
3)这是否意味着我需要避免在整个网络内进行切片(或至少对于从变量到损失的每条路径)?例如,这意味着我不能将完全连接层的结果分割成许多有意义的部分(例如用一个 fc 层估计多个标量,然后将联合估计分割成我想要使用的部分)。
我正在使用 Python 3.5 在 Ubuntu 16 上使用源代码构建 Tensorflow 0.11 RC0。
d = c[:, ]然后创建一个不同的张量a, b, c。如果考虑依赖图,则 d 取决于 c。那么渐变在这种情况下不起作用。grad(y, x)如果 x 依赖于 y,则有效,反之则不然。
| 归档时间: |
|
| 查看次数: |
1913 次 |
| 最近记录: |