Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert elements in a tensorflow array using a dictionary

I have a tensorflow array and I want to convert each one of it's 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 the conversion, the resulting array should be

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

In order to do that, I tried to use tf.map_fn as 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 would be the correct way to do that? I was basically trying to follow the usage from here.

P.S. my arrays are actually 3D, I just used 1D as an example since the code fails in that case as well.

like image 438
Miriam Farber Avatar asked Mar 07 '23 03:03

Miriam Farber


1 Answers

You should use 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))
like image 144
gdelab Avatar answered May 10 '23 16:05

gdelab