6

I am using Tensorflow 2.0, and am trying to update slices within my tensor.

Using a plain item assignment like in PyTorch, it does not work.

import tensorflow as tf

tensor = tf.ones((10, 192, 85))
tensor[:, :, 0] = tf.math.sigmoid([:, :, 0])

>>> Output
TypeError: 'tensorflow.python.framework.ops.EagerTensor' object does not support item assignment

I see that it is possible to use tf.tensor_scatter_nd_update, but it feels too verbose to be efficient, as I have to separately derive the indices to be updated. Thus, I am not sure if this is the best way to do item assignment in eager tensors (I need the code block below to achieve the simpler "PyTorch 2-liner style" above):

import tensorflow as tf

def get_indices(tensor):
  indices = []
  for i in range(tensor.shape[0]):
    for j in range(tensor.shape[1]):
      indices.append([i, j, 0])
  return tf.convert_to_tensor(indices)

tensor = tf.ones((10, 192, 85))
indices = get_indices(tensor)
updates = tf.reshape(tf.math.sigmoid(tensor[:, :, 0]), (-1,))
tensor = tf.tensor_scatter_nd_update(tensor, indices, updates)

Is there an easier/more efficient way to do item assignment of EagerTensors in Tensorflow 2.0?

1 Answer 1

0

you could do:

tensor = tf.ones((10, 192, 85))
tensor = tf.concat([tf.math.sigmoid(tensor[:,:,0:1]), tensor[:,:,1:]], axis=2)
2
  • This works for performing sigmoid in the last layer, but if I have to perform sigmoid operations across different layers within the tensor then it might not be too suitable.
    – chaooder
    Commented Feb 4, 2020 at 14:02
  • 1
    alternatively, a,b,c, = tf.split(tensor, [a_dim, b_dim, c_dim], axis=2); tf.concat([a, tf.math.sigmoid(b), c], axis=2) and specify which b_dim you want to process.
    – kib
    Commented Feb 4, 2020 at 16:01

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.