Miriam Farber
Miriam Farber

Reputation: 19634

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.

Upvotes: 4

Views: 3231

Answers (1)

gdelab
gdelab

Reputation: 6220

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))

Upvotes: 7

Related Questions