Tensorflow 将 op 应用于二维张量的每个元素

Tensorflow apply op to each element of a 2d tensor

我想要的是能够将 tensorflow op 应用于 2d 张量的每个元素,例如

input = tf.Variable([[1.0, 2.0], [3.0, 4.0])
myCustomOp = ... # some kind of custom op that operates on 1D tensors
finalResult = tf.[thing I'm after](input, myCustomOp)
# when run final result should look like: [myCustomOp([1.0, 2.0]), myCustomOp([3.0, 4.0)]

有什么想法吗?

TensorFlow 的下一版本(0.8,如果您从源代码构建或下载每晚构建,则当前可用)包括 higher-order operators including tf.map_fn() and tf.scan() 允许您应用 函数 由对较大张量的子张量的 TensorFlow 操作组成。

tf.map_fn(fn, elems, ...) 函数将 N 维输入 elems 沿第一个维度解包为多个 N-1 维子张量,并将 fn 应用于每个子张量。这似乎非常适合您的用例:

input = tf.Variable([[1.0, 2.0], [3.0, 4.0]])
function_to_map = lambda x: f(x)  # Where `f` instantiates myCustomOp.
final_result = tf.map_fn(function_to_map, input)