python - 变量的切片返回梯度无

标签 python tensorflow deep-learning

我一直在研究 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.]

我的问题是:

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 时有效,反之则不行。

关于python - 变量的切片返回梯度无,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41889531/

相关文章:

tensorflow - Keras 中的 MaxPool 和 MaxPooling 层有什么区别?

Python——2.7 中没有的东西是 3.1 中的什么?很多东西都被向后移植了,什么不是?

python - 为什么我会收到此图表已断开连接的错误?

python - python在Windows上进行多处理时出现运行时错误

python - 如何在 TensorFlow 中更改 csv 文件的 dtype?

python - 导入错误 : cannot import name 'keras'

python - 在神经网络中找到最佳学习率和时期

sqlite - RKFace.modelId 对应的 Apple Photos 中的 facetile 是如何实现的?

python - 每行文本到单词 + Python 中的命名实体标签

python - 在 iPython 和 Django 中使用配置文件