访问张量的元素

Access elements of a Tensor

我有以下 TensorFlow 张量。

tensor1 = tf.constant(np.random.randint(0,255, (2,512,512,1)), dtype='int32') #All elements in range [0,255]
tensor2 = tf.constant(np.random.randint(0,255, (2,512,512,1)), dtype='int32') #All elements in range [0,255]

tensor3 = tf.keras.backend.flatten(tensor1)
tensor4 = tf.keras.backend.flatten(tensor2)

tensor5 = tf.constant(np.random.randint(0,255, (255,255)), dtype='int32') #All elements in range [0,255]

我想用tensor 3和tensor 4中存储的值做一个tuple,查询tensor 5中tuple给定位置的元素,比如tensor 3的第0个元素,即tensor3 [0]=5 且张量 4[0]=99。 所以元组变成了 (5,99)。我想在张量5中查找元素(5,99)的值。我想以批处理的方式对Tensor3和Tensor4中的所有元素进行查找。也就是说,我不想遍历 (len(Tensor3)) 范围内的所有值。我做了以下事情来实现这一点。

tensor6 = tensor5[tensor3[0],tensor4[0]]

但是 tensor6 的形状为 (255,255),而我希望获得形状为 (len(tensor3),len(tensor3)) 的张量。我想在 len(tensor3) 的所有可能位置评估 tensor5。那是在 (0,0),...(1000,1000),....(2000,2000),...。我使用的是 TensorFlow 版本 1.12.0。我怎样才能做到这一点?

我已经设法让一些东西在 Tensorflow v 1.12 中运行,但请告诉我它是否是预期的代码:

import tensorflow as tf
print(tf.__version__)
import numpy as np

tensor1 = tf.constant(np.random.randint(0,255, (2,512,512,1)), dtype='int32') #All elements in range [0,255]
tensor2 = tf.constant(np.random.randint(0,255, (2,512,512,1)), dtype='int32') #All elements in range [0,255]

tensor3 = tf.keras.backend.flatten(tensor1)
tensor4 = tf.keras.backend.flatten(tensor2)

tensor5 = tf.constant(np.random.randint(0,255, (255,255)), dtype='int32') #All elements in range [0,255]

elems = (tensor3, tensor4)
a = tf.map_fn(lambda x: tensor5[x[0], x[1]], elems, dtype=tf.int32)

print(tf.Session().run(a))

根据下面的评论,我想为代码中使用的 map_fn 添加一个解释。由于 for 循环在没有 eager_execution 的情况下不受支持,因此 map_fn (有点)等同于 for 循环。

A map_fn 具有以下参数:operation_performedinput_argumentsoptional_dtype。在引擎盖下发生的是 for 循环是 运行 沿着 input_arguments 中值的长度(它必须包含一个可迭代对象)然后对于获得的每个值 operation_performed 执行。如需进一步说明,请参阅 docs.

函数参数的名称是我解释它们的方式,正如我想理解的那样,官方文档中没有给出。 :)