[英]Assign to slice in Tensorflow2
假设我有以下变量 x 并且我希望将 1 分配给所有零。
x = tf.random.poisson((3,5), 1)
idx = x == 0
y = tf.Variable(tf.zeros_like(x, dtype=tf.float32))
y[idx] = 1.0
当我尝试y[idx].assign(1.0)
时出现错误: AttributeError: 'tensorflow.python.framework.ops.EagerTensor' object has no attribute 'assign'
。
我还尝试了如下所示的其他变体,但没有成功:
y[idx].assign(tf.ones_like(y[idx]))
y[idx] = tf.ones_like(y[idx], dtype=tf.float32)
在我的例子中,我真正需要分配的是 -infinity。 我假设如果我能做到以上,我可以分配它,但如果由于某种原因这更复杂,请告诉我。
没有进一步的上下文,我不知道你为什么要更新Variable
。 但是当你创建一个有值的时候(tensorflow 2.0 eager execution下),你可以先预设矩阵:
>>> x
<tf.Tensor: shape=(3, 5), dtype=float32, numpy=
array([[2., 2., 2., 0., 0.],
[1., 1., 1., 2., 0.],
[1., 0., 2., 0., 1.]], dtype=float32)>
>>> idx
<tf.Tensor: shape=(3, 5), dtype=bool, numpy=
array([[False, False, False, True, True],
[False, False, False, False, True],
[False, True, False, True, False]])>
>>> tf.where(idx, np.inf, tf.zeros_like(x, dtype=tf.float32))
<tf.Tensor: shape=(3, 5), dtype=float32, numpy=
array([[ 0., 0., 0., inf, inf],
[ 0., 0., 0., 0., inf],
[ 0., inf, 0., inf, 0.]], dtype=float32)>
>>> y = tf.Variable(tf.where(idx, np.inf, tf.zeros_like(x, dtype=tf.float32)), dtype=tf.float32)
>>> y
<tf.Variable 'Variable:0' shape=(3, 5) dtype=float32, numpy=
array([[ 0., 0., 0., inf, inf],
[ 0., 0., 0., 0., inf],
[ 0., inf, 0., inf, 0.]], dtype=float32)>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.