【问题标题】:Why is no gradient available when using sparse tensors in TensorFlow?为什么在 TensorFlow 中使用稀疏张量时没有梯度可用?
【发布时间】:2018-01-03 01:43:28
【问题描述】:

当计算涉及稀疏张量时,计算关于变量的损失梯度返回None

这是一个最小的例子:

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 上。

【问题讨论】:

    标签: tensorflow


    【解决方案1】:

    事实证明,sparse_to_dense 操作(sparse_tensor_to_dense 是一个方便的包装器)在 TensorFlow 1.2 中没有梯度,但这可以在 TensorFlow 1.3 中解决(请参阅this issue)。截至今天,2018 年 5 月,该错误尚未修复并已关闭,请参阅 this bug description

    一种解决方法是在图表中设置两条单独的路径,一条避免 sparse_to_dense 操作用于向后传递,另一条使用 sparse_to_dense 但仅用于向前传递。

    一种从稀疏张量is described in here获得稠密可微张量的巧妙方法:

        dense_tensor_hack = tf.sparse_add(tf.zeros(sparse_tensor.dense_shape), sparse_tensor)
    

    现在dense_tensor_hack 具有明确定义的渐变。

    【讨论】:

    • 知道后续版本是否已解决此问题?
    • @JoshuaR。链接的 Github 问题包括 2017 年 6 月 16 日的评论说“顺便说一句,这个操作现在有渐变。”也可以使用scatter_nd 作为sparse_to_dense 的替代品。
    猜你喜欢
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 2017-04-29
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多