如何使用字典将包含 N int 的 1 阶张量修改为包含 N 大小为 M 的向量的 2 阶张量
在Python中类似:
dict = {1 : [1,2,3] , 2 : [3,2,1]}
array1 = np.array([1,1,2,1,2])
array2 = np.array([dict[x] for x in array1])
但我无法迭代张量(除了 while 循环,但我不认为这是最佳解决方案)
最佳答案
如果你的字典是这样的
dict = {1: tf.constant([1, 2, 3]), 2: tf.constant([1, 2, 3])}
tensor1 = tf.constant([1, 1, 2, 1, 2])
那么像这样的事情应该可以完成工作:
vals = [dict[tensor1[k]] for k in range(tensor1.get_shape().as_list()[0])]
tensor2 = tf.stack(vals, axis=0)
如果尺寸未知,事情会变得更加复杂。例如,如果 tensor1 的形状未知,我看不到不涉及 tf.while_loop 的解决方案。
关于python - tensorflow 中的等效列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44284477/