How to index a list with the tensorflow tensor?

Assume that the list is not associated with concatenable objects that must be accessed through the lookup table. Thus, the list index will be a tensor object, but this is not possible.

tf_look_up = tf.constant(np.array([3, 2, 1, 0, 4])) index = tf.constant(2) list = [0,1,2,3,4] target = list[tf_look_up[index]] 

The following error message appears.

  TypeError: list indices must be integers or slices, not Tensor 

Is there a way / workaround to index lists with tensors?

+5
source share
3 answers

tf.gather is for this purpose.

Just run tf.gather(list, tf_look_up[index]) , you will get what you want.

+4
source

Tensorflow has HashTable support. See the documentation for more information.

Here you can do the following:

 table = tf.contrib.lookup.HashTable( tf.contrib.lookup.KeyValueTensorInitializer(tf_look_up, list), -1) 

Then just enter your desired input by running

 target = table.lookup(index) 

Note that -1 is the default if the key is not found. You may need to add the constructor key_dtype and value_dtype depending on the configuration of your tensors.

+1
source

I think this will help: How to convert tensor to numpy array in TensorFlow?

"To convert back from a tensor to a numpy array, you can simply run .eval () on the converted tensor."

0
source

Source: https://habr.com/ru/post/1261396/


All Articles