Suppose I have the following variable x and I wish to assign 1 to all the zeros.
x = tf.random.poisson((3,5), 1)
idx = x == 0
y = tf.Variable(tf.zeros_like(x, dtype=tf.float32))
y[idx] = 1.0
When I try y[idx].assign(1.0)
I get the error: AttributeError: 'tensorflow.python.framework.ops.EagerTensor' object has no attribute 'assign'
.
I also tried other variations of this like below with no luck:
y[idx].assign(tf.ones_like(y[idx]))
y[idx] = tf.ones_like(y[idx], dtype=tf.float32)
In my case what I really have to assign is -infinity. I'm assuming if I can do above I can assign that, but please do let me know if this is more complicated for some reason.
Without further context, I don't know why you want to update a Variable
. But when you create one with a value (under tensorflow 2.0 eager execution), you can preset the matrix first:
>>> 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)>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.