python - 如何使用 tf.scatter_add 在 tensorflow 中增加矩阵元素?

标签 python tensorflow

tf.scatter_add 适用于一维(形状 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 非常大并且可以动态调整大小。 所以给M加上0-but-1等于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)

关于python - 如何使用 tf.scatter_add 在 tensorflow 中增加矩阵元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38461214/

相关文章:

python - PyQt:如何在 Raspberry Pi 桌面启动时运行 GUI?

Python Pandas GroupBy 相当于 SQL 中的 If A and not B where 子句

python - 如何应用 ConvLSTM 层

python - tensorflow 中使用的钩子(Hook)是什么意思

tensorflow - 如何用索引替换张量中的值?

Python SpaCy Regex 不提取包含单词的标记

python - django uwsgi - 重启后 nginx 重启不起作用

python - 如何减少 Tensorflow/Keras 使用的 CPU 数量?

r - 如何在 LSTM 中有效地使用批量归一化?

python - localhost django dev server vs. mac os 上的 postgres 慢?