使用字典转换tensorflow数组中的元素

Mir*_*ber 4 python arrays numpy machine-learning tensorflow

我有一个tensorflow数组,我想使用字典将它的每个元素转换为另一个元素.

这是我的数组:

elems = tf.convert_to_tensor(np.array([1, 2, 3, 4, 5, 6]))
Run Code Online (Sandbox Code Playgroud)

这是字典:

d = {1:1,2:5,3:7,4:5,5:8,6:2}
Run Code Online (Sandbox Code Playgroud)

转换后,生成的数组应该是

tf.convert_to_tensor(np.array([1, 5, 7, 5, 8, 2]))
Run Code Online (Sandbox Code Playgroud)

为了做到这一点,我尝试使用tf.map_fn如下:

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))
Run Code Online (Sandbox Code Playgroud)

当我运行上面的代码时,我收到以下错误:

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

这样做的正确方法是什么?我基本上试图从这里开始使用.

PS我的阵列实际上是3D,我只使用1D作为例子,因为在这种情况下代码也失败了.

gde*_*lab 7

你应该使用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))
Run Code Online (Sandbox Code Playgroud)