如何使用 tf.scatter_add 在 tensorflow 中增加矩阵元素? [英] how to increment matrix element in tensorflow using tf.scatter_add?
问题描述
tf.scatter_add 适用于 1d(形状 1) 张量:
tf.scatter_add works nicely for 1d (shape 1) tensors:
> 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)
但是我怎样才能增加,比如说
But how can I increment, say [0,0] element of
M = tf.Variable(tf.constant([[1,2], [3,4]]))
使其成为 [[2, 2], [3, 4]]使用 tf.scatter_add?
to make it [[2, 2], [3, 4]] using tf.scatter_add?
官方文档很友好'一个神秘的.我尝试了不同的 arg 值,比如
the official documentation is kind'a cryptic. And I tried different arg values, say
> sess.run(tf.scatter_add(M, [[0, 0]], [1]))
*** ValueError: Shapes (1,) and (1, 2, 2) are not compatible
并没有成功.
顺便说一句,就我而言,M 非常大并且可以动态调整大小.因此,将零一等于一元素矩阵添加到 M 不是这种情况.
Btw, in my case, M is quite large and is resized dynamically. So adding zero-but-one equal to 1 element matrix to M is not the case.
推荐答案
tf.scatter_add
更新张量的切片,但不能更新单个系数.例如,它可以一次更新矩阵的整行.
tf.scatter_add
updates slices of a tensor and not capable of updating individual coefficients. For instance, it can update entire rows of a matrix at once.
此外,tf.scatter_add
的 updates
参数的形状取决于其 indices
参数的形状.当 ref
参数是一个形状为 (M, N)
的矩阵时,则
Also, the shape of the updates
argument to tf.scatter_add
depends on the shape of its indices
argument. When the ref
argument is a matrix with shape (M, N)
, then
- 如果
indices
是一个标量i
,那么updates
应该是一个形状为(N)
的向量. - 如果
indices
是一个形状为(k)
的向量[i1, i2, .. ik]
,则updates
应该具有(k, N)
的形状.
- If
indices
is a scalari
, thenupdates
should be a vector with shape(N)
. - If
indices
is a vector[i1, i2, .. ik]
with shape(k)
, thenupdates
should have the shape(k, N)
.
在你的情况下,你可以简单地将 [1, 0]
添加到 M
的第一行,如下所示,以获得你想要的效果:
In your case, you can simply add [1, 0]
to the first row of M
as follows to get the effect you want:
sess.run(tf.scatter_add(M, 0, [1, 0]))
array([[2, 2],
[3, 4]], dtype=int32)
这篇关于如何使用 tf.scatter_add 在 tensorflow 中增加矩阵元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!