【问题标题】:how to increment matrix element in tensorflow using tf.scatter_add?如何使用 tf.scatter_add 在张量流中增加矩阵元素?
【发布时间】:2016-07-19 14:21:37
【问题描述】:

tf.scatter_add 适用于 1d(形状 1)张量:

> S = tf.Variable(tf.constant([1,2,3,4]))
> sess.run(tf.initialize_all_variables())
> sess.run(tf.scatter_add(S, [0], [10]))

array([11,  2,  3,  4], dtype=int32)

> sess.run(tf.scatter_add(S, [0, 1], [10, 100]))

array([ 21, 102,   3,   4], dtype=int32)

但是我怎样才能增加,比如说

的 [0,0] 元素
M = tf.Variable(tf.constant([[1,2], [3,4]]))

使其成为 [[2, 2], [3, 4]] 使用 tf.scatter_add?

official documentation 有点神秘。我尝试了不同的 arg 值,比如

> sess.run(tf.scatter_add(M, [[0, 0]], [1]))
*** ValueError: Shapes (1,) and (1, 2, 2) are not compatible

并没有成功。

顺便说一句,在我的情况下,M 非常大并且可以动态调整大小。 因此,将等于 1 个元素的矩阵添加到 M 中的情况并非如此。

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    tf.scatter_add 更新张量的切片并且不能更新单个系数。例如,它可以一次更新矩阵的整行。

    此外,tf.scatter_addupdates 参数的形状取决于其 indices 参数的形状。当ref 参数是一个形状为(M, N) 的矩阵时,那么

    • 如果indices 是一个标量i,那么updates 应该是一个形状为(N) 的向量。
    • 如果indices 是形状为(k) 的向量[i1, i2, .. ik],则updates 的形状应为(k, N)

    在你的情况下,你可以简单地将[1, 0]添加到M的第一行,如下所示得到你想要的效果:

    sess.run(tf.scatter_add(M, 0, [1, 0]))
    array([[2, 2],
       [3, 4]], dtype=int32)
    

    【讨论】:

      猜你喜欢
      • 2016-06-16
      • 1970-01-01
      • 1970-01-01
      • 2018-05-24
      • 2018-12-09
      • 2012-10-04
      • 2019-12-26
      • 2019-04-21
      • 2023-03-20
      相关资源
      最近更新 更多