我有一个tensorflow数组,我想使用字典将它的每个元素转换为另一个元素。
这是我的阵列:
elems = tf.convert_to_tensor(np.array([1, 2, 3, 4, 5, 6]))
这是字典:
d = {1:1,2:5,3:7,4:5,5:8,6:2}
转换后,生成的数组应为
tf.convert_to_tensor(np.array([1, 5, 7, 5, 8, 2]))
为了做到这一点,我尝试使用
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))
运行上述代码时,出现以下错误:
squares = tf.map_fn(lambda x: d[x], elems) KeyError: <tf.Tensor 'map/while/TensorArrayReadV3:0' shape=() dtype=int64>
正确的方法是什么?我基本上是想了解
here
.
P、 我的数组实际上是3D的,我只是以1D为例,因为这种情况下代码也会失败。