Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjust Single Value within Tensor -- TensorFlow

I feel embarrassed asking this, but how do you adjust a single value within a tensor? Suppose you want to add '1' to only one value within your tensor?

Doing it by indexing doesn't work:

TypeError: 'Tensor' object does not support item assignment 

One approach would be to build an identically shaped tensor of 0's. And then adjusting a 1 at the position you want. Then you would add the two tensors together. Again this runs into the same problem as before.

I've read through the API docs several times and can't seem to figure out how to do this. Thanks in advance!

like image 890
LeavesBreathe Avatar asked Jan 08 '16 20:01

LeavesBreathe


People also ask

How do I change the value of a tensor in TensorFlow?

Yet, it seems not possible in the current version of Tensorflow. An alternative way is changing tensor to ndarray for the process, and then use tf. convert_to_tensor to change back. The key is how to change tensor to ndarray .

Can tensors have strings?

# Tensors can be strings, too here is a scalar string. # If you have three string tensors of different lengths, this is OK. # Note that the shape is (3,). The string length is not included.

Can you slice tensors?

You can use tf. slice on higher dimensional tensors as well. You can also use tf. strided_slice to extract slices of tensors by 'striding' over the tensor dimensions.


2 Answers

UPDATE: TensorFlow 1.0 includes a tf.scatter_nd() operator, which can be used to create delta below without creating a tf.SparseTensor.


This is actually surprisingly tricky with the existing ops! Perhaps somebody can suggest a nicer way to wrap up the following, but here's one way to do it.

Let's say you have a tf.constant() tensor:

c = tf.constant([[0.0, 0.0, 0.0],                  [0.0, 0.0, 0.0],                  [0.0, 0.0, 0.0]]) 

...and you want to add 1.0 at location [1, 1]. One way you could do this is to define a tf.SparseTensor, delta, representing the change:

indices = [[1, 1]]  # A list of coordinates to update.  values = [1.0]  # A list of values corresponding to the respective                 # coordinate in indices.  shape = [3, 3]  # The shape of the corresponding dense tensor, same as `c`.  delta = tf.SparseTensor(indices, values, shape) 

Then you can use the tf.sparse_tensor_to_dense() op to make a dense tensor from delta and add it to c:

result = c + tf.sparse_tensor_to_dense(delta)  sess = tf.Session() sess.run(result) # ==> array([[ 0.,  0.,  0.], #            [ 0.,  1.,  0.], #            [ 0.,  0.,  0.]], dtype=float32) 
like image 127
mrry Avatar answered Oct 06 '22 14:10

mrry


How about tf.scatter_update(ref, indices, updates) or tf.scatter_add(ref, indices, updates)?

ref[indices[...], :] = updates ref[indices[...], :] += updates 

See this.

like image 22
Liping Liu Avatar answered Oct 06 '22 15:10

Liping Liu