![](/img/trans.png)
[英]In Tensorflow, how to use tf.gather() for the last dimension?
[英]Tensorflow: chaining tf.gather() produces IndexedSlices warning
我遇到了一个问题,链接tf.gather()
索引会产生以下警告:
/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/gradients.py:90: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of memory.
"Converting sparse IndexedSlices to a dense Tensor of unknown shape. "
当一个层索引到输入层,在相应的切片上执行某些操作,然后下一层索引到结果中时,就会出现这种情况。 这是一个代表性的例子:
import tensorflow as tf
## 10-Dimensional data will be fed to the model
X = tf.placeholder( tf.float32, [10, None] )
## W works with the first 3 features of a sample
W = tf.Variable( tf.ones( [5, 3] ) )
Xi = tf.gather( X, [0,1,2] )
mm = tf.matmul( W, Xi )
## Indexing into the result produces a warning during backprop
h = tf.gather( mm, [0,1] )
...
train_step = tf.train.AdamOptimizer(1e-4).minimize( loss )
警告在train_step
定义时出现,如果第二个tf.gather()
调用被取消则消失。 如果X
具有明确数量的样本(例如, [10, 1000]
) [10, 1000]
则警告也会消失。
思考?
tf.gather
操作的渐变函数返回IndexedSlices
类型的值。 在你的程序中,输入第二个tf.gather
是tf.matmul
( mm
)的结果。 因此,矩阵乘法的梯度函数传递一个IndexedSlices
值。
现在,想象一下tf.matmul
的渐变函数需要做什么。 为了计算W
的梯度,它必须将输入的梯度乘以Xi
的转置。 在这种情况下,传入的渐变是IndexedSlices
类型, Xi
的转置是密集张量( Tensor
)类型。 TensorFlow没有可以对IndexedSlices
和Tensor
进行操作的矩阵乘法的实现。 因此,简单地转换IndexedSlices
到Tensor
调用之前tf.matmul
。
如果你看一下该转换函数的代码在这里 ,你会发现它打印出来的时候这个稀疏到密集的转换可能导致主要是一个非常大的密集张警告( _LARGE_SPARSE_NUM_ELEMENTS
决定如何大),或未知的密集张量尺寸。 当您使用形状[10, None]
对占位符X
进行整形时,此转换发生在形状未知的IndexedSlices
上(实际上,只有一个维度未知,但仍然无法静态确定结果形状),因此您会看到警告打印出来。 一旦设定的形状X
至[10, 1000]
的形状IndexedSlices
变成完全指定, 并且将得到的致密的张量大小在阈值内,这样就不会看到警告打印出来。
对于你的计算,如果你根本无法避免对tf.gather
的结果的tf.matmul
,那么我会过多地担心这个警告,除非X
的列数非常大。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.