Convert elements to tensorflow array using dictionary

I have an array of tensorflow and I want to convert each of its elements to another element using a dictionary.

Here is my array:

elems = tf.convert_to_tensor(np.array([1, 2, 3, 4, 5, 6]))

and here is the dictionary:

d = {1:1,2:5,3:7,4:5,5:8,6:2}

After conversion, the resulting array should be

tf.convert_to_tensor(np.array([1, 5, 7, 5, 8, 2]))

To do this, I tried using tf.map_fnas follows:

import tensorflow as tf
import numpy as np

d = {1:1,2:5,3:7,4:5,5:8,6:2}

elems = tf.convert_to_tensor(np.array([1, 2, 3, 4, 5, 6]))
res = tf.map_fn(lambda x: d[x], elems)
sess=tf.Session()
print(sess.run(res))

When I run the code above, I get the following error:

squares = tf.map_fn(lambda x: d[x], elems) KeyError: <tf.Tensor 'map/while/TensorArrayReadV3:0' shape=() dtype=int64>

What will be the correct way? I basically tried to monitor usage here .

PS my arrays are actually 3D, I just used 1D as an example, since in this case the code also does not work.

+4
source share
1 answer

tensorflow.contrib.lookup.HashTable:

import tensorflow as tf
import numpy as np

d = {1:1,2:5,3:7,4:5,5:8,6:2}
keys = list(d.keys())
values = [d[k] for k in keys]
table = tf.contrib.lookup.HashTable(
  tf.contrib.lookup.KeyValueTensorInitializer(keys, values, key_dtype=tf.int64, value_dtype=tf.int64), -1
)
elems = tf.convert_to_tensor(np.array([1, 2, 3, 4, 5, 6]), dtype=tf.int64)
res = tf.map_fn(lambda x: table.lookup(x), elems)
sess=tf.Session()
sess.run(table.init)
print(sess.run(res))
+4

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


All Articles