2017-07-27 280 views
1

當計算涉及稀疏張量時,計算相對於變量的損失梯度返回None爲什麼在TensorFlow中使用稀疏張量時沒有梯度可用?

這裏有一個小例子:

x = tf.placeholder(tf.float32, shape=[1,2]) 

w = tf.get_variable("w", [2, 3]) 

y = tf.matmul(x, w) 

sparse_loss = tf.SparseTensor([[0], [2], [4]], tf.reshape(y, [-1]), [5]) 

dense_loss = tf.sparse_tensor_to_dense(sparse_loss) 

sparse_grads = tf.gradients(sparse_loss.values, w) 
print(sparse_grads) 

dense_grads = tf.gradients(dense_loss, w) 
print(dense_grads) 

這將打印

[<tf.Tensor 'gradients/MatMul_grad/MatMul_1:0' shape=(2, 3) dtype=float32>] 
[None] 

顯示,梯度可用於稀疏張量值,但不是在它已經重新轉換爲密張量。

在沒有GPU的Ubuntu Linux上,TensorFlow 1.2發生這種情況。

回答

1

事實證明sparse_to_dense操作(其中sparse_tensor_to_dense是一個便捷包裝)在TensorFlow 1.2中沒有梯度,但這可以在TensorFlow 1.3(請參閱this issue)中解決。

解決方法是在圖形中使用兩條單​​獨的路徑,一條避免sparse_to_dense操作用於反向傳遞,另一條使用sparse_to_dense但僅用於正向傳遞。

+0

任何想法,如果這已在後續版本中解決? –

+1

@JoshuaR。鏈接的Github問題在2017年6月16日發表評論,內容爲「順便提一下,此操作現在有一個漸變。」也可以使用'scatter_nd'作爲'sparse_to_dense'的替代方法。 –

相關問題