Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use tf.scatter_update in a two dimensional tf.Variable

I' m following this Manipulating matrix elements in tensorflow. using tf.scatter_update. But my problem is: What happens if my tf.Variable is 2D? Let's say:

a = tf.Variable(initial_value=[[0, 0, 0, 0],[0, 0, 0, 0]])

How can i update for example the first element of every row and assign to that the value 1?

I tried something like

for line in range(2):
    sess.run(tf.scatter_update(a[line],[0],[1]))

but it fails (i was expecting that) and gives me the error:

TypeError: Input 'ref' of 'ScatterUpdate' Op requires l-value input

How can i fix that kind of problems?

`

like image 768
Cfis Yoi Avatar asked Oct 29 '16 15:10

Cfis Yoi


People also ask

How do you initialize a TensorFlow variable in a matrix?

First, remember that you can use the TensorFlow eye functionality to easily create a square identity matrix. We create a 5x5 identity matrix with a data type of float32 and assign it to the Python variable identity matrix. So we used tf. eye, give it a size of 5, and the data type is float32.

How do you get the value of a tf variable?

To get the current value of a variable x in TensorFlow 2, you can simply print it with print(x) . This prints a representation of the tf. Variable object that also shows you its current value.

How do I change the value of a tf variable?

Tensorflow variables represent the tensors whose values can be changed by running operations on them. The assign() is the method available in the Variable class which is used to assign the new tf. Tensor to the variable. The new value must have the same shape and dtype as the old Variable value.

Is tf variable trainable?

New!


1 Answers

In tensorflow you cannot update a Tensor but you can update a Variable.

The scatter_update operator can update only the first dimension of the variable. You have to pass always a reference tensor to the scatter update (a instead of a[line]).

This is how you can update the first element of the variable:

import tensorflow as tf

g = tf.Graph()
with g.as_default():
    a = tf.Variable(initial_value=[[0, 0, 0, 0],[0, 0, 0, 0]])
    b = tf.scatter_update(a, [0, 1], [[1, 0, 0, 0], [1, 0, 0, 0]])

with tf.Session(graph=g) as sess:
   sess.run(tf.initialize_all_variables())
   print sess.run(a)
   print sess.run(b)

Output:

[[0 0 0 0]
 [0 0 0 0]]
[[1 0 0 0]
 [1 0 0 0]]

But having to change again the whole tensor it might be faster to just assign a completely new one.

like image 71
fabrizioM Avatar answered Oct 03 '22 02:10

fabrizioM