Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill a specific index in tensor with a value

I'm beginner with tensorflow. I created this tensor

z = tf.zeros([20,2], tf.float32)

and I want to change the value of index z[2,1] and z[2,2] to 1.0 instead of zeros. How can I do that?

like image 274
shoseta Avatar asked Jan 03 '23 19:01

shoseta


1 Answers

What you exactly ask is not possible for two reasons:

  • z is a constant tensor, it can't be changed.
  • There is no z[2,2], only z[2,0] and z[2,1].

But assuming you want to change z to a variable and fix the indices, it can be done this way:

z = tf.Variable(tf.zeros([20,2], tf.float32))  # a variable, not a const
assign21 = tf.assign(z[2, 0], 1.0)             # an op to update z
assign22 = tf.assign(z[2, 1], 1.0)             # an op to update z

with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())
  print(sess.run(z))                           # prints all zeros
  sess.run([assign21, assign22])
  print(sess.run(z))                           # prints 1.0 in the 3d row
like image 151
Maxim Avatar answered Jan 13 '23 14:01

Maxim