tensorflow - map_fn to do computation on every possible combination of two tensors

家住魔仙堡 提交于 2019-12-24 07:09:53

问题


does anyone know how to use map_fn or any other tensorflow-func to do a computation on every combination of two input-tensors?

So what i want is something like this: Having two arrays ([1,2] and [4,5]) i want as a result a matrix with the output of the computation (e.g. add) on every possible combination of the two arrays. So the result would be:

[[5,6],
 [6,7]]

I used map_fn but this only takes the elements index-wise:

[[5]
 [7]]

Has anyone an idea how implement this?

Thanks


回答1:


You can add new unit dimensions to each Tensor, then rely on broadcasting addition:

import tensorflow as tf
import tensorflow.contrib.eager as tfe
tfe.enable_eager_execution()
first = tf.constant([1, 2])
second = tf.constant([4, 5])
print(first[None, :] + second[:, None])

Prints:

tf.Tensor(
[[5 6]
 [6 7]], shape=(2, 2), dtype=int32)


来源:https://stackoverflow.com/questions/47794516/tensorflow-map-fn-to-do-computation-on-every-possible-combination-of-two-tenso

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!