首页 文章

在Tensor中调整单值 - TensorFlow

提问于
浏览
52

我觉得这很尴尬,但你如何在张量内调整单个值?假设你想在张量中只有一个值加'1'?

通过索引编写它不起作用:

TypeError: 'Tensor' object does not support item assignment

一种方法是 Build 一个相同形状的0张量 . 然后在您想要的位置调整1 . 然后你将两个张量加在一起 . 这又遇到了和以前一样的问题 .

我已多次阅读API文档,似乎无法弄清楚如何执行此操作 . 提前致谢!

2 回答

  • 64

    UPDATE: TensorFlow 1.0包含一个tf.scatter_nd()运算符,可用于在不创建 tf.SparseTensor 的情况下创建 delta .


    对于现有的操作,这实际上是非常棘手的!也许有人可以建议一个更好的方法来结束以下,但这是一种方法来做到这一点 .

    假设你有一个 tf.constant() 张量:

    c = tf.constant([[0.0, 0.0, 0.0],
                     [0.0, 0.0, 0.0],
                     [0.0, 0.0, 0.0]])
    

    ...并且您想在位置[1,1]添加 1.0 . 您可以这样做的一种方法是定义一个tf.SparseTensordelta ,表示更改:

    indices = [[1, 1]]  # A list of coordinates to update.
    
    values = [1.0]  # A list of values corresponding to the respective
                    # coordinate in indices.
    
    shape = [3, 3]  # The shape of the corresponding dense tensor, same as `c`.
    
    delta = tf.SparseTensor(indices, values, shape)
    

    然后你可以使用tf.sparse_tensor_to_dense() op从 delta 创建一个密集张量并将其添加到 c

    result = c + tf.sparse_tensor_to_dense(delta)
    
    sess = tf.Session()
    sess.run(result)
    # ==> array([[ 0.,  0.,  0.],
    #            [ 0.,  1.,  0.],
    #            [ 0.,  0.,  0.]], dtype=float32)
    
  • 8

    tf.scatter_update(ref, indices, updates)tf.scatter_add(ref, indices, updates) 怎么样?

    ref[indices[...], :] = updates
    ref[indices[...], :] += updates
    

    this .

相关问题